From a179703a69616084c150019141aea26b8727f634 Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 11:24:05 -0600 Subject: [PATCH 01/11] clean up three-vrm source map - commit 0d9e74022e33279033d4667ecddcc5595c7ad5ce from XRPackage --- vrarmik/three-vrm.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vrarmik/three-vrm.js b/vrarmik/three-vrm.js index 65e3338..0dea3c6 100644 --- a/vrarmik/three-vrm.js +++ b/vrarmik/three-vrm.js @@ -4215,5 +4215,4 @@ module.exports = THREE; /***/ }) -/******/ }); -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fX3RocmVlX3ZybV9fL3dlYnBhY2svYm9vdHN0cmFwIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvYXNzaWduLnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvaW5kZXgudHMiLCJ3ZWJwYWNrOi8vX190aHJlZV92cm1fXy8uL3NyYy92cm0vVlJNLnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvdnJtL1ZSTUltcG9ydGVyLnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvdnJtL2JsZW5kc2hhcGUvVlJNQmxlbmRTaGFwZUdyb3VwLnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvdnJtL2JsZW5kc2hhcGUvVlJNQmxlbmRTaGFwZUltcG9ydGVyLnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvdnJtL2JsZW5kc2hhcGUvVlJNQmxlbmRTaGFwZVByb3h5LnRzIiwid2VicGFjazovL19fdGhyZWVfdnJtX18vLi9zcmMvdnJtL2JsZW5kc2hhcGUvaW5kZXgudHMiLCJ3ZWJwYWNrOi8vX190aHJlZV92cm1fXy8uL3NyYy92cm0vZGVidWcvVlJ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JbmRleCA9IGJpbmQuaW5kZXg7XG4gICAgICAgICAgICBpZiAoXG4gICAgICAgICAgICAgICFwcmltaXRpdmVzLmV2ZXJ5KFxuICAgICAgICAgICAgICAgIChwcmltaXRpdmUpID0+XG4gICAgICAgICAgICAgICAgICBBcnJheS5pc0FycmF5KHByaW1pdGl2ZS5tb3JwaFRhcmdldEluZmx1ZW5jZXMpICYmXG4gICAgICAgICAgICAgICAgICBtb3JwaFRhcmdldEluZGV4IDwgcHJpbWl0aXZlLm1vcnBoVGFyZ2V0SW5mbHVlbmNlcy5sZW5ndGgsXG4gICAgICAgICAgICAgIClcbiAgICAgICAgICAgICkge1xuICAgICAgICAgICAgICBjb25zb2xlLndhcm4oXG4gICAgICAgICAgICAgICAgYFZSTUJsZW5kU2hhcGVJbXBvcnRlcjogJHtzY2hlbWFHcm91cC5uYW1lfSBhdHRlbXB0cyB0byBpbmRleCAke21vcnBoVGFyZ2V0SW5kZXh9dGggbW9ycGggYnV0IG5vdCBmb3VuZC5gLFxuICAgICAgICAgICAgICApO1xuICAgICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGdyb3VwLmFkZEJpbmQoe1xuICAgICAgICAgICAgICBtZXNoZXM6IHByaW1pdGl2ZXMsXG4gICAgICAgICAgICAgIG1vcnBoVGFyZ2V0SW5kZXgsXG4gICAgICAgICAgICAgIHdlaWdodDogYmluZC53ZWlnaHQgfHwgMTAwLFxuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgfSk7XG4gICAgICAgIH1cblxuICAgICAgICBjb25zdCBtYXRlcmlhbFZhbHVlcyA9IHNjaGVtYUdyb3VwLm1hdGVyaWFsVmFsdWVzO1xuICAgICAgICBpZiAobWF0ZXJpYWxWYWx1ZXMpIHtcbiAgICAgICAgICBtYXRlcmlhbFZhbHVlcy5mb3JFYWNoKChtYXRlcmlhbFZhbHVlKSA9PiB7XG4gICAgICAgICAgICBpZiAoXG4gICAgICAgICAgICAgIG1hdGVyaWFsVmFsdWUubWF0ZXJpYWxOYW1lID09PSB1bmRlZmluZWQgfHxcbiAgICAgICAgICAgICAgbWF0ZXJpYWxWYWx1ZS5wcm9wZXJ0eU5hbWUgPT09IHVuZGVmaW5lZCB8fFxuICAgICAgICAgICAgICBtYXRlcmlhbFZhbHVlLnRhcmdldFZhbHVlID09PSB1bmRlZmluZWRcbiAgICAgICAgICAgICkge1xuICAgICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGNvbnN0IG1hdGVyaWFsczogVEhSRUUuTWF0ZXJpYWxbXSA9IFtdO1xuICAgICAgICAgICAgZ2x0Zi5zY2VuZS50cmF2ZXJzZSgob2JqZWN0KSA9PiB7XG4gICAgICAgICAgICAgIGlmICgob2JqZWN0IGFzIGFueSkubWF0ZXJpYWwpIHtcbiAgICAgICAgICAgICAgICBjb25zdCBtYXRlcmlhbDogVEhSRUUuTWF0ZXJpYWxbXSB8IFRIUkVFLk1hdGVyaWFsID0gKG9iamVjdCBhcyBhbnkpLm1hdGVyaWFsO1xuICAgICAgICAgICAgICAgIGlmIChBcnJheS5pc0FycmF5KG1hdGVyaWFsKSkge1xuICAgICAgICAgICAgICAgICAgbWF0ZXJpYWxzLnB1c2goXG4gICAgICAgICAgICAgICAgICAgIC4uLm1hdGVyaWFsLmZpbHRlcihcbiAgICAgICAgICAgICAgICAgICAgICAobXRsKSA9PiBtdGwubmFtZSA9PT0gbWF0ZXJpYWxWYWx1ZS5tYXRlcmlhbE5hbWUhICYmIG1hdGVyaWFscy5pbmRleE9mKG10bCkgPT09IC0xLFxuICAgICAgICAgICAgICAgICAgICApLFxuICAgICAgICAgICAgICAgICAgKTtcbiAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKG1hdGVyaWFsLm5hbWUgPT09IG1hdGVyaWFsVmFsdWUubWF0ZXJpYWxOYW1lICYmIG1hdGVyaWFscy5pbmRleE9mKG1hdGVyaWFsKSA9PT0gLTEpIHtcbiAgICA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gICAgaHVtYW5Cb25lQXJyYXkucHVzaCh7XG4gICAgICAgICAgICBuYW1lOiBib25lLmJvbmUsXG4gICAgICAgICAgICBib25lOiBuZXcgVlJNSHVtYW5Cb25lKG5vZGUsIHtcbiAgICAgICAgICAgICAgYXhpc0xlbmd0aDogYm9uZS5heGlzTGVuZ3RoLFxuICAgICAgICAgICAgICBjZW50ZXI6IGJvbmUuY2VudGVyICYmIG5ldyBUSFJFRS5WZWN0b3IzKGJvbmUuY2VudGVyLngsIGJvbmUuY2VudGVyLnksIGJvbmUuY2VudGVyLnopLFxuICAgICAgICAgICAgICBtYXg6IGJvbmUubWF4ICYmIG5ldyBUSFJFRS5WZWN0b3IzKGJvbmUubWF4LngsIGJvbmUubWF4LnksIGJvbmUubWF4LnopLFxuICAgICAgICAgICAgICBtaW46IGJvbmUubWluICYmIG5ldyBUSFJFRS5WZWN0b3IzKGJvbmUubWluLngsIGJvbmUubWluLnksIGJvbmUubWluLnopLFxuICAgICAgICAgICAgICB1c2VEZWZhdWx0VmFsdWVzOiBib25lLnVzZURlZmF1bHRWYWx1ZXMsXG4gICAgICAgICAgICB9KSxcbiAgICAgICAgICB9KTtcbiAgICAgICAgfSksXG4gICAgICApO1xuICAgIH1cblxuICAgIGNvbnN0IGh1bWFuRGVzY3JpcHRpb246IFZSTUh1bWFuRGVzY3JpcHRpb24gPSB7XG4gICAgICBhcm1TdHJldGNoOiBzY2hlbWFIdW1hbm9pZC5hcm1TdHJldGNoLFxuICAgICAgbGVnU3RyZXRjaDogc2NoZW1hSHVtYW5vaWQubGVnU3RyZXRjaCxcbiAgICAgIHVwcGVyQXJtVHdpc3Q6IHNjaGVtYUh1bWFub2lkLnVwcGVyQXJtVHdpc3QsXG4gICAgICBsb3dlckFybVR3aXN0OiBzY2hlbWFIdW1hbm9pZC5sb3dlckFybVR3aXN0LFxuICAgICAgdXBwZXJMZWdUd2lzdDogc2NoZW1hSHVtYW5vaWQudXBwZXJMZWdUd2lzdCxcbiAgICAgIGx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b29rQXRIb3Jpem9udGFsSW5uZXI7XG4gICAgY29uc3QgbG9va0F0SG9yaXpvbnRhbE91dGVyID0gc2NoZW1hRmlyc3RQZXJzb24ubG9va0F0SG9yaXpvbnRhbE91dGVyO1xuICAgIGNvbnN0IGxvb2tBdFZlcnRpY2FsRG93biA9IHNjaGVtYUZpcnN0UGVyc29uLmxvb2tBdFZlcnRpY2FsRG93bjtcbiAgICBjb25zdCBsb29rQXRWZXJ0aWNhbFVwID0gc2NoZW1hRmlyc3RQZXJzb24ubG9va0F0VmVydGljYWxVcDtcblxuICAgIHN3aXRjaCAoc2NoZW1hRmlyc3RQZXJzb24ubG9va0F0VHlwZU5hbWUpIHtcbiAgICAgIGNhc2UgVlJNU2NoZW1hLkZpcnN0UGVyc29uTG9va0F0VHlwZU5hbWUuQm9uZToge1xuICAgICAgICBpZiAoXG4gICAgICAgICAgbG9va0F0SG9yaXpvbnRhbElubmVyID09PSB1bmRlZmluZWQgfHxcbiAgICAgICAgICBsb29rQXRIb3Jpem9udGFsT3V0ZXIgPT09IHVuZGVmaW5lZCB8fFxuICAgICAgICAgIGxvb2tBdFZlcnRpY2FsRG93biA9PT0gdW5kZWZpbmVkIHx8XG4gICAgICAgICAgbG9va0F0VmVydGljYWxVcCA9PT0gdW5kZWZpbmVkXG4gICAgICAgICkge1xuICAgICAgICAgIHJldHVybiBudWxsO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIHJldHVybiBuZXcgVlJNTG9va0F0Qm9uZUFwcGx5ZXIoXG4gICAgICAgICAgICBodW1hbm9pZCxcbiAgICAgICAgICAgIHRoaXMuX2ltcG9ydEN1cnZlTWFwcGVyQm9uZShsb29rQXRIb3Jpem9udGFsSW5uZXIpLFxuICAgICAgICAgICAgdGhpcy5faW1wb3J0Q3VydmVNYXBwZXJCb25lKGxvb2tBdEhvcml6b250YWxPdXRlciksXG4gICAgICAgICAgICB0aGlzLl9pbXBvcnRDdXJ2ZU1hcHBlckJvbmUobG9va0F0VmV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dWVzdEVudk1hcCkge1xuICAgICAgICAgICAgICB0aGlzLl9yZXF1ZXN0RW52TWFwKCkudGhlbigoZW52TWFwKSA9PiB7XG4gICAgICAgICAgICAgICAgKHZybU1hdGVyaWFscy5zdXJmYWNlIGFzIGFueSkuZW52TWFwID0gZW52TWFwO1xuICAgICAgICAgICAgICAgIHZybU1hdGVyaWFscy5zdXJmYWNlLm5lZWRzVXBkYXRlID0gdHJ1ZTtcbiAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIC8vIHJlbmRlciBvcmRlclxuICAgICAgICAgICAgcHJpbWl0aXZlLnJlbmRlck9yZGVyID0gcHJvcHMucmVuZGVyUXVldWUgfHwgMjAwMDtcblxuICAgICAgICAgICAgLy8gb3V0bGluZSAoXCIyIHBhc3Mgc2hhZGluZyB1c2luZyBncm91cHNcIiB0cmljayBoZXJlKVxuICAgICAgICAgICAgaWYgKHZybU1hdGVyaWFscy5vdXRsaW5lKSB7XG4gICAgICAgICAgICAgIHByaW1pdGl2ZS5tYXRlcmlhbFsxXSA9IHZybU1hdGVyaWFscy5vdXRsaW5lO1xuICAgICAgICAgICAgICAocHJpbWl0aXZlLmdlb21ldHJ5IGFzIFRIUkVFLkJ1ZmZlckdlb21ldHJ5KS5hZGRHcm91cChcbiAgICAgICAgICAgICAgICAwLFxuICAgICAgICAgICAgICAgIChwcmltaXRpdmUuZ2VvbWV0cnkgYXMgVEhSRUUuQnVmZmVyR2VvbWV0cnkpLmluZGV4LmNvdW50LFxuICAgICAgICAgICAgICAgIDEsXG4gICAgICAgICAgICAgICk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfSksXG4gICAgICAgICk7XG4gICAgICB9KSxcbiAgICApO1xuXG4gICAgcmV0dXJuIG1hdGVyaWFscztcbiAgfVxuXG4gIHB1YmxpYyBhc3luYyBjcmVhdGVWUk1NYXRlcmlhbHMoXG4gICAgb3JpZ2luYWxNYXRlcmlhbDogVEhSRUUuTWF0Z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NpdGlvbi5zZXRGcm9tTWF0cml4UG9zaXRpb24odGhpcy5ib25lLm1hdHJpeFdvcmxkKTtcbiAgICBjb25zdCBzdGlmZm5lc3MgPSB0aGlzLnN0aWZmbmVzc0ZvcmNlICogZGVsdGE7XG4gICAgY29uc3QgZXh0ZXJuYWwgPSBfdjNCLmNvcHkodGhpcy5ncmF2aXR5RGlyKS5tdWx0aXBseVNjYWxhcih0aGlzLmdyYXZpdHlQb3dlciAqIGRlbHRhKTtcblxuICAgIC8vIHZlcmxldOepjeWIhuOBp+asoeOBruS9jee9ruOCkuioiOeul1xuICAgIHRoaXMuX25leHRUYWlsXG4gICAgICAuY29weSh0aGlzLl9jdXJyZW50VGFpbClcbiAgICAgIC5hZGQoXG4gICAgICAgIF92M0FcbiAgICAgICAgICAuY29weSh0aGlzLl9jdXJyZW50VGFpbClcbiAgICAgICAgICAuc3ViKHRoaXMuX3ByZXZUYWlsKVxuICAgICAgICAgIC5tdWx0aXBseVNjYWxhcigxIC0gdGhpcy5kcmFnRm9yY2UpLFxuICAgICAgKSAvLyDliY3jg5Xjg6zjg7zjg6Djga7np7vli5XjgpLntpnntprjgZnjgoso5rib6KGw44KC44GC44KL44KIKVxuICAgICAgLmFkZChcbiAgICAgICAgX3YzQVxuICAgICAgICAgIC5jb3B5KHRoaXMuX2JvbmVBeGlzKVxuICAgICAgICAgIC5hcHBseU1hdHJpeDQodGhpcy5faW5pdGlhbExvY2FsTWF0cml4KVxuICAgICAgICAgIC5hcHBseU1hdHJpeDQodGhpcy5fZ2V0UGFyZW50TWF0cml4V29ybGQoKSlcbiAgICAgICAgICAuc3ViKHRoaXMuX3dvcmxkUG9zaXRpb24pXG4gICAgICAgICAgLm5vcm1hbGl6ZSgpXG4gICAgICAgICAgLm11bHRpcGx5U2NhbGFyKHN0aWZmbmVzcyksXG4gICAgICApIC8vIOimquOBruWbnui7ouOBq+OCiOOCi+WtkOODnOODvOODs+OBruenu+WLleebruaomVxuICAgICAgLmFkZChleHRlcm5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pZGVyTWVzaFtdID0gW107XG4gICAgICB2cm1Cb25lR3JvdXAuY29sbGlkZXJHcm91cHMuZm9yRWFjaCgoY29sbGlkZXJJbmRleCkgPT4ge1xuICAgICAgICBjb2xsaWRlcnMucHVzaCguLi5jb2xsaWRlckdyb3Vwc1tjb2xsaWRlckluZGV4XS5jb2xsaWRlcnMpO1xuICAgICAgfSk7XG5cbiAgICAgIGNvbnN0IHNwcmluZ0JvbmVHcm91cDogVlJNU3ByaW5nQm9uZUdyb3VwID0gW107XG4gICAgICB2cm1Cb25lR3JvdXAuYm9uZXMuZm9yRWFjaChhc3luYyAobm9kZUluZGV4KSA9PiB7XG4gICAgICAgIC8vIFZSTeOBruaDheWgseOBi+OCieOAjOaPuuOCjOODouODjuOAjeODnOODvOODs+OBruODq+ODvOODiOOBjOWPluOCjOOCi1xuICAgICAgICBjb25zdCBzcHJpbmdSb290Qm9uZTogR0xURk5vZGUgPSBhd2FpdCBnbHRmLnBhcnNlci5nZXREZXBlbmRlbmN5KCdub2RlJywgbm9kZUluZGV4KTtcblxuICAgICAgICAvLyBpdCdzIHdlaXJkIGJ1dCB0aGVyZSBtaWdodCBiZSBjYXNlcyB3ZSBjYW4ndCBmaW5kIHRoZSByb290IGJvbmVcbiAgICAgICAgaWYgKCFzcHJpbmdSb290Qm9uZSkge1xuICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuXG4gICAgICAgIHNwcmluZ1Jvb3RCb25lLnRyYXZlcnNlKChib25lKSA9PiB7XG4gICAgICAgICAgY29uc3Qgc3ByaW5nQm9uZSA9IHRoaXMuX2NyZWF0ZVNwcmluZ0JvbmUoXG4gICAgICAgICAgICBnbHRmLFxuICAgICAgICAgICAgYm9uZSxcbiAgICAgICAgICAgIGhpdFJhZGl1cyxcbiAgICAgICAgICAgIHN0aWZmaW5lc3MsXG4gICAgICAgICAgICBncmF2aXR5RGlyLFxuICAgICAgICAgICAgZ3Jhdml0eVBvd2VyLFxuICAgICAgICAgICAgZHJhZ0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uc3QgY29sbGlkZXJHcm91cHM6IFZSTVNwcmluZ0JvbmVDb2xsaWRlckdyb3VwW10gPSBbXTtcbiAgICB2cm1Db2xsaWRlckdyb3Vwcy5mb3JFYWNoKGFzeW5jIChjb2xsaWRlckdyb3VwKSA9PiB7XG4gICAgICBpZiAoY29sbGlkZXJHcm91cC5ub2RlID09PSB1bmRlZmluZWQgfHwgY29sbGlkZXJHcm91cC5jb2xsaWRlcnMgPT09IHVuZGVmaW5lZCkge1xuICAgICAgICByZXR1cm47XG4gICAgICB9XG5cbiAgICAgIGNvbnN0IGJvbmUgPSBhd2FpdCBnbHRmLnBhcnNlci5nZXREZXBlbmRlbmN5KCdub2RlJywgY29sbGlkZXJHcm91cC5ub2RlKTtcbiAgICAgIGNvbnN0IGNvbGxpZGVyczogVlJNU3ByaW5nQm9uZUNvbGxpZGVyTWVzaFtdID0gW107XG4gICAgICBjb2xsaWRlckdyb3VwLmNvbGxpZGVycy5mb3JFYWNoKChjb2xsaWRlcikgPT4ge1xuICAgICAgICBpZiAoXG4gICAgICAgICAgY29sbGlkZXIub2Zmc2V0ID09PSB1bmRlZmluZWQgfHxcbiAgICAgICAgICBjb2xsaWRlci5vZmZzZXQueCA9PT0gdW5kZWZpbmVkIHx8XG4gICAgICAgICAgY29sbGlkZXIub2Zmc2V0LnkgPT09IHVuZGVmaW5lZCB8fFxuICAgICAgICAgIGNvbGxpZGVyLm9mZnNldC56ID09PSB1bmRlZmluZWQgfHxcbiAgICAgICAgICBjb2xsaWRlci5yYWRpdXMgPT09IHVuZGVmaW5lZFxuICAgICAgICApIHtcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cblxuICAgICAgICBjb25zdCBvZmZzZXRNYXRyaXggPSBuZXcgVEhSRUUuTWF0cml4NCgpLm1ha2VUcmFuc2xhdGlvbihcbiAgICAgICAgICBjb2xsaWRlci5vZmZzZXQueCxcbiAgICAgICAgICBjb2xsaWRlci5vZmZzZXQueSxcbiAgICAgICAgICAtY29sbGl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RyaXhXb3JsZC5kZWNvbXBvc2UoX3Bvc2l0aW9uLCBvdXQsIF9zY2FsZSk7XG4gIHJldHVybiBvdXQ7XG59XG4iLCJleHBvcnQgZnVuY3Rpb24gcmVuYW1lTWF0ZXJpYWxQcm9wZXJ0eShuYW1lOiBzdHJpbmcpOiBzdHJpbmcge1xuICBpZiAobmFtZVswXSAhPT0gJ18nKSB7XG4gICAgY29uc29sZS53YXJuKGByZW5hbWVNYXRlcmlhbFByb3BlcnR5OiBHaXZlbiBwcm9wZXJ0eSBuYW1lIFwiJHtuYW1lfVwiIG1pZ2h0IGJlIGludmFsaWRgKTtcbiAgICByZXR1cm4gbmFtZTtcbiAgfVxuICBuYW1lID0gbmFtZS5zdWJzdHJpbmcoMSk7XG5cbiAgaWYgKCEvW0EtWl0vLnRlc3QobmFtZVswXSkpIHtcbiAgICBjb25zb2xlLndhcm4oYHJlbmFtZU1hdGVyaWFsUHJvcGVydHk6IEdpdmVuIHByb3BlcnR5IG5hbWUgXCIke25hbWV9XCIgbWlnaHQgYmUgaW52YWxpZGApO1xuICAgIHJldHVybiBuYW1lO1xuICB9XG4gIHJldHVybiBuYW1lWzBdLnRvTG93ZXJDYXNlKCkgKyBuYW1lLnN1YnN0cmluZygxKTtcbn1cbiIsIm1vZHVsZS5leHBvcnRzID0gVEhSRUU7Il0sInNvdXJjZVJvb3QiOiIifQ== \ No newline at end of file +/******/ }); \ No newline at end of file From 7cb0f67bdfdecfdceb33c4d1186cfa38a82f136f Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 11:27:24 -0600 Subject: [PATCH 02/11] clean up avatar wrist rotation - commit a713666ebe818be02441ccd3dd4f703a59a8e2eb from XRPackage small avatars code cleanup - commit aa2c0ddf69855415a0a1979f60ccf8056fdf345b from XRPackage Clean up spring bone manager promise - commit f930d12b4e8f468141ddce708a1f0474e7c6f78e from XRPackage --- avatars.js | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/avatars.js b/avatars.js index 7fb0049..8e08448 100644 --- a/avatars.js +++ b/avatars.js @@ -1,3 +1,4 @@ +import THREE from '../three.module.js'; import './vrarmik/three-vrm.js'; import {fixSkeletonZForward} from './vrarmik/SkeletonUtils.js'; import PoseManager from './vrarmik/PoseManager.js'; @@ -8,8 +9,8 @@ import skeletonString from './skeleton.js'; const zeroVector = new THREE.Vector3(); const upRotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI/2); -const leftRotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI*0.8); -const rightRotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -Math.PI*0.8); +const leftRotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI*0.5); +const rightRotation = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -Math.PI*0.5); const z180Quaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI); const localVector = new THREE.Vector3(); @@ -61,7 +62,7 @@ const _copySkeleton = (src, dst) => { }; const cubeGeometry = new THREE.ConeBufferGeometry(0.05, 0.2, 3) - .applyMatrix(new THREE.Matrix4().makeRotationFromQuaternion( + .applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion( new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1))) ); const cubeMaterials ={}; @@ -540,6 +541,7 @@ class Avatar { this.hairBones = hairBones; this.springBoneManager = null; + let springBoneManagerPromise = null; if (options.hair) { new Promise((accept, reject) => { if (!object) { @@ -594,7 +596,7 @@ class Avatar { }; } - new THREE.VRMSpringBoneImporter().import(object) + springBoneManagerPromise = new THREE.VRMSpringBoneImporter().import(object) .then(springBoneManager => { this.springBoneManager = springBoneManager; }); @@ -871,7 +873,13 @@ class Avatar { this.decapitated = false; if (options.decapitate) { - this.decapitate(); + if (springBoneManagerPromise) { + springBoneManagerPromise.then(() => { + this.decapitate(); + }); + } else { + this.decapitate(); + } } } initializeBonePositions(setups) { From f81e95cdeafad8c2348d4bd27baea8198037addc Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 11:47:22 -0600 Subject: [PATCH 03/11] GLTFLoader.js from Add GLTFLoader.js - commit 2c481b61fbdffcc2c40a8c67887f2c8c056ff455 from XRPackage --- GLTFLoader.js | 1213 ++++++++++++++++++++++++++----------------------- 1 file changed, 638 insertions(+), 575 deletions(-) diff --git a/GLTFLoader.js b/GLTFLoader.js index 8c31d19..0189341 100644 --- a/GLTFLoader.js +++ b/GLTFLoader.js @@ -6,18 +6,81 @@ * @author Don McCurdy / https://www.donmccurdy.com */ -THREE.GLTFLoader = ( function () { +import { + AnimationClip, + Bone, + Box3, + BufferAttribute, + BufferGeometry, + ClampToEdgeWrapping, + Color, + DirectionalLight, + DoubleSide, + FileLoader, + FrontSide, + Group, + InterleavedBuffer, + InterleavedBufferAttribute, + Interpolant, + InterpolateDiscrete, + InterpolateLinear, + Line, + LineBasicMaterial, + LineLoop, + LineSegments, + LinearFilter, + LinearMipmapLinearFilter, + LinearMipmapNearestFilter, + Loader, + LoaderUtils, + Material, + MathUtils, + Matrix4, + Mesh, + MeshBasicMaterial, + MeshStandardMaterial, + MirroredRepeatWrapping, + NearestFilter, + NearestMipmapLinearFilter, + NearestMipmapNearestFilter, + NumberKeyframeTrack, + Object3D, + OrthographicCamera, + PerspectiveCamera, + PointLight, + Points, + PointsMaterial, + PropertyBinding, + QuaternionKeyframeTrack, + RGBAFormat, + RGBFormat, + RepeatWrapping, + Skeleton, + SkinnedMesh, + Sphere, + SpotLight, + TangentSpaceNormalMap, + TextureLoader, + TriangleFanDrawMode, + TriangleStripDrawMode, + Vector2, + Vector3, + VectorKeyframeTrack, + sRGBEncoding +} from "./three.module.js"; + +var GLTFLoader = ( function () { function GLTFLoader( manager ) { - THREE.Loader.call( this, manager ); + Loader.call( this, manager ); this.dracoLoader = null; this.ddsLoader = null; } - GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { + GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: GLTFLoader, @@ -37,7 +100,7 @@ THREE.GLTFLoader = ( function () { } else { - resourcePath = THREE.LoaderUtils.extractUrlBase( url ); + resourcePath = LoaderUtils.extractUrlBase( url ); } @@ -63,7 +126,7 @@ THREE.GLTFLoader = ( function () { }; - var loader = new THREE.FileLoader( scope.manager ); + var loader = new FileLoader( scope.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); @@ -121,7 +184,7 @@ THREE.GLTFLoader = ( function () { } else { - var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); + var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { @@ -140,7 +203,7 @@ THREE.GLTFLoader = ( function () { } else { - content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); + content = LoaderUtils.decodeText( new Uint8Array( data ) ); } @@ -150,7 +213,7 @@ THREE.GLTFLoader = ( function () { if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { - if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) ); + if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); return; } @@ -181,11 +244,15 @@ THREE.GLTFLoader = ( function () { break; case EXTENSIONS.MSFT_TEXTURE_DDS: - extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader ); + extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader ); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: - extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension(); + extensions[ extensionName ] = new GLTFTextureTransformExtension(); + break; + + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); break; default: @@ -263,6 +330,7 @@ THREE.GLTFLoader = ( function () { KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', MSFT_TEXTURE_DDS: 'MSFT_texture_dds' }; @@ -276,7 +344,7 @@ THREE.GLTFLoader = ( function () { if ( ! ddsLoader ) { - throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' ); + throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader' ); } @@ -304,7 +372,7 @@ THREE.GLTFLoader = ( function () { var lightDef = this.lightDefs[ lightIndex ]; var lightNode; - var color = new THREE.Color( 0xffffff ); + var color = new Color( 0xffffff ); if ( lightDef.color !== undefined ) color.fromArray( lightDef.color ); var range = lightDef.range !== undefined ? lightDef.range : 0; @@ -312,18 +380,18 @@ THREE.GLTFLoader = ( function () { switch ( lightDef.type ) { case 'directional': - lightNode = new THREE.DirectionalLight( color ); + lightNode = new DirectionalLight( color ); lightNode.target.position.set( 0, 0, - 1 ); lightNode.add( lightNode.target ); break; case 'point': - lightNode = new THREE.PointLight( color ); + lightNode = new PointLight( color ); lightNode.distance = range; break; case 'spot': - lightNode = new THREE.SpotLight( color ); + lightNode = new SpotLight( color ); lightNode.distance = range; // Handle spotlight properties. lightDef.spot = lightDef.spot || {}; @@ -367,7 +435,7 @@ THREE.GLTFLoader = ( function () { GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { - return THREE.MeshBasicMaterial; + return MeshBasicMaterial; }; @@ -375,7 +443,7 @@ THREE.GLTFLoader = ( function () { var pending = []; - materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); + materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var metallicRoughness = materialDef.pbrMetallicRoughness; @@ -417,7 +485,7 @@ THREE.GLTFLoader = ( function () { var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { - magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), + magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), version: headerView.getUint32( 4, true ), length: headerView.getUint32( 8, true ) }; @@ -428,7 +496,7 @@ THREE.GLTFLoader = ( function () { } else if ( this.header.version < 2.0 ) { - throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' ); + throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' ); } @@ -446,7 +514,7 @@ THREE.GLTFLoader = ( function () { if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); - this.content = THREE.LoaderUtils.decodeText( contentArray ); + this.content = LoaderUtils.decodeText( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { @@ -485,6 +553,7 @@ THREE.GLTFLoader = ( function () { this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; + this.dracoLoader.preload(); } @@ -597,6 +666,158 @@ THREE.GLTFLoader = ( function () { * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness */ + + /** + * A sub class of StandardMaterial with some of the functionality + * changed via the `onBeforeCompile` callback + * @pailhead + */ + + function GLTFMeshStandardSGMaterial( params ) { + + MeshStandardMaterial.call( this ); + + this.isGLTFSpecularGlossinessMaterial = true; + + //various chunks that need replacing + var specularMapParsFragmentChunk = [ + '#ifdef USE_SPECULARMAP', + ' uniform sampler2D specularMap;', + '#endif' + ].join( '\n' ); + + var glossinessMapParsFragmentChunk = [ + '#ifdef USE_GLOSSINESSMAP', + ' uniform sampler2D glossinessMap;', + '#endif' + ].join( '\n' ); + + var specularMapFragmentChunk = [ + 'vec3 specularFactor = specular;', + '#ifdef USE_SPECULARMAP', + ' vec4 texelSpecular = texture2D( specularMap, vUv );', + ' texelSpecular = sRGBToLinear( texelSpecular );', + ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', + ' specularFactor *= texelSpecular.rgb;', + '#endif' + ].join( '\n' ); + + var glossinessMapFragmentChunk = [ + 'float glossinessFactor = glossiness;', + '#ifdef USE_GLOSSINESSMAP', + ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', + ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', + ' glossinessFactor *= texelGlossiness.a;', + '#endif' + ].join( '\n' ); + + var lightPhysicalFragmentChunk = [ + 'PhysicalMaterial material;', + 'material.diffuseColor = diffuseColor.rgb;', + 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', + 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', + 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.', + 'material.specularRoughness += geometryRoughness;', + 'material.specularRoughness = min( material.specularRoughness, 1.0 );', + 'material.specularColor = specularFactor.rgb;', + ].join( '\n' ); + + var uniforms = { + specular: { value: new Color().setHex( 0xffffff ) }, + glossiness: { value: 1 }, + specularMap: { value: null }, + glossinessMap: { value: null } + }; + + this._extraUniforms = uniforms; + + // please see #14031 or #13198 for an alternate approach + this.onBeforeCompile = function ( shader ) { + + for ( var uniformName in uniforms ) { + + shader.uniforms[ uniformName ] = uniforms[ uniformName ]; + + } + + shader.fragmentShader = shader.fragmentShader.replace( 'uniform float roughness;', 'uniform vec3 specular;' ); + shader.fragmentShader = shader.fragmentShader.replace( 'uniform float metalness;', 'uniform float glossiness;' ); + shader.fragmentShader = shader.fragmentShader.replace( '#include ', specularMapParsFragmentChunk ); + shader.fragmentShader = shader.fragmentShader.replace( '#include ', glossinessMapParsFragmentChunk ); + shader.fragmentShader = shader.fragmentShader.replace( '#include ', specularMapFragmentChunk ); + shader.fragmentShader = shader.fragmentShader.replace( '#include ', glossinessMapFragmentChunk ); + shader.fragmentShader = shader.fragmentShader.replace( '#include ', lightPhysicalFragmentChunk ); + + }; + + /*eslint-disable*/ + Object.defineProperties( + this, + { + specular: { + get: function () { return uniforms.specular.value; }, + set: function ( v ) { uniforms.specular.value = v; } + }, + specularMap: { + get: function () { return uniforms.specularMap.value; }, + set: function ( v ) { uniforms.specularMap.value = v; } + }, + glossiness: { + get: function () { return uniforms.glossiness.value; }, + set: function ( v ) { uniforms.glossiness.value = v; } + }, + glossinessMap: { + get: function () { return uniforms.glossinessMap.value; }, + set: function ( v ) { + + uniforms.glossinessMap.value = v; + //how about something like this - @pailhead + if ( v ) { + + this.defines.USE_GLOSSINESSMAP = ''; + // set USE_ROUGHNESSMAP to enable vUv + this.defines.USE_ROUGHNESSMAP = ''; + + } else { + + delete this.defines.USE_ROUGHNESSMAP; + delete this.defines.USE_GLOSSINESSMAP; + + } + + } + } + } + ); + + /*eslint-enable*/ + delete this.metalness; + delete this.roughness; + delete this.metalnessMap; + delete this.roughnessMap; + + this.setValues( params ); + + } + + GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial; + + GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) { + + MeshStandardMaterial.prototype.copy.call( this, source ); + this.specularMap = source.specularMap; + this.specular.copy( source.specular ); + this.glossinessMap = source.glossinessMap; + this.glossiness = source.glossiness; + delete this.metalness; + delete this.roughness; + delete this.metalnessMap; + delete this.roughnessMap; + return this; + + }; + function GLTFMaterialsPbrSpecularGlossinessExtension() { return { @@ -616,6 +837,7 @@ THREE.GLTFLoader = ( function () { 'bumpMap', 'bumpScale', 'normalMap', + 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', @@ -631,7 +853,7 @@ THREE.GLTFLoader = ( function () { getMaterialType: function () { - return THREE.ShaderMaterial; + return GLTFMeshStandardSGMaterial; }, @@ -639,73 +861,7 @@ THREE.GLTFLoader = ( function () { var pbrSpecularGlossiness = materialDef.extensions[ this.name ]; - var shader = THREE.ShaderLib[ 'standard' ]; - - var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); - - var specularMapParsFragmentChunk = [ - '#ifdef USE_SPECULARMAP', - ' uniform sampler2D specularMap;', - '#endif' - ].join( '\n' ); - - var glossinessMapParsFragmentChunk = [ - '#ifdef USE_GLOSSINESSMAP', - ' uniform sampler2D glossinessMap;', - '#endif' - ].join( '\n' ); - - var specularMapFragmentChunk = [ - 'vec3 specularFactor = specular;', - '#ifdef USE_SPECULARMAP', - ' vec4 texelSpecular = texture2D( specularMap, vUv );', - ' texelSpecular = sRGBToLinear( texelSpecular );', - ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', - ' specularFactor *= texelSpecular.rgb;', - '#endif' - ].join( '\n' ); - - var glossinessMapFragmentChunk = [ - 'float glossinessFactor = glossiness;', - '#ifdef USE_GLOSSINESSMAP', - ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', - ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', - ' glossinessFactor *= texelGlossiness.a;', - '#endif' - ].join( '\n' ); - - var lightPhysicalFragmentChunk = [ - 'PhysicalMaterial material;', - 'material.diffuseColor = diffuseColor.rgb;', - 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', - 'material.specularColor = specularFactor.rgb;', - ].join( '\n' ); - - var fragmentShader = shader.fragmentShader - .replace( 'uniform float roughness;', 'uniform vec3 specular;' ) - .replace( 'uniform float metalness;', 'uniform float glossiness;' ) - .replace( '#include ', specularMapParsFragmentChunk ) - .replace( '#include ', glossinessMapParsFragmentChunk ) - .replace( '#include ', specularMapFragmentChunk ) - .replace( '#include ', glossinessMapFragmentChunk ) - .replace( '#include ', lightPhysicalFragmentChunk ); - - delete uniforms.roughness; - delete uniforms.metalness; - delete uniforms.roughnessMap; - delete uniforms.metalnessMap; - - uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) }; - uniforms.glossiness = { value: 0.5 }; - uniforms.specularMap = { value: null }; - uniforms.glossinessMap = { value: null }; - - materialParams.vertexShader = shader.vertexShader; - materialParams.fragmentShader = fragmentShader; - materialParams.uniforms = uniforms; - materialParams.defines = { 'STANDARD': '' }; - - materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); + materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var pending = []; @@ -725,9 +881,9 @@ THREE.GLTFLoader = ( function () { } - materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 ); + materialParams.emissive = new Color( 0.0, 0.0, 0.0 ); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; - materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 ); + materialParams.specular = new Color( 1.0, 1.0, 1.0 ); if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { @@ -747,237 +903,66 @@ THREE.GLTFLoader = ( function () { }, - createMaterial: function ( params ) { - - // setup material properties based on MeshStandardMaterial for Specular-Glossiness - - var material = new THREE.ShaderMaterial( { - defines: params.defines, - vertexShader: params.vertexShader, - fragmentShader: params.fragmentShader, - uniforms: params.uniforms, - fog: true, - lights: true, - opacity: params.opacity, - transparent: params.transparent - } ); + createMaterial: function ( materialParams ) { - material.isGLTFSpecularGlossinessMaterial = true; + var material = new GLTFMeshStandardSGMaterial( materialParams ); + material.fog = true; - material.color = params.color; + material.color = materialParams.color; - material.map = params.map === undefined ? null : params.map; + material.map = materialParams.map === undefined ? null : materialParams.map; material.lightMap = null; material.lightMapIntensity = 1.0; - material.aoMap = params.aoMap === undefined ? null : params.aoMap; + material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; material.aoMapIntensity = 1.0; - material.emissive = params.emissive; + material.emissive = materialParams.emissive; material.emissiveIntensity = 1.0; - material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap; + material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; - material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap; + material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; material.bumpScale = 1; - material.normalMap = params.normalMap === undefined ? null : params.normalMap; + material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; + material.normalMapType = TangentSpaceNormalMap; - if ( params.normalScale ) material.normalScale = params.normalScale; + if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; - material.specularMap = params.specularMap === undefined ? null : params.specularMap; - material.specular = params.specular; + material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; + material.specular = materialParams.specular; - material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap; - material.glossiness = params.glossiness; + material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; + material.glossiness = materialParams.glossiness; material.alphaMap = null; - material.envMap = params.envMap === undefined ? null : params.envMap; + material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; material.envMapIntensity = 1.0; material.refractionRatio = 0.98; - material.extensions.derivatives = true; - return material; }, - /** - * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can - * copy only properties it knows about or inherits, and misses many properties that would - * normally be defined by MeshStandardMaterial. - * - * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of - * loading a glTF model, but cloning later (e.g. by the user) would require these changes - * AND also updating `.onBeforeRender` on the parent mesh. - * - * @param {THREE.ShaderMaterial} source - * @return {THREE.ShaderMaterial} - */ - cloneMaterial: function ( source ) { - - var target = source.clone(); - - target.isGLTFSpecularGlossinessMaterial = true; - - var params = this.specularGlossinessParams; - - for ( var i = 0, il = params.length; i < il; i ++ ) { - - var value = source[ params[ i ] ]; - target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value; - - } - - return target; - - }, - - // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer. - refreshUniforms: function ( renderer, scene, camera, geometry, material ) { - - if ( material.isGLTFSpecularGlossinessMaterial !== true ) { - - return; - - } - - var uniforms = material.uniforms; - var defines = material.defines; - - uniforms.opacity.value = material.opacity; - - uniforms.diffuse.value.copy( material.color ); - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; - - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; - - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; - - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map - - var uvScaleMap; - - if ( material.map ) { - - uvScaleMap = material.map; - - } else if ( material.specularMap ) { - - uvScaleMap = material.specularMap; - - } else if ( material.displacementMap ) { - - uvScaleMap = material.displacementMap; - - } else if ( material.normalMap ) { - - uvScaleMap = material.normalMap; - - } else if ( material.bumpMap ) { - - uvScaleMap = material.bumpMap; - - } else if ( material.glossinessMap ) { - - uvScaleMap = material.glossinessMap; - - } else if ( material.alphaMap ) { - - uvScaleMap = material.alphaMap; - - } else if ( material.emissiveMap ) { - - uvScaleMap = material.emissiveMap; - - } - - if ( uvScaleMap !== undefined ) { - - // backwards compatibility - if ( uvScaleMap.isWebGLRenderTarget ) { - - uvScaleMap = uvScaleMap.texture; - - } - - if ( uvScaleMap.matrixAutoUpdate === true ) { - - uvScaleMap.updateMatrix(); - - } - - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - - } - - if ( material.envMap ) { - - uniforms.envMap.value = material.envMap; - uniforms.envMapIntensity.value = material.envMapIntensity; - - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1; - - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; - - uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel; - - } - - uniforms.specular.value.copy( material.specular ); - uniforms.glossiness.value = material.glossiness; - - uniforms.glossinessMap.value = material.glossinessMap; - - uniforms.emissiveMap.value = material.emissiveMap; - uniforms.bumpMap.value = material.bumpMap; - uniforms.normalMap.value = material.normalMap; - - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; - - if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) { - - defines.USE_GLOSSINESSMAP = ''; - // set USE_ROUGHNESSMAP to enable vUv - defines.USE_ROUGHNESSMAP = ''; - - } - - if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) { - - delete defines.USE_GLOSSINESSMAP; - delete defines.USE_ROUGHNESSMAP; + }; - } + } - } + /** + * Mesh Quantization Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization + */ + function GLTFMeshQuantizationExtension() { - }; + this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } @@ -989,11 +974,11 @@ THREE.GLTFLoader = ( function () { // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } - GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype ); + GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype ); GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) { @@ -1098,18 +1083,18 @@ THREE.GLTFLoader = ( function () { }; var WEBGL_FILTERS = { - 9728: THREE.NearestFilter, - 9729: THREE.LinearFilter, - 9984: THREE.NearestMipmapNearestFilter, - 9985: THREE.LinearMipmapNearestFilter, - 9986: THREE.NearestMipmapLinearFilter, - 9987: THREE.LinearMipmapLinearFilter + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { - 33071: THREE.ClampToEdgeWrapping, - 33648: THREE.MirroredRepeatWrapping, - 10497: THREE.RepeatWrapping + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping }; var WEBGL_TYPE_SIZES = { @@ -1143,8 +1128,8 @@ THREE.GLTFLoader = ( function () { var INTERPOLATION = { CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. - LINEAR: THREE.InterpolateLinear, - STEP: THREE.InterpolateDiscrete + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete }; var ALPHA_MODES = { @@ -1154,8 +1139,8 @@ THREE.GLTFLoader = ( function () { }; var MIME_TYPE_FORMATS = { - 'image/png': THREE.RGBAFormat, - 'image/jpeg': THREE.RGBFormat + 'image/png': RGBAFormat, + 'image/jpeg': RGBFormat }; /* UTILITY FUNCTIONS */ @@ -1186,24 +1171,26 @@ THREE.GLTFLoader = ( function () { } - var defaultMaterial; - /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */ - function createDefaultMaterial() { - - defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( { - color: 0xFFFFFF, - emissive: 0x000000, - metalness: 1, - roughness: 1, - transparent: false, - depthTest: true, - side: THREE.FrontSide - } ); + function createDefaultMaterial( cache ) { + + if ( cache[ 'DefaultMaterial' ] === undefined ) { + + cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { + color: 0xFFFFFF, + emissive: 0x000000, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + } ); + + } - return defaultMaterial; + return cache[ 'DefaultMaterial' ]; } @@ -1225,7 +1212,7 @@ THREE.GLTFLoader = ( function () { } /** - * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object + * @param {Object3D|Material|BufferGeometry} object * @param {GLTF.definition} gltfDef */ function assignExtrasToUserData( object, gltfDef ) { @@ -1249,10 +1236,10 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * - * @param {THREE.BufferGeometry} geometry + * @param {BufferGeometry} geometry * @param {Array} targets * @param {GLTFParser} parser - * @return {Promise} + * @return {Promise} */ function addMorphTargets( geometry, targets, parser ) { @@ -1309,95 +1296,9 @@ THREE.GLTFLoader = ( function () { var morphPositions = accessors[ 0 ]; var morphNormals = accessors[ 1 ]; - // Clone morph target accessors before modifying them. - - for ( var i = 0, il = morphPositions.length; i < il; i ++ ) { - - if ( geometry.attributes.position === morphPositions[ i ] ) continue; - - morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] ); - - } - - for ( var i = 0, il = morphNormals.length; i < il; i ++ ) { - - if ( geometry.attributes.normal === morphNormals[ i ] ) continue; - - morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] ); - - } - - for ( var i = 0, il = targets.length; i < il; i ++ ) { - - var target = targets[ i ]; - var attributeName = 'morphTarget' + i; - - if ( hasMorphPosition ) { - - // Three.js morph position is absolute value. The formula is - // basePosition - // + weight0 * ( morphPosition0 - basePosition ) - // + weight1 * ( morphPosition1 - basePosition ) - // ... - // while the glTF one is relative - // basePosition - // + weight0 * glTFmorphPosition0 - // + weight1 * glTFmorphPosition1 - // ... - // then we need to convert from relative to absolute here. - - if ( target.POSITION !== undefined ) { - - var positionAttribute = morphPositions[ i ]; - positionAttribute.name = attributeName; - - var position = geometry.attributes.position; - - for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) { - - positionAttribute.setXYZ( - j, - positionAttribute.getX( j ) + position.getX( j ), - positionAttribute.getY( j ) + position.getY( j ), - positionAttribute.getZ( j ) + position.getZ( j ) - ); - - } - - } - - } - - if ( hasMorphNormal ) { - - // see target.POSITION's comment - - if ( target.NORMAL !== undefined ) { - - var normalAttribute = morphNormals[ i ]; - normalAttribute.name = attributeName; - - var normal = geometry.attributes.normal; - - for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) { - - normalAttribute.setXYZ( - j, - normalAttribute.getX( j ) + normal.getX( j ), - normalAttribute.getY( j ) + normal.getY( j ), - normalAttribute.getZ( j ) + normal.getZ( j ) - ); - - } - - } - - } - - } - if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; + geometry.morphTargetsRelative = true; return geometry; @@ -1406,7 +1307,7 @@ THREE.GLTFLoader = ( function () { } /** - * @param {THREE.Mesh} mesh + * @param {Mesh} mesh * @param {GLTF.Mesh} meshDef */ function updateMorphTargets( mesh, meshDef ) { @@ -1485,31 +1386,6 @@ THREE.GLTFLoader = ( function () { } - function cloneBufferAttribute( attribute ) { - - if ( attribute.isInterleavedBufferAttribute ) { - - var count = attribute.count; - var itemSize = attribute.itemSize; - var array = attribute.array.slice( 0, count * itemSize ); - - for ( var i = 0, j = 0; i < count; ++ i ) { - - array[ j ++ ] = attribute.getX( i ); - if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i ); - if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i ); - if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i ); - - } - - return new THREE.BufferAttribute( array, itemSize, attribute.normalized ); - - } - - return attribute.clone(); - - } - /* GLTF PARSER */ function GLTFParser( json, extensions, options ) { @@ -1524,10 +1400,10 @@ THREE.GLTFLoader = ( function () { // BufferGeometry caching this.primitiveCache = {}; - this.textureLoader = new THREE.TextureLoader( this.options.manager ); + this.textureLoader = new TextureLoader( this.options.manager ); this.textureLoader.setCrossOrigin( this.options.crossOrigin ); - this.fileLoader = new THREE.FileLoader( this.options.manager ); + this.fileLoader = new FileLoader( this.options.manager ); this.fileLoader.setResponseType( 'arraybuffer' ); if ( this.options.crossOrigin === 'use-credentials' ) { @@ -1605,7 +1481,7 @@ THREE.GLTFLoader = ( function () { } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To - // avoid having more than one THREE.Mesh with the same name, count + // avoid having more than one Mesh with the same name, count // references and rename instances below. // // Example: CesiumMilkTruck sample model reuses "Wheel" meshes. @@ -1645,7 +1521,7 @@ THREE.GLTFLoader = ( function () { * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.getDependency = function ( type, index ) { @@ -1804,7 +1680,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadAccessor = function ( accessorIndex ) { @@ -1870,13 +1746,13 @@ THREE.GLTFLoader = ( function () { array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes ); // Integer parameters to IB/IBA are in array elements, not bytes. - ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes ); + ib = new InterleavedBuffer( array, byteStride / elementBytes ); parser.cache.add( ibCacheKey, ib ); } - bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized ); + bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized ); } else { @@ -1890,7 +1766,7 @@ THREE.GLTFLoader = ( function () { } - bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized ); + bufferAttribute = new BufferAttribute( array, itemSize, normalized ); } @@ -1909,7 +1785,7 @@ THREE.GLTFLoader = ( function () { if ( bufferView !== null ) { // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. - bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized ); + bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized ); } @@ -1945,7 +1821,7 @@ THREE.GLTFLoader = ( function () { var options = this.options; var textureLoader = this.textureLoader; - var URL = window.URL || window.webkitURL; + var URL = globalThis.URL || globalThis.webkitURL; var textureDef = json.textures[ textureIndex ]; @@ -2013,7 +1889,7 @@ THREE.GLTFLoader = ( function () { texture.flipY = false; - if ( textureDef.name !== undefined ) texture.name = textureDef.name; + if ( textureDef.name ) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files. if ( source.mimeType in MIME_TYPE_FORMATS ) { @@ -2025,10 +1901,10 @@ THREE.GLTFLoader = ( function () { var samplers = json.samplers || {}; var sampler = samplers[ textureDef.sampler ] || {}; - texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter; - texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter; - texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping; - texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping; + texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; return texture; @@ -2058,13 +1934,21 @@ THREE.GLTFLoader = ( function () { case 'metalnessMap': case 'normalMap': case 'roughnessMap': - texture.format = THREE.RGBFormat; + texture.format = RGBFormat; break; } } + // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured + // However, we will copy UV set 0 to UV set 1 on demand for aoMap + if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) { + + console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' ); + + } + if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; @@ -2089,13 +1973,12 @@ THREE.GLTFLoader = ( function () { * but reuse of the same glTF material may require multiple threejs materials * to accomodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. - * @param {THREE.Object3D} mesh Mesh, Line, or Points instance. + * @param {Object3D} mesh Mesh, Line, or Points instance. */ GLTFParser.prototype.assignFinalMaterial = function ( mesh ) { var geometry = mesh.geometry; var material = mesh.material; - var extensions = this.extensions; var useVertexTangents = geometry.attributes.tangent !== undefined; var useVertexColors = geometry.attributes.color !== undefined; @@ -2112,8 +1995,8 @@ THREE.GLTFLoader = ( function () { if ( ! pointsMaterial ) { - pointsMaterial = new THREE.PointsMaterial(); - THREE.Material.prototype.copy.call( pointsMaterial, material ); + pointsMaterial = new PointsMaterial(); + Material.prototype.copy.call( pointsMaterial, material ); pointsMaterial.color.copy( material.color ); pointsMaterial.map = material.map; pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px @@ -2132,8 +2015,8 @@ THREE.GLTFLoader = ( function () { if ( ! lineMaterial ) { - lineMaterial = new THREE.LineBasicMaterial(); - THREE.Material.prototype.copy.call( lineMaterial, material ); + lineMaterial = new LineBasicMaterial(); + Material.prototype.copy.call( lineMaterial, material ); lineMaterial.color.copy( material.color ); this.cache.add( cacheKey, lineMaterial ); @@ -2161,13 +2044,11 @@ THREE.GLTFLoader = ( function () { if ( ! cachedMaterial ) { - cachedMaterial = material.isGLTFSpecularGlossinessMaterial - ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material ) - : material.clone(); + cachedMaterial = material.clone(); if ( useSkinning ) cachedMaterial.skinning = true; if ( useVertexTangents ) cachedMaterial.vertexTangents = true; - if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors; + if ( useVertexColors ) cachedMaterial.vertexColors = true; if ( useFlatShading ) cachedMaterial.flatShading = true; if ( useMorphTargets ) cachedMaterial.morphTargets = true; if ( useMorphNormals ) cachedMaterial.morphNormals = true; @@ -2184,15 +2065,14 @@ THREE.GLTFLoader = ( function () { if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) { - console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' ); - geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) ); + geometry.setAttribute( 'uv2', new BufferAttribute( geometry.attributes.uv.array, 2 ) ); } - if ( material.isGLTFSpecularGlossinessMaterial ) { + // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 + if ( material.normalScale && ! useVertexTangents ) { - // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update - mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms; + material.normalScale.y = - material.normalScale.y; } @@ -2203,7 +2083,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadMaterial = function ( materialIndex ) { @@ -2235,11 +2115,11 @@ THREE.GLTFLoader = ( function () { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material - materialType = THREE.MeshStandardMaterial; + materialType = MeshStandardMaterial; var metallicRoughness = materialDef.pbrMetallicRoughness || {}; - materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); + materialParams.color = new Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { @@ -2271,7 +2151,7 @@ THREE.GLTFLoader = ( function () { if ( materialDef.doubleSided === true ) { - materialParams.side = THREE.DoubleSide; + materialParams.side = DoubleSide; } @@ -2281,6 +2161,9 @@ THREE.GLTFLoader = ( function () { materialParams.transparent = true; + // See: https://github.com/mrdoob/three.js/issues/17706 + materialParams.depthWrite = false; + } else { materialParams.transparent = false; @@ -2293,11 +2176,11 @@ THREE.GLTFLoader = ( function () { } - if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { + if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); - materialParams.normalScale = new THREE.Vector2( 1, 1 ); + materialParams.normalScale = new Vector2( 1, 1 ); if ( materialDef.normalTexture.scale !== undefined ) { @@ -2307,7 +2190,7 @@ THREE.GLTFLoader = ( function () { } - if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { + if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) ); @@ -2319,13 +2202,13 @@ THREE.GLTFLoader = ( function () { } - if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) { + if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) { - materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor ); + materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor ); } - if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { + if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) ); @@ -2335,7 +2218,7 @@ THREE.GLTFLoader = ( function () { var material; - if ( materialType === THREE.ShaderMaterial ) { + if ( materialType === GLTFMeshStandardSGMaterial ) { material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams ); @@ -2345,12 +2228,11 @@ THREE.GLTFLoader = ( function () { } - if ( materialDef.name !== undefined ) material.name = materialDef.name; + if ( materialDef.name ) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. - if ( material.map ) material.map.encoding = THREE.sRGBEncoding; - if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding; - if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding; + if ( material.map ) material.map.encoding = sRGBEncoding; + if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding; assignExtrasToUserData( material, materialDef ); @@ -2363,10 +2245,100 @@ THREE.GLTFLoader = ( function () { }; /** - * @param {THREE.BufferGeometry} geometry + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + */ + function computeBounds( geometry, primitiveDef, parser ) { + + var attributes = primitiveDef.attributes; + + var box = new Box3(); + + if ( attributes.POSITION !== undefined ) { + + var accessor = parser.json.accessors[ attributes.POSITION ]; + + var min = accessor.min; + var max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + box.set( + new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), + new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) ); + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + return; + + } + + } else { + + return; + + } + + var targets = primitiveDef.targets; + + if ( targets !== undefined ) { + + var vector = new Vector3(); + + for ( var i = 0, il = targets.length; i < il; i ++ ) { + + var target = targets[ i ]; + + if ( target.POSITION !== undefined ) { + + var accessor = parser.json.accessors[ target.POSITION ]; + var min = accessor.min; + var max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + // we need to get max of absolute components because target weight is [-1,1] + vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); + vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); + vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); + + box.expandByVector( vector ); + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + } + + } + + } + + } + + geometry.boundingBox = box; + + var sphere = new Sphere(); + + box.getCenter( sphere.center ); + sphere.radius = box.min.distanceTo( box.max ) / 2; + + geometry.boundingSphere = sphere; + + } + + /** + * @param {BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser - * @return {Promise} + * @return {Promise} */ function addPrimitiveAttributes( geometry, primitiveDef, parser ) { @@ -2379,7 +2351,7 @@ THREE.GLTFLoader = ( function () { return parser.getDependency( 'accessor', accessorIndex ) .then( function ( accessor ) { - geometry.addAttribute( attributeName, accessor ); + geometry.setAttribute( attributeName, accessor ); } ); @@ -2410,6 +2382,8 @@ THREE.GLTFLoader = ( function () { assignExtrasToUserData( geometry, primitiveDef ); + computeBounds( geometry, primitiveDef, parser ); + return Promise.all( pending ).then( function () { return primitiveDef.targets !== undefined @@ -2420,13 +2394,107 @@ THREE.GLTFLoader = ( function () { } + /** + * @param {BufferGeometry} geometry + * @param {Number} drawMode + * @return {BufferGeometry} + */ + function toTrianglesDrawMode( geometry, drawMode ) { + + var index = geometry.getIndex(); + + // generate index if not present + + if ( index === null ) { + + var indices = []; + + var position = geometry.getAttribute( 'position' ); + + if ( position !== undefined ) { + + for ( var i = 0; i < position.count; i ++ ) { + + indices.push( i ); + + } + + geometry.setIndex( indices ); + index = geometry.getIndex(); + + } else { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); + return geometry; + + } + + } + + // + + var numberOfTriangles = index.count - 2; + var newIndices = []; + + if ( drawMode === TriangleFanDrawMode ) { + + // gl.TRIANGLE_FAN + + for ( var i = 1; i <= numberOfTriangles; i ++ ) { + + newIndices.push( index.getX( 0 ) ); + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + + } + + } else { + + // gl.TRIANGLE_STRIP + + for ( var i = 0; i < numberOfTriangles; i ++ ) { + + if ( i % 2 === 0 ) { + + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i + 2 ) ); + + + } else { + + newIndices.push( index.getX( i + 2 ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i ) ); + + } + + } + + } + + if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { + + console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); + + } + + // build final geometry + + var newGeometry = geometry.clone(); + newGeometry.setIndex( newIndices ); + + return newGeometry; + + } + /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @param {Array} primitives - * @return {Promise>} + * @return {Promise>} */ GLTFParser.prototype.loadGeometries = function ( primitives ) { @@ -2473,7 +2541,7 @@ THREE.GLTFLoader = ( function () { } else { // Otherwise create a new geometry - geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser ); + geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser ); } @@ -2493,7 +2561,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadMesh = function ( meshIndex ) { @@ -2508,115 +2576,116 @@ THREE.GLTFLoader = ( function () { for ( var i = 0, il = primitives.length; i < il; i ++ ) { var material = primitives[ i ].material === undefined - ? createDefaultMaterial() + ? createDefaultMaterial( this.cache ) : this.getDependency( 'material', primitives[ i ].material ); pending.push( material ); } - return Promise.all( pending ).then( function ( originalMaterials ) { + pending.push( parser.loadGeometries( primitives ) ); - return parser.loadGeometries( primitives ).then( function ( geometries ) { + return Promise.all( pending ).then( function ( results ) { - var meshes = []; + var materials = results.slice( 0, results.length - 1 ); + var geometries = results[ results.length - 1 ]; - for ( var i = 0, il = geometries.length; i < il; i ++ ) { + var meshes = []; - var geometry = geometries[ i ]; - var primitive = primitives[ i ]; + for ( var i = 0, il = geometries.length; i < il; i ++ ) { - // 1. create Mesh + var geometry = geometries[ i ]; + var primitive = primitives[ i ]; - var mesh; + // 1. create Mesh - var material = originalMaterials[ i ]; + var mesh; - if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || - primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || - primitive.mode === undefined ) { + var material = materials[ i ]; - // .isSkinnedMesh isn't in glTF spec. See .markDefs() - mesh = meshDef.isSkinnedMesh === true - ? new THREE.SkinnedMesh( geometry, material ) - : new THREE.Mesh( geometry, material ); + if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || + primitive.mode === undefined ) { - if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) { + // .isSkinnedMesh isn't in glTF spec. See .markDefs() + mesh = meshDef.isSkinnedMesh === true + ? new SkinnedMesh( geometry, material ) + : new Mesh( geometry, material ); - // we normalize floating point skin weight array to fix malformed assets (see #15319) - // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs - mesh.normalizeSkinWeights(); + if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) { - } + // we normalize floating point skin weight array to fix malformed assets (see #15319) + // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs + mesh.normalizeSkinWeights(); - if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) { + } - mesh.drawMode = THREE.TriangleStripDrawMode; + if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) { - } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) { + mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode ); - mesh.drawMode = THREE.TriangleFanDrawMode; + } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) { - } + mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode ); - } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { + } - mesh = new THREE.LineSegments( geometry, material ); + } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { - } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) { + mesh = new LineSegments( geometry, material ); - mesh = new THREE.Line( geometry, material ); + } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) { - } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) { + mesh = new Line( geometry, material ); - mesh = new THREE.LineLoop( geometry, material ); + } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) { - } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) { + mesh = new LineLoop( geometry, material ); - mesh = new THREE.Points( geometry, material ); + } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) { - } else { + mesh = new Points( geometry, material ); - throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode ); + } else { - } + throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode ); - if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) { + } - updateMorphTargets( mesh, meshDef ); + if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) { - } + updateMorphTargets( mesh, meshDef ); - mesh.name = meshDef.name || ( 'mesh_' + meshIndex ); + } - if ( geometries.length > 1 ) mesh.name += '_' + i; + mesh.name = meshDef.name || ( 'mesh_' + meshIndex ); - assignExtrasToUserData( mesh, meshDef ); + if ( geometries.length > 1 ) mesh.name += '_' + i; - parser.assignFinalMaterial( mesh ); + assignExtrasToUserData( mesh, meshDef ); - meshes.push( mesh ); + parser.assignFinalMaterial( mesh ); - } + meshes.push( mesh ); - if ( meshes.length === 1 ) { + } - return meshes[ 0 ]; + if ( meshes.length === 1 ) { - } + return meshes[ 0 ]; - var group = new THREE.Group(); + } - for ( var i = 0, il = meshes.length; i < il; i ++ ) { + var group = new Group(); - group.add( meshes[ i ] ); + for ( var i = 0, il = meshes.length; i < il; i ++ ) { - } + group.add( meshes[ i ] ); - return group; + } - } ); + return group; } ); @@ -2642,15 +2711,15 @@ THREE.GLTFLoader = ( function () { if ( cameraDef.type === 'perspective' ) { - camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 ); + camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 ); } else if ( cameraDef.type === 'orthographic' ) { - camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar ); + camera = new OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar ); } - if ( cameraDef.name !== undefined ) camera.name = cameraDef.name; + if ( cameraDef.name ) camera.name = cameraDef.name; assignExtrasToUserData( camera, cameraDef ); @@ -2688,7 +2757,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadAnimation = function ( animationIndex ) { @@ -2756,32 +2825,32 @@ THREE.GLTFLoader = ( function () { case PATH_PROPERTIES.weights: - TypedKeyframeTrack = THREE.NumberKeyframeTrack; + TypedKeyframeTrack = NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: - TypedKeyframeTrack = THREE.QuaternionKeyframeTrack; + TypedKeyframeTrack = QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: - TypedKeyframeTrack = THREE.VectorKeyframeTrack; + TypedKeyframeTrack = VectorKeyframeTrack; break; } var targetName = node.name ? node.name : node.uuid; - var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear; + var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; var targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { - // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh. + // Node may be a Group (glTF mesh with several primitives) or a Mesh. node.traverse( function ( object ) { if ( object.isMesh === true && object.morphTargetInfluences ) { @@ -2871,9 +2940,9 @@ THREE.GLTFLoader = ( function () { } - var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex; + var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex; - return new THREE.AnimationClip( name, undefined, tracks ); + return new AnimationClip( name, undefined, tracks ); } ); @@ -2882,7 +2951,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadNode = function ( nodeIndex ) { @@ -2912,16 +2981,6 @@ THREE.GLTFLoader = ( function () { node = mesh.clone(); node.name += '_instance_' + instanceNum; - // onBeforeRender copy for Specular-Glossiness - node.onBeforeRender = mesh.onBeforeRender; - - for ( var i = 0, il = node.children.length; i < il; i ++ ) { - - node.children[ i ].name += '_instance_' + instanceNum; - node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender; - - } - } else { node = mesh; @@ -2974,11 +3033,11 @@ THREE.GLTFLoader = ( function () { // .isBone isn't in glTF spec. See .markDefs if ( nodeDef.isBone === true ) { - node = new THREE.Bone(); + node = new Bone(); } else if ( objects.length > 1 ) { - node = new THREE.Group(); + node = new Group(); } else if ( objects.length === 1 ) { @@ -2986,7 +3045,7 @@ THREE.GLTFLoader = ( function () { } else { - node = new THREE.Object3D(); + node = new Object3D(); } @@ -3000,10 +3059,10 @@ THREE.GLTFLoader = ( function () { } - if ( nodeDef.name !== undefined ) { + if ( nodeDef.name ) { node.userData.name = nodeDef.name; - node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name ); + node.name = PropertyBinding.sanitizeNodeName( nodeDef.name ); } @@ -3013,9 +3072,9 @@ THREE.GLTFLoader = ( function () { if ( nodeDef.matrix !== undefined ) { - var matrix = new THREE.Matrix4(); + var matrix = new Matrix4(); matrix.fromArray( nodeDef.matrix ); - node.applyMatrix( matrix ); + node.applyMatrix4( matrix ); } else { @@ -3048,7 +3107,7 @@ THREE.GLTFLoader = ( function () { /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex - * @return {Promise} + * @return {Promise} */ GLTFParser.prototype.loadScene = function () { @@ -3097,7 +3156,7 @@ THREE.GLTFLoader = ( function () { bones.push( jointNode ); - var mat = new THREE.Matrix4(); + var mat = new Matrix4(); if ( skinEntry.inverseBindMatrices !== undefined ) { @@ -3115,7 +3174,7 @@ THREE.GLTFLoader = ( function () { } - mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld ); + mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld ); } ); @@ -3157,8 +3216,10 @@ THREE.GLTFLoader = ( function () { var sceneDef = this.json.scenes[ sceneIndex ]; var parser = this; - var scene = new THREE.Scene(); - if ( sceneDef.name !== undefined ) scene.name = sceneDef.name; + // Loader returns Group, not Scene. + // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 + var scene = new Group(); + if ( sceneDef.name ) scene.name = sceneDef.name; assignExtrasToUserData( scene, sceneDef ); @@ -3187,3 +3248,5 @@ THREE.GLTFLoader = ( function () { return GLTFLoader; } )(); + +export { GLTFLoader }; From c19b7a4fe5227eac03d2d35f4e7645ef31bc26ee Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 11:51:12 -0600 Subject: [PATCH 04/11] Update three.js from three.module.js from XRPackage update three.module.js - commit a23f131e7a643de29c07d3826076e1cd0d00889f from XRPackage Major xrpackage refactoring - commit 09524374d5bdc7535e946b5742c520550def3d7d from XRPackage Update three.module.js - commit d76fe1513ba2908e8425f6ccdfb42608c56cf46e from XRPackage Clean up framebuffer latching - commit 71e86a10ccd7d6d26c26c371abe651d48f786e4c from XRPackage Add THREE.js WebGLRenderer getFramebuffer method - commit 1b13f447577669b8274b2924df7cc1e69014169b from XRPackage --- three.js | 60490 +++++++++++++++++++++++++++-------------------------- 1 file changed, 30662 insertions(+), 29828 deletions(-) diff --git a/three.js b/three.js index b7f5b33..f37bad9 100644 --- a/three.js +++ b/three.js @@ -1,89 +1,81 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = global || self, factory(global.THREE = {})); -}(this, function (exports) { 'use strict'; +// Polyfills - // Polyfills +if ( Number.EPSILON === undefined ) { - if ( Number.EPSILON === undefined ) { + Number.EPSILON = Math.pow( 2, - 52 ); - Number.EPSILON = Math.pow( 2, - 52 ); +} - } - - if ( Number.isInteger === undefined ) { +if ( Number.isInteger === undefined ) { - // Missing in IE - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + // Missing in IE + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - Number.isInteger = function ( value ) { + Number.isInteger = function ( value ) { - return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value; - - }; + return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value; - } + }; - // +} - if ( Math.sign === undefined ) { +// - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign +if ( Math.sign === undefined ) { - Math.sign = function ( x ) { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; + Math.sign = function ( x ) { - }; + return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; - } + }; - if ( 'name' in Function.prototype === false ) { +} - // Missing in IE - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name +if ( 'name' in Function.prototype === false ) { - Object.defineProperty( Function.prototype, 'name', { + // Missing in IE + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - get: function () { + Object.defineProperty( Function.prototype, 'name', { - return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ]; + get: function () { - } + return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ]; - } ); + } - } + } ); - if ( Object.assign === undefined ) { +} - // Missing in IE - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign +if ( Object.assign === undefined ) { - Object.assign = function ( target ) { + // Missing in IE + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - if ( target === undefined || target === null ) { + Object.assign = function ( target ) { - throw new TypeError( 'Cannot convert undefined or null to object' ); + if ( target === undefined || target === null ) { - } + throw new TypeError( 'Cannot convert undefined or null to object' ); - var output = Object( target ); + } - for ( var index = 1; index < arguments.length; index ++ ) { + const output = Object( target ); - var source = arguments[ index ]; + for ( let index = 1; index < arguments.length; index ++ ) { - if ( source !== undefined && source !== null ) { + const source = arguments[ index ]; - for ( var nextKey in source ) { + if ( source !== undefined && source !== null ) { - if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { + for ( const nextKey in source ) { - output[ nextKey ] = source[ nextKey ]; + if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { - } + output[ nextKey ] = source[ nextKey ]; } @@ -91,4836 +83,4962 @@ } - return output; + } - }; + return output; - } + }; - var REVISION = '111dev'; - var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; - var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; - var CullFaceNone = 0; - var CullFaceBack = 1; - var CullFaceFront = 2; - var CullFaceFrontBack = 3; - var FrontFaceDirectionCW = 0; - var FrontFaceDirectionCCW = 1; - var BasicShadowMap = 0; - var PCFShadowMap = 1; - var PCFSoftShadowMap = 2; - var VSMShadowMap = 3; - var FrontSide = 0; - var BackSide = 1; - var DoubleSide = 2; - var FlatShading = 1; - var SmoothShading = 2; - var NoColors = 0; - var FaceColors = 1; - var VertexColors = 2; - var NoBlending = 0; - var NormalBlending = 1; - var AdditiveBlending = 2; - var SubtractiveBlending = 3; - var MultiplyBlending = 4; - var CustomBlending = 5; - var AddEquation = 100; - var SubtractEquation = 101; - var ReverseSubtractEquation = 102; - var MinEquation = 103; - var MaxEquation = 104; - var ZeroFactor = 200; - var OneFactor = 201; - var SrcColorFactor = 202; - var OneMinusSrcColorFactor = 203; - var SrcAlphaFactor = 204; - var OneMinusSrcAlphaFactor = 205; - var DstAlphaFactor = 206; - var OneMinusDstAlphaFactor = 207; - var DstColorFactor = 208; - var OneMinusDstColorFactor = 209; - var SrcAlphaSaturateFactor = 210; - var NeverDepth = 0; - var AlwaysDepth = 1; - var LessDepth = 2; - var LessEqualDepth = 3; - var EqualDepth = 4; - var GreaterEqualDepth = 5; - var GreaterDepth = 6; - var NotEqualDepth = 7; - var MultiplyOperation = 0; - var MixOperation = 1; - var AddOperation = 2; - var NoToneMapping = 0; - var LinearToneMapping = 1; - var ReinhardToneMapping = 2; - var Uncharted2ToneMapping = 3; - var CineonToneMapping = 4; - var ACESFilmicToneMapping = 5; - - var UVMapping = 300; - var CubeReflectionMapping = 301; - var CubeRefractionMapping = 302; - var EquirectangularReflectionMapping = 303; - var EquirectangularRefractionMapping = 304; - var SphericalReflectionMapping = 305; - var CubeUVReflectionMapping = 306; - var CubeUVRefractionMapping = 307; - var RepeatWrapping = 1000; - var ClampToEdgeWrapping = 1001; - var MirroredRepeatWrapping = 1002; - var NearestFilter = 1003; - var NearestMipmapNearestFilter = 1004; - var NearestMipMapNearestFilter = 1004; - var NearestMipmapLinearFilter = 1005; - var NearestMipMapLinearFilter = 1005; - var LinearFilter = 1006; - var LinearMipmapNearestFilter = 1007; - var LinearMipMapNearestFilter = 1007; - var LinearMipmapLinearFilter = 1008; - var LinearMipMapLinearFilter = 1008; - var UnsignedByteType = 1009; - var ByteType = 1010; - var ShortType = 1011; - var UnsignedShortType = 1012; - var IntType = 1013; - var UnsignedIntType = 1014; - var FloatType = 1015; - var HalfFloatType = 1016; - var UnsignedShort4444Type = 1017; - var UnsignedShort5551Type = 1018; - var UnsignedShort565Type = 1019; - var UnsignedInt248Type = 1020; - var AlphaFormat = 1021; - var RGBFormat = 1022; - var RGBAFormat = 1023; - var LuminanceFormat = 1024; - var LuminanceAlphaFormat = 1025; - var RGBEFormat = RGBAFormat; - var DepthFormat = 1026; - var DepthStencilFormat = 1027; - var RedFormat = 1028; - var RGB_S3TC_DXT1_Format = 33776; - var RGBA_S3TC_DXT1_Format = 33777; - var RGBA_S3TC_DXT3_Format = 33778; - var RGBA_S3TC_DXT5_Format = 33779; - var RGB_PVRTC_4BPPV1_Format = 35840; - var RGB_PVRTC_2BPPV1_Format = 35841; - var RGBA_PVRTC_4BPPV1_Format = 35842; - var RGBA_PVRTC_2BPPV1_Format = 35843; - var RGB_ETC1_Format = 36196; - var RGBA_ASTC_4x4_Format = 37808; - var RGBA_ASTC_5x4_Format = 37809; - var RGBA_ASTC_5x5_Format = 37810; - var RGBA_ASTC_6x5_Format = 37811; - var RGBA_ASTC_6x6_Format = 37812; - var RGBA_ASTC_8x5_Format = 37813; - var RGBA_ASTC_8x6_Format = 37814; - var RGBA_ASTC_8x8_Format = 37815; - var RGBA_ASTC_10x5_Format = 37816; - var RGBA_ASTC_10x6_Format = 37817; - var RGBA_ASTC_10x8_Format = 37818; - var RGBA_ASTC_10x10_Format = 37819; - var RGBA_ASTC_12x10_Format = 37820; - var RGBA_ASTC_12x12_Format = 37821; - var LoopOnce = 2200; - var LoopRepeat = 2201; - var LoopPingPong = 2202; - var InterpolateDiscrete = 2300; - var InterpolateLinear = 2301; - var InterpolateSmooth = 2302; - var ZeroCurvatureEnding = 2400; - var ZeroSlopeEnding = 2401; - var WrapAroundEnding = 2402; - var TrianglesDrawMode = 0; - var TriangleStripDrawMode = 1; - var TriangleFanDrawMode = 2; - var LinearEncoding = 3000; - var sRGBEncoding = 3001; - var GammaEncoding = 3007; - var RGBEEncoding = 3002; - var LogLuvEncoding = 3003; - var RGBM7Encoding = 3004; - var RGBM16Encoding = 3005; - var RGBDEncoding = 3006; - var BasicDepthPacking = 3200; - var RGBADepthPacking = 3201; - var TangentSpaceNormalMap = 0; - var ObjectSpaceNormalMap = 1; - - var ZeroStencilOp = 0; - var KeepStencilOp = 7680; - var ReplaceStencilOp = 7681; - var IncrementStencilOp = 7682; - var DecrementStencilOp = 7683; - var IncrementWrapStencilOp = 34055; - var DecrementWrapStencilOp = 34056; - var InvertStencilOp = 5386; - - var NeverStencilFunc = 512; - var LessStencilFunc = 513; - var EqualStencilFunc = 514; - var LessEqualStencilFunc = 515; - var GreaterStencilFunc = 516; - var NotEqualStencilFunc = 517; - var GreaterEqualStencilFunc = 518; - var AlwaysStencilFunc = 519; - - var StaticDrawUsage = 35044; - var DynamicDrawUsage = 35048; - var StreamDrawUsage = 35040; - var StaticReadUsage = 35045; - var DynamicReadUsage = 35049; - var StreamReadUsage = 35041; - var StaticCopyUsage = 35046; - var DynamicCopyUsage = 35050; - var StreamCopyUsage = 35042; +} + +const REVISION = '117'; +const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; +const CullFaceNone = 0; +const CullFaceBack = 1; +const CullFaceFront = 2; +const CullFaceFrontBack = 3; +const FrontFaceDirectionCW = 0; +const FrontFaceDirectionCCW = 1; +const BasicShadowMap = 0; +const PCFShadowMap = 1; +const PCFSoftShadowMap = 2; +const VSMShadowMap = 3; +const FrontSide = 0; +const BackSide = 1; +const DoubleSide = 2; +const FlatShading = 1; +const SmoothShading = 2; +const NoBlending = 0; +const NormalBlending = 1; +const AdditiveBlending = 2; +const SubtractiveBlending = 3; +const MultiplyBlending = 4; +const CustomBlending = 5; +const AddEquation = 100; +const SubtractEquation = 101; +const ReverseSubtractEquation = 102; +const MinEquation = 103; +const MaxEquation = 104; +const ZeroFactor = 200; +const OneFactor = 201; +const SrcColorFactor = 202; +const OneMinusSrcColorFactor = 203; +const SrcAlphaFactor = 204; +const OneMinusSrcAlphaFactor = 205; +const DstAlphaFactor = 206; +const OneMinusDstAlphaFactor = 207; +const DstColorFactor = 208; +const OneMinusDstColorFactor = 209; +const SrcAlphaSaturateFactor = 210; +const NeverDepth = 0; +const AlwaysDepth = 1; +const LessDepth = 2; +const LessEqualDepth = 3; +const EqualDepth = 4; +const GreaterEqualDepth = 5; +const GreaterDepth = 6; +const NotEqualDepth = 7; +const MultiplyOperation = 0; +const MixOperation = 1; +const AddOperation = 2; +const NoToneMapping = 0; +const LinearToneMapping = 1; +const ReinhardToneMapping = 2; +const Uncharted2ToneMapping = 3; +const CineonToneMapping = 4; +const ACESFilmicToneMapping = 5; + +const UVMapping = 300; +const CubeReflectionMapping = 301; +const CubeRefractionMapping = 302; +const EquirectangularReflectionMapping = 303; +const EquirectangularRefractionMapping = 304; +const SphericalReflectionMapping = 305; +const CubeUVReflectionMapping = 306; +const CubeUVRefractionMapping = 307; +const RepeatWrapping = 1000; +const ClampToEdgeWrapping = 1001; +const MirroredRepeatWrapping = 1002; +const NearestFilter = 1003; +const NearestMipmapNearestFilter = 1004; +const NearestMipMapNearestFilter = 1004; +const NearestMipmapLinearFilter = 1005; +const NearestMipMapLinearFilter = 1005; +const LinearFilter = 1006; +const LinearMipmapNearestFilter = 1007; +const LinearMipMapNearestFilter = 1007; +const LinearMipmapLinearFilter = 1008; +const LinearMipMapLinearFilter = 1008; +const UnsignedByteType = 1009; +const ByteType = 1010; +const ShortType = 1011; +const UnsignedShortType = 1012; +const IntType = 1013; +const UnsignedIntType = 1014; +const FloatType = 1015; +const HalfFloatType = 1016; +const UnsignedShort4444Type = 1017; +const UnsignedShort5551Type = 1018; +const UnsignedShort565Type = 1019; +const UnsignedInt248Type = 1020; +const AlphaFormat = 1021; +const RGBFormat = 1022; +const RGBAFormat = 1023; +const LuminanceFormat = 1024; +const LuminanceAlphaFormat = 1025; +const RGBEFormat = RGBAFormat; +const DepthFormat = 1026; +const DepthStencilFormat = 1027; +const RedFormat = 1028; +const RedIntegerFormat = 1029; +const RGFormat = 1030; +const RGIntegerFormat = 1031; +const RGBIntegerFormat = 1032; +const RGBAIntegerFormat = 1033; + +const RGB_S3TC_DXT1_Format = 33776; +const RGBA_S3TC_DXT1_Format = 33777; +const RGBA_S3TC_DXT3_Format = 33778; +const RGBA_S3TC_DXT5_Format = 33779; +const RGB_PVRTC_4BPPV1_Format = 35840; +const RGB_PVRTC_2BPPV1_Format = 35841; +const RGBA_PVRTC_4BPPV1_Format = 35842; +const RGBA_PVRTC_2BPPV1_Format = 35843; +const RGB_ETC1_Format = 36196; +const RGB_ETC2_Format = 37492; +const RGBA_ETC2_EAC_Format = 37496; +const RGBA_ASTC_4x4_Format = 37808; +const RGBA_ASTC_5x4_Format = 37809; +const RGBA_ASTC_5x5_Format = 37810; +const RGBA_ASTC_6x5_Format = 37811; +const RGBA_ASTC_6x6_Format = 37812; +const RGBA_ASTC_8x5_Format = 37813; +const RGBA_ASTC_8x6_Format = 37814; +const RGBA_ASTC_8x8_Format = 37815; +const RGBA_ASTC_10x5_Format = 37816; +const RGBA_ASTC_10x6_Format = 37817; +const RGBA_ASTC_10x8_Format = 37818; +const RGBA_ASTC_10x10_Format = 37819; +const RGBA_ASTC_12x10_Format = 37820; +const RGBA_ASTC_12x12_Format = 37821; +const RGBA_BPTC_Format = 36492; +const SRGB8_ALPHA8_ASTC_4x4_Format = 37840; +const SRGB8_ALPHA8_ASTC_5x4_Format = 37841; +const SRGB8_ALPHA8_ASTC_5x5_Format = 37842; +const SRGB8_ALPHA8_ASTC_6x5_Format = 37843; +const SRGB8_ALPHA8_ASTC_6x6_Format = 37844; +const SRGB8_ALPHA8_ASTC_8x5_Format = 37845; +const SRGB8_ALPHA8_ASTC_8x6_Format = 37846; +const SRGB8_ALPHA8_ASTC_8x8_Format = 37847; +const SRGB8_ALPHA8_ASTC_10x5_Format = 37848; +const SRGB8_ALPHA8_ASTC_10x6_Format = 37849; +const SRGB8_ALPHA8_ASTC_10x8_Format = 37850; +const SRGB8_ALPHA8_ASTC_10x10_Format = 37851; +const SRGB8_ALPHA8_ASTC_12x10_Format = 37852; +const SRGB8_ALPHA8_ASTC_12x12_Format = 37853; +const LoopOnce = 2200; +const LoopRepeat = 2201; +const LoopPingPong = 2202; +const InterpolateDiscrete = 2300; +const InterpolateLinear = 2301; +const InterpolateSmooth = 2302; +const ZeroCurvatureEnding = 2400; +const ZeroSlopeEnding = 2401; +const WrapAroundEnding = 2402; +const NormalAnimationBlendMode = 2500; +const AdditiveAnimationBlendMode = 2501; +const TrianglesDrawMode = 0; +const TriangleStripDrawMode = 1; +const TriangleFanDrawMode = 2; +const LinearEncoding = 3000; +const sRGBEncoding = 3001; +const GammaEncoding = 3007; +const RGBEEncoding = 3002; +const LogLuvEncoding = 3003; +const RGBM7Encoding = 3004; +const RGBM16Encoding = 3005; +const RGBDEncoding = 3006; +const BasicDepthPacking = 3200; +const RGBADepthPacking = 3201; +const TangentSpaceNormalMap = 0; +const ObjectSpaceNormalMap = 1; + +const ZeroStencilOp = 0; +const KeepStencilOp = 7680; +const ReplaceStencilOp = 7681; +const IncrementStencilOp = 7682; +const DecrementStencilOp = 7683; +const IncrementWrapStencilOp = 34055; +const DecrementWrapStencilOp = 34056; +const InvertStencilOp = 5386; + +const NeverStencilFunc = 512; +const LessStencilFunc = 513; +const EqualStencilFunc = 514; +const LessEqualStencilFunc = 515; +const GreaterStencilFunc = 516; +const NotEqualStencilFunc = 517; +const GreaterEqualStencilFunc = 518; +const AlwaysStencilFunc = 519; + +const StaticDrawUsage = 35044; +const DynamicDrawUsage = 35048; +const StreamDrawUsage = 35040; +const StaticReadUsage = 35045; +const DynamicReadUsage = 35049; +const StreamReadUsage = 35041; +const StaticCopyUsage = 35046; +const DynamicCopyUsage = 35050; +const StreamCopyUsage = 35042; + +/** + * https://github.com/mrdoob/eventdispatcher.js/ + */ + +function EventDispatcher() {} + +Object.assign( EventDispatcher.prototype, { + + addEventListener: function ( type, listener ) { + + if ( this._listeners === undefined ) this._listeners = {}; + + var listeners = this._listeners; + + if ( listeners[ type ] === undefined ) { + + listeners[ type ] = []; + + } + + if ( listeners[ type ].indexOf( listener ) === - 1 ) { + + listeners[ type ].push( listener ); + + } + + }, + + hasEventListener: function ( type, listener ) { + + if ( this._listeners === undefined ) return false; - /** - * https://github.com/mrdoob/eventdispatcher.js/ - */ + var listeners = this._listeners; + + return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; + + }, - function EventDispatcher() {} + removeEventListener: function ( type, listener ) { - Object.assign( EventDispatcher.prototype, { + if ( this._listeners === undefined ) return; - addEventListener: function ( type, listener ) { + var listeners = this._listeners; + var listenerArray = listeners[ type ]; - if ( this._listeners === undefined ) { this._listeners = {}; } + if ( listenerArray !== undefined ) { - var listeners = this._listeners; + var index = listenerArray.indexOf( listener ); - if ( listeners[ type ] === undefined ) { + if ( index !== - 1 ) { - listeners[ type ] = []; + listenerArray.splice( index, 1 ); } - if ( listeners[ type ].indexOf( listener ) === - 1 ) { + } - listeners[ type ].push( listener ); + }, - } + dispatchEvent: function ( event ) { - }, + if ( this._listeners === undefined ) return; - hasEventListener: function ( type, listener ) { + var listeners = this._listeners; + var listenerArray = listeners[ event.type ]; - if ( this._listeners === undefined ) { return false; } + if ( listenerArray !== undefined ) { - var listeners = this._listeners; + event.target = this; - return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; + // Make a copy, in case listeners are removed while iterating. + var array = listenerArray.slice( 0 ); - }, + for ( var i = 0, l = array.length; i < l; i ++ ) { - removeEventListener: function ( type, listener ) { + array[ i ].call( this, event ); - if ( this._listeners === undefined ) { return; } + } - var listeners = this._listeners; - var listenerArray = listeners[ type ]; + } - if ( listenerArray !== undefined ) { + } - var index = listenerArray.indexOf( listener ); +} ); - if ( index !== - 1 ) { +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author thezwap + */ - listenerArray.splice( index, 1 ); +var _lut = []; - } +for ( var i = 0; i < 256; i ++ ) { - } + _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); - }, +} - dispatchEvent: function ( event ) { +var MathUtils = { - if ( this._listeners === undefined ) { return; } + DEG2RAD: Math.PI / 180, + RAD2DEG: 180 / Math.PI, - var listeners = this._listeners; - var listenerArray = listeners[ event.type ]; + generateUUID: function () { - if ( listenerArray !== undefined ) { + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 - event.target = this; + var d0 = Math.random() * 0xffffffff | 0; + var d1 = Math.random() * 0xffffffff | 0; + var d2 = Math.random() * 0xffffffff | 0; + var d3 = Math.random() * 0xffffffff | 0; + var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; - var array = listenerArray.slice( 0 ); + // .toUpperCase() here flattens concatenated strings to save heap memory space. + return uuid.toUpperCase(); - for ( var i = 0, l = array.length; i < l; i ++ ) { + }, - array[ i ].call( this, event ); + clamp: function ( value, min, max ) { - } + return Math.max( min, Math.min( max, value ) ); - } + }, - } + // compute euclidian modulo of m % n + // https://en.wikipedia.org/wiki/Modulo_operation - } ); + euclideanModulo: function ( n, m ) { - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + return ( ( n % m ) + m ) % m; - var _lut = []; + }, - for ( var i = 0; i < 256; i ++ ) { + // Linear mapping from range to range - _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); + mapLinear: function ( x, a1, a2, b1, b2 ) { - } + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - var _Math = { + }, - DEG2RAD: Math.PI / 180, - RAD2DEG: 180 / Math.PI, + // https://en.wikipedia.org/wiki/Linear_interpolation - generateUUID: function () { + lerp: function ( x, y, t ) { - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 + return ( 1 - t ) * x + t * y; - var d0 = Math.random() * 0xffffffff | 0; - var d1 = Math.random() * 0xffffffff | 0; - var d2 = Math.random() * 0xffffffff | 0; - var d3 = Math.random() * 0xffffffff | 0; - var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + - _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + - _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + - _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; + }, - // .toUpperCase() here flattens concatenated strings to save heap memory space. - return uuid.toUpperCase(); + // http://en.wikipedia.org/wiki/Smoothstep - }, + smoothstep: function ( x, min, max ) { - clamp: function ( value, min, max ) { + if ( x <= min ) return 0; + if ( x >= max ) return 1; - return Math.max( min, Math.min( max, value ) ); + x = ( x - min ) / ( max - min ); - }, + return x * x * ( 3 - 2 * x ); - // compute euclidian modulo of m % n - // https://en.wikipedia.org/wiki/Modulo_operation + }, - euclideanModulo: function ( n, m ) { + smootherstep: function ( x, min, max ) { - return ( ( n % m ) + m ) % m; + if ( x <= min ) return 0; + if ( x >= max ) return 1; - }, + x = ( x - min ) / ( max - min ); - // Linear mapping from range to range + return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); - mapLinear: function ( x, a1, a2, b1, b2 ) { + }, - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + // Random integer from interval - }, + randInt: function ( low, high ) { - // https://en.wikipedia.org/wiki/Linear_interpolation + return low + Math.floor( Math.random() * ( high - low + 1 ) ); - lerp: function ( x, y, t ) { + }, - return ( 1 - t ) * x + t * y; + // Random float from interval - }, + randFloat: function ( low, high ) { - // http://en.wikipedia.org/wiki/Smoothstep + return low + Math.random() * ( high - low ); - smoothstep: function ( x, min, max ) { + }, - if ( x <= min ) { return 0; } - if ( x >= max ) { return 1; } + // Random float from <-range/2, range/2> interval - x = ( x - min ) / ( max - min ); + randFloatSpread: function ( range ) { - return x * x * ( 3 - 2 * x ); + return range * ( 0.5 - Math.random() ); - }, + }, - smootherstep: function ( x, min, max ) { + degToRad: function ( degrees ) { - if ( x <= min ) { return 0; } - if ( x >= max ) { return 1; } + return degrees * MathUtils.DEG2RAD; - x = ( x - min ) / ( max - min ); + }, - return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); + radToDeg: function ( radians ) { - }, + return radians * MathUtils.RAD2DEG; - // Random integer from interval + }, - randInt: function ( low, high ) { + isPowerOfTwo: function ( value ) { - return low + Math.floor( Math.random() * ( high - low + 1 ) ); + return ( value & ( value - 1 ) ) === 0 && value !== 0; - }, + }, - // Random float from interval + ceilPowerOfTwo: function ( value ) { - randFloat: function ( low, high ) { + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); - return low + Math.random() * ( high - low ); + }, - }, + floorPowerOfTwo: function ( value ) { - // Random float from <-range/2, range/2> interval + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); - randFloatSpread: function ( range ) { + }, - return range * ( 0.5 - Math.random() ); + setQuaternionFromProperEuler: function ( q, a, b, c, order ) { - }, + // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles - degToRad: function ( degrees ) { + // rotations are applied to the axes in the order specified by 'order' + // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' + // angles are in radians - return degrees * _Math.DEG2RAD; + var cos = Math.cos; + var sin = Math.sin; - }, + var c2 = cos( b / 2 ); + var s2 = sin( b / 2 ); - radToDeg: function ( radians ) { + var c13 = cos( ( a + c ) / 2 ); + var s13 = sin( ( a + c ) / 2 ); - return radians * _Math.RAD2DEG; + var c1_3 = cos( ( a - c ) / 2 ); + var s1_3 = sin( ( a - c ) / 2 ); - }, + var c3_1 = cos( ( c - a ) / 2 ); + var s3_1 = sin( ( c - a ) / 2 ); - isPowerOfTwo: function ( value ) { + switch ( order ) { - return ( value & ( value - 1 ) ) === 0 && value !== 0; + case 'XYX': + q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); + break; - }, + case 'YZY': + q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); + break; - ceilPowerOfTwo: function ( value ) { + case 'ZXZ': + q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); + break; - return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); + case 'XZX': + q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); + break; - }, + case 'YXY': + q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); + break; - floorPowerOfTwo: function ( value ) { + case 'ZYZ': + q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); + break; - return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); + default: + console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order ); } - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author philogb / http://blog.thejit.org/ - * @author egraether / http://egraether.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - */ +}; - function Vector2( x, y ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author philogb / http://blog.thejit.org/ + * @author egraether / http://egraether.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - this.x = x || 0; - this.y = y || 0; +function Vector2( x, y ) { - } + this.x = x || 0; + this.y = y || 0; - Object.defineProperties( Vector2.prototype, { +} - "width": { +Object.defineProperties( Vector2.prototype, { - get: function () { + "width": { - return this.x; + get: function () { - }, + return this.x; - set: function ( value ) { + }, - this.x = value; + set: function ( value ) { - } + this.x = value; - }, + } - "height": { + }, - get: function () { + "height": { - return this.y; + get: function () { - }, + return this.y; - set: function ( value ) { + }, - this.y = value; + set: function ( value ) { - } + this.y = value; } - } ); + } - Object.assign( Vector2.prototype, { +} ); - isVector2: true, +Object.assign( Vector2.prototype, { - set: function ( x, y ) { + isVector2: true, - this.x = x; - this.y = y; + set: function ( x, y ) { - return this; + this.x = x; + this.y = y; - }, + return this; - setScalar: function ( scalar ) { + }, - this.x = scalar; - this.y = scalar; + setScalar: function ( scalar ) { - return this; + this.x = scalar; + this.y = scalar; - }, + return this; - setX: function ( x ) { + }, - this.x = x; + setX: function ( x ) { - return this; + this.x = x; - }, + return this; - setY: function ( y ) { + }, - this.y = y; + setY: function ( y ) { - return this; + this.y = y; - }, + return this; - setComponent: function ( index, value ) { + }, - switch ( index ) { + setComponent: function ( index, value ) { - case 0: this.x = value; break; - case 1: this.y = value; break; - default: throw new Error( 'index is out of range: ' + index ); + switch ( index ) { - } + case 0: this.x = value; break; + case 1: this.y = value; break; + default: throw new Error( 'index is out of range: ' + index ); - return this; + } - }, + return this; - getComponent: function ( index ) { + }, - switch ( index ) { + getComponent: function ( index ) { - case 0: return this.x; - case 1: return this.y; - default: throw new Error( 'index is out of range: ' + index ); + switch ( index ) { - } + case 0: return this.x; + case 1: return this.y; + default: throw new Error( 'index is out of range: ' + index ); - }, + } - clone: function () { + }, - return new this.constructor( this.x, this.y ); + clone: function () { - }, + return new this.constructor( this.x, this.y ); - copy: function ( v ) { + }, - this.x = v.x; - this.y = v.y; + copy: function ( v ) { - return this; + this.x = v.x; + this.y = v.y; - }, + return this; - add: function ( v, w ) { + }, - if ( w !== undefined ) { + add: function ( v, w ) { - console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - this.x += v.x; - this.y += v.y; + } - return this; + this.x += v.x; + this.y += v.y; - }, + return this; - addScalar: function ( s ) { + }, - this.x += s; - this.y += s; + addScalar: function ( s ) { - return this; + this.x += s; + this.y += s; - }, + return this; - addVectors: function ( a, b ) { + }, - this.x = a.x + b.x; - this.y = a.y + b.y; + addVectors: function ( a, b ) { - return this; + this.x = a.x + b.x; + this.y = a.y + b.y; - }, + return this; - addScaledVector: function ( v, s ) { + }, - this.x += v.x * s; - this.y += v.y * s; + addScaledVector: function ( v, s ) { - return this; + this.x += v.x * s; + this.y += v.y * s; - }, + return this; - sub: function ( v, w ) { + }, - if ( w !== undefined ) { + sub: function ( v, w ) { - console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - this.x -= v.x; - this.y -= v.y; + } - return this; + this.x -= v.x; + this.y -= v.y; - }, + return this; - subScalar: function ( s ) { + }, - this.x -= s; - this.y -= s; + subScalar: function ( s ) { - return this; + this.x -= s; + this.y -= s; - }, + return this; - subVectors: function ( a, b ) { + }, - this.x = a.x - b.x; - this.y = a.y - b.y; + subVectors: function ( a, b ) { - return this; + this.x = a.x - b.x; + this.y = a.y - b.y; - }, + return this; - multiply: function ( v ) { + }, - this.x *= v.x; - this.y *= v.y; + multiply: function ( v ) { - return this; + this.x *= v.x; + this.y *= v.y; - }, + return this; - multiplyScalar: function ( scalar ) { + }, - this.x *= scalar; - this.y *= scalar; + multiplyScalar: function ( scalar ) { - return this; + this.x *= scalar; + this.y *= scalar; - }, + return this; - divide: function ( v ) { + }, - this.x /= v.x; - this.y /= v.y; + divide: function ( v ) { - return this; + this.x /= v.x; + this.y /= v.y; - }, + return this; - divideScalar: function ( scalar ) { + }, - return this.multiplyScalar( 1 / scalar ); + divideScalar: function ( scalar ) { - }, + return this.multiplyScalar( 1 / scalar ); - applyMatrix3: function ( m ) { + }, - var x = this.x, y = this.y; - var e = m.elements; + applyMatrix3: function ( m ) { - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + var x = this.x, y = this.y; + var e = m.elements; - return this; + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; - }, + return this; - min: function ( v ) { + }, - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); + min: function ( v ) { - return this; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); - }, + return this; - max: function ( v ) { + }, - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); + max: function ( v ) { - return this; + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); - }, + return this; - clamp: function ( min, max ) { + }, - // assumes min < max, componentwise + clamp: function ( min, max ) { - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + // assumes min < max, componentwise - return this; + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - }, + return this; - clampScalar: function ( minVal, maxVal ) { + }, - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + clampScalar: function ( minVal, maxVal ) { - return this; + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - }, + return this; - clampLength: function ( min, max ) { + }, - var length = this.length(); + clampLength: function ( min, max ) { - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + var length = this.length(); - }, + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - floor: function () { + }, - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); + floor: function () { - return this; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); - }, + return this; - ceil: function () { + }, - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); + ceil: function () { - return this; + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); - }, + return this; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); + round: function () { - return this; + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); - }, + return this; - roundToZero: function () { + }, - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + roundToZero: function () { - return this; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - }, + return this; - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; + negate: function () { - return this; + this.x = - this.x; + this.y = - this.y; - }, + return this; - dot: function ( v ) { + }, - return this.x * v.x + this.y * v.y; + dot: function ( v ) { - }, + return this.x * v.x + this.y * v.y; - cross: function ( v ) { + }, - return this.x * v.y - this.y * v.x; + cross: function ( v ) { - }, + return this.x * v.y - this.y * v.x; - lengthSq: function () { + }, - return this.x * this.x + this.y * this.y; + lengthSq: function () { - }, + return this.x * this.x + this.y * this.y; - length: function () { + }, - return Math.sqrt( this.x * this.x + this.y * this.y ); + length: function () { - }, + return Math.sqrt( this.x * this.x + this.y * this.y ); - manhattanLength: function () { + }, - return Math.abs( this.x ) + Math.abs( this.y ); + manhattanLength: function () { - }, + return Math.abs( this.x ) + Math.abs( this.y ); - normalize: function () { + }, - return this.divideScalar( this.length() || 1 ); + normalize: function () { - }, + return this.divideScalar( this.length() || 1 ); - angle: function () { + }, - // computes the angle in radians with respect to the positive x-axis + angle: function () { - var angle = Math.atan2( this.y, this.x ); + // computes the angle in radians with respect to the positive x-axis - if ( angle < 0 ) { angle += 2 * Math.PI; } + var angle = Math.atan2( - this.y, - this.x ) + Math.PI; - return angle; + return angle; - }, + }, - distanceTo: function ( v ) { + distanceTo: function ( v ) { - return Math.sqrt( this.distanceToSquared( v ) ); + return Math.sqrt( this.distanceToSquared( v ) ); - }, + }, - distanceToSquared: function ( v ) { + distanceToSquared: function ( v ) { - var dx = this.x - v.x, dy = this.y - v.y; - return dx * dx + dy * dy; + var dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; - }, + }, - manhattanDistanceTo: function ( v ) { + manhattanDistanceTo: function ( v ) { - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); - }, + }, - setLength: function ( length ) { + setLength: function ( length ) { - return this.normalize().multiplyScalar( length ); + return this.normalize().multiplyScalar( length ); - }, + }, - lerp: function ( v, alpha ) { + lerp: function ( v, alpha ) { - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; - return this; + return this; - }, + }, - lerpVectors: function ( v1, v2, alpha ) { + lerpVectors: function ( v1, v2, alpha ) { - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; - }, + return this; - equals: function ( v ) { + }, - return ( ( v.x === this.x ) && ( v.y === this.y ) ); + equals: function ( v ) { - }, + return ( ( v.x === this.x ) && ( v.y === this.y ) ); - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) { offset = 0; } + fromArray: function ( array, offset ) { - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; + if ( offset === undefined ) offset = 0; - return this; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + toArray: function ( array, offset ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return array; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; - }, + return array; - fromBufferAttribute: function ( attribute, index, offset ) { + }, - if ( offset !== undefined ) { + fromBufferAttribute: function ( attribute, index, offset ) { - console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); + if ( offset !== undefined ) { - } + console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); + } - return this; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); - }, + return this; - rotateAround: function ( center, angle ) { + }, - var c = Math.cos( angle ), s = Math.sin( angle ); + rotateAround: function ( center, angle ) { - var x = this.x - center.x; - var y = this.y - center.y; + var c = Math.cos( angle ), s = Math.sin( angle ); - this.x = x * c - y * s + center.x; - this.y = x * s + y * c + center.y; + var x = this.x - center.x; + var y = this.y - center.y; - return this; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; - } + return this; - } ); + }, - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + random: function () { - function Quaternion( x, y, z, w ) { + this.x = Math.random(); + this.y = Math.random(); - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._w = ( w !== undefined ) ? w : 1; + return this; } - Object.assign( Quaternion, { +} ); - slerp: function ( qa, qb, qm, t ) { +/** + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw + */ - return qm.copy( qa ).slerp( qb, t ); +function Matrix3() { - }, + this.elements = [ - slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - // fuzz-free, array-based Quaternion SLERP operation + ]; - var x0 = src0[ srcOffset0 + 0 ], - y0 = src0[ srcOffset0 + 1 ], - z0 = src0[ srcOffset0 + 2 ], - w0 = src0[ srcOffset0 + 3 ], + if ( arguments.length > 0 ) { - x1 = src1[ srcOffset1 + 0 ], - y1 = src1[ srcOffset1 + 1 ], - z1 = src1[ srcOffset1 + 2 ], - w1 = src1[ srcOffset1 + 3 ]; + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); - if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { + } - var s = 1 - t, +} - cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, +Object.assign( Matrix3.prototype, { - dir = ( cos >= 0 ? 1 : - 1 ), - sqrSin = 1 - cos * cos; + isMatrix3: true, - // Skip the Slerp for tiny steps to avoid numeric problems: - if ( sqrSin > Number.EPSILON ) { + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { - var sin = Math.sqrt( sqrSin ), - len = Math.atan2( sin, cos * dir ); + var te = this.elements; - s = Math.sin( s * len ) / sin; - t = Math.sin( t * len ) / sin; + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; - } + return this; - var tDir = t * dir; + }, - x0 = x0 * s + x1 * tDir; - y0 = y0 * s + y1 * tDir; - z0 = z0 * s + z1 * tDir; - w0 = w0 * s + w1 * tDir; + identity: function () { - // Normalize in case we just did a lerp: - if ( s === 1 - t ) { + this.set( - var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 - x0 *= f; - y0 *= f; - z0 *= f; - w0 *= f; + ); - } + return this; - } + }, - dst[ dstOffset ] = x0; - dst[ dstOffset + 1 ] = y0; - dst[ dstOffset + 2 ] = z0; - dst[ dstOffset + 3 ] = w0; + clone: function () { - } + return new this.constructor().fromArray( this.elements ); - } ); + }, - Object.defineProperties( Quaternion.prototype, { + copy: function ( m ) { - x: { + var te = this.elements; + var me = m.elements; - get: function () { + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; - return this._x; + return this; - }, + }, - set: function ( value ) { + extractBasis: function ( xAxis, yAxis, zAxis ) { - this._x = value; - this._onChangeCallback(); + xAxis.setFromMatrix3Column( this, 0 ); + yAxis.setFromMatrix3Column( this, 1 ); + zAxis.setFromMatrix3Column( this, 2 ); - } + return this; - }, + }, - y: { + setFromMatrix4: function ( m ) { - get: function () { + var me = m.elements; - return this._y; + this.set( - }, + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - set: function ( value ) { + ); - this._y = value; - this._onChangeCallback(); + return this; - } + }, - }, + multiply: function ( m ) { - z: { + return this.multiplyMatrices( this, m ); - get: function () { + }, - return this._z; + premultiply: function ( m ) { - }, + return this.multiplyMatrices( m, this ); - set: function ( value ) { + }, - this._z = value; - this._onChangeCallback(); + multiplyMatrices: function ( a, b ) { - } + var ae = a.elements; + var be = b.elements; + var te = this.elements; - }, + var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; - w: { + var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; - get: function () { + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; - return this._w; + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; - }, + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; - set: function ( value ) { + return this; - this._w = value; - this._onChangeCallback(); + }, - } + multiplyScalar: function ( s ) { - } + var te = this.elements; - } ); + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - Object.assign( Quaternion.prototype, { + return this; - isQuaternion: true, + }, - set: function ( x, y, z, w ) { + determinant: function () { - this._x = x; - this._y = y; - this._z = z; - this._w = w; + var te = this.elements; - this._onChangeCallback(); + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - return this; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - }, + }, - clone: function () { + getInverse: function ( matrix, throwOnDegenerate ) { - return new this.constructor( this._x, this._y, this._z, this._w ); + if ( throwOnDegenerate !== undefined ) { - }, + console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." ); - copy: function ( quaternion ) { + } - this._x = quaternion.x; - this._y = quaternion.y; - this._z = quaternion.z; - this._w = quaternion.w; + var me = matrix.elements, + te = this.elements, - this._onChangeCallback(); + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], - return this; + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - }, + det = n11 * t11 + n21 * t12 + n31 * t13; - setFromEuler: function ( euler, update ) { + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - if ( ! ( euler && euler.isEuler ) ) { + var detInv = 1 / det; - throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; - } + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; - var x = euler._x, y = euler._y, z = euler._z, order = euler.order; + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; - // http://www.mathworks.com/matlabcentral/fileexchange/ - // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ - // content/SpinCalc.m + return this; - var cos = Math.cos; - var sin = Math.sin; + }, - var c1 = cos( x / 2 ); - var c2 = cos( y / 2 ); - var c3 = cos( z / 2 ); + transpose: function () { - var s1 = sin( x / 2 ); - var s2 = sin( y / 2 ); - var s3 = sin( z / 2 ); + var tmp, m = this.elements; - if ( order === 'XYZ' ) { + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + return this; - } else if ( order === 'YXZ' ) { + }, - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + getNormalMatrix: function ( matrix4 ) { - } else if ( order === 'ZXY' ) { + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + }, - } else if ( order === 'ZYX' ) { + transposeIntoArray: function ( r ) { - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + var m = this.elements; - } else if ( order === 'YZX' ) { + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; - this._x = s1 * c2 * c3 + c1 * s2 * s3; - this._y = c1 * s2 * c3 + s1 * c2 * s3; - this._z = c1 * c2 * s3 - s1 * s2 * c3; - this._w = c1 * c2 * c3 - s1 * s2 * s3; + return this; - } else if ( order === 'XZY' ) { + }, - this._x = s1 * c2 * c3 - c1 * s2 * s3; - this._y = c1 * s2 * c3 - s1 * c2 * s3; - this._z = c1 * c2 * s3 + s1 * s2 * c3; - this._w = c1 * c2 * c3 + s1 * s2 * s3; + setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) { - } + var c = Math.cos( rotation ); + var s = Math.sin( rotation ); - if ( update !== false ) { this._onChangeCallback(); } + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); - return this; + }, - }, + scale: function ( sx, sy ) { - setFromAxisAngle: function ( axis, angle ) { + var te = this.elements; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; + te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; - // assumes axis is normalized + return this; - var halfAngle = angle / 2, s = Math.sin( halfAngle ); + }, - this._x = axis.x * s; - this._y = axis.y * s; - this._z = axis.z * s; - this._w = Math.cos( halfAngle ); + rotate: function ( theta ) { - this._onChangeCallback(); + var c = Math.cos( theta ); + var s = Math.sin( theta ); - return this; + var te = this.elements; - }, + var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; + var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; - setFromRotationMatrix: function ( m ) { + te[ 0 ] = c * a11 + s * a21; + te[ 3 ] = c * a12 + s * a22; + te[ 6 ] = c * a13 + s * a23; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + te[ 1 ] = - s * a11 + c * a21; + te[ 4 ] = - s * a12 + c * a22; + te[ 7 ] = - s * a13 + c * a23; - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return this; - var te = m.elements, + }, - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], + translate: function ( tx, ty ) { - trace = m11 + m22 + m33, - s; + var te = this.elements; - if ( trace > 0 ) { + te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; + te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; - s = 0.5 / Math.sqrt( trace + 1.0 ); + return this; - this._w = 0.25 / s; - this._x = ( m32 - m23 ) * s; - this._y = ( m13 - m31 ) * s; - this._z = ( m21 - m12 ) * s; + }, - } else if ( m11 > m22 && m11 > m33 ) { + equals: function ( matrix ) { - s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + var te = this.elements; + var me = matrix.elements; - this._w = ( m32 - m23 ) / s; - this._x = 0.25 * s; - this._y = ( m12 + m21 ) / s; - this._z = ( m13 + m31 ) / s; + for ( var i = 0; i < 9; i ++ ) { - } else if ( m22 > m33 ) { + if ( te[ i ] !== me[ i ] ) return false; - s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + } - this._w = ( m13 - m31 ) / s; - this._x = ( m12 + m21 ) / s; - this._y = 0.25 * s; - this._z = ( m23 + m32 ) / s; + return true; - } else { + }, - s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + fromArray: function ( array, offset ) { - this._w = ( m21 - m12 ) / s; - this._x = ( m13 + m31 ) / s; - this._y = ( m23 + m32 ) / s; - this._z = 0.25 * s; + if ( offset === undefined ) offset = 0; - } + for ( var i = 0; i < 9; i ++ ) { - this._onChangeCallback(); + this.elements[ i ] = array[ i + offset ]; - return this; + } - }, + return this; - setFromUnitVectors: function ( vFrom, vTo ) { + }, - // assumes direction vectors vFrom and vTo are normalized + toArray: function ( array, offset ) { - var EPS = 0.000001; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - var r = vFrom.dot( vTo ) + 1; + var te = this.elements; - if ( r < EPS ) { + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - r = 0; + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - this._x = - vFrom.y; - this._y = vFrom.x; - this._z = 0; - this._w = r; + return array; - } else { + } - this._x = 0; - this._y = - vFrom.z; - this._z = vFrom.y; - this._w = r; +} ); - } +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - } else { +var _canvas; - // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 +var ImageUtils = { - this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; - this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; - this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; - this._w = r; + getDataURL: function ( image ) { - } + var canvas; - return this.normalize(); + if ( typeof HTMLCanvasElement == 'undefined' ) { - }, + return image.src; - angleTo: function ( q ) { + } else if ( image instanceof HTMLCanvasElement ) { - return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) ); + canvas = image; - }, + } else { - rotateTowards: function ( q, step ) { + if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - var angle = this.angleTo( q ); + _canvas.width = image.width; + _canvas.height = image.height; - if ( angle === 0 ) { return this; } + var context = _canvas.getContext( '2d' ); - var t = Math.min( 1, step / angle ); + if ( image instanceof ImageData ) { - this.slerp( q, t ); + context.putImageData( image, 0, 0 ); - return this; + } else { - }, + context.drawImage( image, 0, 0, image.width, image.height ); - inverse: function () { + } - // quaternion is assumed to have unit length + canvas = _canvas; - return this.conjugate(); + } - }, + if ( canvas.width > 2048 || canvas.height > 2048 ) { - conjugate: function () { + return canvas.toDataURL( 'image/jpeg', 0.6 ); - this._x *= - 1; - this._y *= - 1; - this._z *= - 1; + } else { - this._onChangeCallback(); + return canvas.toDataURL( 'image/png' ); - return this; + } - }, + } - dot: function ( v ) { +}; - return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - }, +var textureId = 0; - lengthSq: function () { +function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + Object.defineProperty( this, 'id', { value: textureId ++ } ); - }, + this.uuid = MathUtils.generateUUID(); - length: function () { + this.name = ''; - return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - }, + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - normalize: function () { + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - var l = this.length(); + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter; - if ( l === 0 ) { + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - this._x = 0; - this._y = 0; - this._z = 0; - this._w = 1; + this.format = format !== undefined ? format : RGBAFormat; + this.internalFormat = null; + this.type = type !== undefined ? type : UnsignedByteType; - } else { + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; - l = 1 / l; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); - this._x = this._x * l; - this._y = this._y * l; - this._z = this._z * l; - this._w = this._w * l; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - } + // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. + // + // Also changing the encoding after already used by a Material will not automatically make the Material + // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. + this.encoding = encoding !== undefined ? encoding : LinearEncoding; - this._onChangeCallback(); + this.version = 0; + this.onUpdate = null; - return this; +} - }, +Texture.DEFAULT_IMAGE = undefined; +Texture.DEFAULT_MAPPING = UVMapping; - multiply: function ( q, p ) { +Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - if ( p !== undefined ) { + constructor: Texture, - console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); - return this.multiplyQuaternions( q, p ); + isTexture: true, - } + updateMatrix: function () { - return this.multiplyQuaternions( this, q ); + this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); - }, + }, - premultiply: function ( q ) { + clone: function () { - return this.multiplyQuaternions( q, this ); + return new this.constructor().copy( this ); - }, + }, - multiplyQuaternions: function ( a, b ) { + copy: function ( source ) { - // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + this.name = source.name; - var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; - var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; - this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; - this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; - this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this.mapping = source.mapping; - this._onChangeCallback(); + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - return this; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - }, + this.anisotropy = source.anisotropy; - slerp: function ( qb, t ) { + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; - if ( t === 0 ) { return this; } - if ( t === 1 ) { return this.copy( qb ); } + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; - var x = this._x, y = this._y, z = this._z, w = this._w; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); - // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; - var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + return this; - if ( cosHalfTheta < 0 ) { + }, - this._w = - qb._w; - this._x = - qb._x; - this._y = - qb._y; - this._z = - qb._z; + toJSON: function ( meta ) { - cosHalfTheta = - cosHalfTheta; + var isRootObject = ( meta === undefined || typeof meta === 'string' ); - } else { + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { - this.copy( qb ); + return meta.textures[ this.uuid ]; - } + } - if ( cosHalfTheta >= 1.0 ) { + var output = { - this._w = w; - this._x = x; - this._y = y; - this._z = z; + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, - return this; + uuid: this.uuid, + name: this.name, - } + mapping: this.mapping, - var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, - if ( sqrSinHalfTheta <= Number.EPSILON ) { + wrap: [ this.wrapS, this.wrapT ], - var s = 1 - t; - this._w = s * w + t * this._w; - this._x = s * x + t * this._x; - this._y = s * y + t * this._y; - this._z = s * z + t * this._z; + format: this.format, + type: this.type, + encoding: this.encoding, - this.normalize(); - this._onChangeCallback(); + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - return this; + flipY: this.flipY, - } + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment - var sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); - var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); - var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, - ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + }; - this._w = ( w * ratioA + this._w * ratioB ); - this._x = ( x * ratioA + this._x * ratioB ); - this._y = ( y * ratioA + this._y * ratioB ); - this._z = ( z * ratioA + this._z * ratioB ); + if ( this.image !== undefined ) { - this._onChangeCallback(); + // TODO: Move to THREE.Image - return this; + var image = this.image; - }, + if ( image.uuid === undefined ) { - equals: function ( quaternion ) { + image.uuid = MathUtils.generateUUID(); // UGH - return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + } - }, + if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { - fromArray: function ( array, offset ) { + var url; - if ( offset === undefined ) { offset = 0; } + if ( Array.isArray( image ) ) { - this._x = array[ offset ]; - this._y = array[ offset + 1 ]; - this._z = array[ offset + 2 ]; - this._w = array[ offset + 3 ]; + // process array of images e.g. CubeTexture - this._onChangeCallback(); + url = []; - return this; + for ( var i = 0, l = image.length; i < l; i ++ ) { - }, + url.push( ImageUtils.getDataURL( image[ i ] ) ); - toArray: function ( array, offset ) { + } - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + } else { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._w; + // process single image - return array; + url = ImageUtils.getDataURL( image ); - }, + } - _onChange: function ( callback ) { + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: url + }; - this._onChangeCallback = callback; + } - return this; + output.image = image.uuid; - }, + } - _onChangeCallback: function () {} + if ( ! isRootObject ) { - } ); + meta.textures[ this.uuid ] = output; - /** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + } - var _vector = new Vector3(); - var _quaternion = new Quaternion(); + return output; - function Vector3( x, y, z ) { + }, - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; + dispose: function () { - } + this.dispatchEvent( { type: 'dispose' } ); - Object.assign( Vector3.prototype, { + }, - isVector3: true, + transformUv: function ( uv ) { - set: function ( x, y, z ) { + if ( this.mapping !== UVMapping ) return uv; - this.x = x; - this.y = y; - this.z = z; + uv.applyMatrix3( this.matrix ); - return this; + if ( uv.x < 0 || uv.x > 1 ) { - }, + switch ( this.wrapS ) { - setScalar: function ( scalar ) { + case RepeatWrapping: - this.x = scalar; - this.y = scalar; - this.z = scalar; + uv.x = uv.x - Math.floor( uv.x ); + break; - return this; + case ClampToEdgeWrapping: - }, + uv.x = uv.x < 0 ? 0 : 1; + break; - setX: function ( x ) { + case MirroredRepeatWrapping: - this.x = x; + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - return this; + uv.x = Math.ceil( uv.x ) - uv.x; - }, + } else { - setY: function ( y ) { + uv.x = uv.x - Math.floor( uv.x ); - this.y = y; + } - return this; + break; - }, + } + + } - setZ: function ( z ) { + if ( uv.y < 0 || uv.y > 1 ) { - this.z = z; + switch ( this.wrapT ) { - return this; + case RepeatWrapping: - }, + uv.y = uv.y - Math.floor( uv.y ); + break; - setComponent: function ( index, value ) { + case ClampToEdgeWrapping: - switch ( index ) { + uv.y = uv.y < 0 ? 0 : 1; + break; - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - default: throw new Error( 'index is out of range: ' + index ); + case MirroredRepeatWrapping: - } + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - return this; + uv.y = Math.ceil( uv.y ) - uv.y; - }, + } else { - getComponent: function ( index ) { + uv.y = uv.y - Math.floor( uv.y ); - switch ( index ) { + } - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - default: throw new Error( 'index is out of range: ' + index ); + break; } - }, + } - clone: function () { + if ( this.flipY ) { - return new this.constructor( this.x, this.y, this.z ); + uv.y = 1 - uv.y; - }, + } - copy: function ( v ) { + return uv; - this.x = v.x; - this.y = v.y; - this.z = v.z; + } - return this; +} ); - }, +Object.defineProperty( Texture.prototype, "needsUpdate", { + + set: function ( value ) { - add: function ( v, w ) { + if ( value === true ) this.version ++; - if ( w !== undefined ) { + } - console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); +} ); - } +/** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - this.x += v.x; - this.y += v.y; - this.z += v.z; +function Vector4( x, y, z, w ) { - return this; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - }, +} - addScalar: function ( s ) { +Object.defineProperties( Vector4.prototype, { - this.x += s; - this.y += s; - this.z += s; + "width": { - return this; + get: function () { + + return this.z; }, - addVectors: function ( a, b ) { + set: function ( value ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; + this.z = value; - return this; + } - }, + }, - addScaledVector: function ( v, s ) { + "height": { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; + get: function () { - return this; + return this.w; }, - sub: function ( v, w ) { + set: function ( value ) { - if ( w !== undefined ) { + this.w = value; - console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + } - } + } - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; +} ); - return this; +Object.assign( Vector4.prototype, { - }, + isVector4: true, - subScalar: function ( s ) { + set: function ( x, y, z, w ) { - this.x -= s; - this.y -= s; - this.z -= s; + this.x = x; + this.y = y; + this.z = z; + this.w = w; - return this; + return this; - }, + }, - subVectors: function ( a, b ) { + setScalar: function ( scalar ) { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; - return this; + return this; - }, + }, - multiply: function ( v, w ) { + setX: function ( x ) { - if ( w !== undefined ) { + this.x = x; - console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); - return this.multiplyVectors( v, w ); + return this; - } + }, - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; + setY: function ( y ) { - return this; + this.y = y; - }, + return this; - multiplyScalar: function ( scalar ) { + }, - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; + setZ: function ( z ) { - return this; + this.z = z; - }, + return this; - multiplyVectors: function ( a, b ) { + }, - this.x = a.x * b.x; - this.y = a.y * b.y; - this.z = a.z * b.z; + setW: function ( w ) { - return this; + this.w = w; - }, + return this; - applyEuler: function ( euler ) { + }, - if ( ! ( euler && euler.isEuler ) ) { + setComponent: function ( index, value ) { - console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); + switch ( index ) { - } + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); - return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); + } - }, + return this; - applyAxisAngle: function ( axis, angle ) { + }, - return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); + getComponent: function ( index ) { - }, + switch ( index ) { - applyMatrix3: function ( m ) { + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + } - this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; - this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; - this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; + }, - return this; + clone: function () { - }, + return new this.constructor( this.x, this.y, this.z, this.w ); - applyMatrix4: function ( m ) { + }, - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + copy: function ( v ) { - var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; - this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; + return this; - return this; + }, - }, + add: function ( v, w ) { - applyQuaternion: function ( q ) { + if ( w !== undefined ) { - var x = this.x, y = this.y, z = this.z; - var qx = q.x, qy = q.y, qz = q.z, qw = q.w; + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - // calculate quat * vector + } - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; - var iw = - qx * x - qy * y - qz * z; + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - // calculate result * inverse quat + return this; - this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; - this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; - this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; + }, - return this; + addScalar: function ( s ) { - }, + this.x += s; + this.y += s; + this.z += s; + this.w += s; - project: function ( camera ) { + return this; - return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); + }, - }, + addVectors: function ( a, b ) { - unproject: function ( camera ) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); + return this; - }, + }, - transformDirection: function ( m ) { + addScaledVector: function ( v, s ) { - // input: THREE.Matrix4 affine matrix - // vector interpreted as a direction + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - var x = this.x, y = this.y, z = this.z; - var e = m.elements; + return this; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; + }, - return this.normalize(); + sub: function ( v, w ) { - }, + if ( w !== undefined ) { - divide: function ( v ) { + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; + } - return this; + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - }, + return this; - divideScalar: function ( scalar ) { + }, - return this.multiplyScalar( 1 / scalar ); + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - min: function ( v ) { + return this; - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); + }, - return this; + subVectors: function ( a, b ) { - }, + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - max: function ( v ) { + return this; - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); + }, - return this; + multiplyScalar: function ( scalar ) { - }, + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - clamp: function ( min, max ) { + return this; - // assumes min < max, componentwise + }, - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + applyMatrix4: function ( m ) { - return this; + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - }, + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - clampScalar: function ( minVal, maxVal ) { + return this; - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + }, - return this; + divideScalar: function ( scalar ) { - }, + return this.multiplyScalar( 1 / scalar ); - clampLength: function ( min, max ) { + }, - var length = this.length(); + setAxisAngleFromQuaternion: function ( q ) { - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - }, + // q is assumed to be normalized - floor: function () { + this.w = 2 * Math.acos( q.w ); - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); + var s = Math.sqrt( 1 - q.w * q.w ); - return this; + if ( s < 0.0001 ) { - }, + this.x = 1; + this.y = 0; + this.z = 0; - ceil: function () { + } else { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - return this; + } - }, + return this; - round: function () { + }, - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); + setAxisAngleFromRotationMatrix: function ( m ) { - return this; + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - }, + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - roundToZero: function () { + var angle, x, y, z, // variables for result + epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + te = m.elements, - return this; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - }, + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - negate: function () { + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - return this; + // this singularity is identity matrix so angle = 0 - }, + this.set( 1, 0, 0, 0 ); - dot: function ( v ) { + return this; // zero angle, arbitrary axis - return this.x * v.x + this.y * v.y + this.z * v.z; + } - }, + // otherwise this singularity is angle = 180 - // TODO lengthSquared? + angle = Math.PI; - lengthSq: function () { + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - return this.x * this.x + this.y * this.y + this.z * this.z; + if ( ( xx > yy ) && ( xx > zz ) ) { - }, + // m11 is the largest diagonal term - length: function () { + if ( xx < epsilon ) { - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); + x = 0; + y = 0.707106781; + z = 0.707106781; - }, + } else { - manhattanLength: function () { + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); + } - }, + } else if ( yy > zz ) { - normalize: function () { + // m22 is the largest diagonal term - return this.divideScalar( this.length() || 1 ); + if ( yy < epsilon ) { - }, + x = 0.707106781; + y = 0; + z = 0.707106781; - setLength: function ( length ) { + } else { - return this.normalize().multiplyScalar( length ); + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - }, + } - lerp: function ( v, alpha ) { + } else { - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; + // m33 is the largest diagonal term so base result on this - return this; + if ( zz < epsilon ) { - }, + x = 0.707106781; + y = 0.707106781; + z = 0; - lerpVectors: function ( v1, v2, alpha ) { + } else { - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - }, + } - cross: function ( v, w ) { + } - if ( w !== undefined ) { + this.set( x, y, z, angle ); - console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); - return this.crossVectors( v, w ); + return this; // return 180 deg rotation - } + } - return this.crossVectors( this, v ); + // as we have reached here there are no singularities so we can handle normally - }, + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - crossVectors: function ( a, b ) { + if ( Math.abs( s ) < 0.001 ) s = 1; - var ax = a.x, ay = a.y, az = a.z; - var bx = b.x, by = b.y, bz = b.z; + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - return this; + return this; - }, + }, - projectOnVector: function ( v ) { + min: function ( v ) { - // v cannot be the zero v + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - var scalar = v.dot( this ) / v.lengthSq(); + return this; - return this.copy( v ).multiplyScalar( scalar ); + }, - }, + max: function ( v ) { - projectOnPlane: function ( planeNormal ) { + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - _vector.copy( this ).projectOnVector( planeNormal ); + return this; - return this.sub( _vector ); + }, - }, + clamp: function ( min, max ) { - reflect: function ( normal ) { + // assumes min < max, componentwise - // reflect incident vector off plane orthogonal to normal - // normal is assumed to have unit length + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); + return this; - }, + }, - angleTo: function ( v ) { + clampScalar: function ( minVal, maxVal ) { - var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); + this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); - if ( denominator === 0 ) { console.error( 'THREE.Vector3: angleTo() can\'t handle zero length vectors.' ); } + return this; - var theta = this.dot( v ) / denominator; + }, - // clamp, to handle numerical problems + clampLength: function ( min, max ) { - return Math.acos( _Math.clamp( theta, - 1, 1 ) ); + var length = this.length(); - }, + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - distanceTo: function ( v ) { + }, - return Math.sqrt( this.distanceToSquared( v ) ); + floor: function () { - }, + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - distanceToSquared: function ( v ) { + return this; - var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + }, - return dx * dx + dy * dy + dz * dz; + ceil: function () { - }, + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - manhattanDistanceTo: function ( v ) { + return this; - return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); + }, - }, + round: function () { - setFromSpherical: function ( s ) { + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); + return this; - }, + }, - setFromSphericalCoords: function ( radius, phi, theta ) { + roundToZero: function () { - var sinPhiRadius = Math.sin( phi ) * radius; + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - this.x = sinPhiRadius * Math.sin( theta ); - this.y = Math.cos( phi ) * radius; - this.z = sinPhiRadius * Math.cos( theta ); + return this; - return this; + }, - }, + negate: function () { - setFromCylindrical: function ( c ) { + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); + return this; - }, + }, - setFromCylindricalCoords: function ( radius, theta, y ) { + dot: function ( v ) { - this.x = radius * Math.sin( theta ); - this.y = y; - this.z = radius * Math.cos( theta ); + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - return this; + }, - }, + lengthSq: function () { - setFromMatrixPosition: function ( m ) { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - var e = m.elements; + }, - this.x = e[ 12 ]; - this.y = e[ 13 ]; - this.z = e[ 14 ]; + length: function () { - return this; + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - }, + }, - setFromMatrixScale: function ( m ) { + manhattanLength: function () { - var sx = this.setFromMatrixColumn( m, 0 ).length(); - var sy = this.setFromMatrixColumn( m, 1 ).length(); - var sz = this.setFromMatrixColumn( m, 2 ).length(); + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - this.x = sx; - this.y = sy; - this.z = sz; + }, - return this; + normalize: function () { - }, + return this.divideScalar( this.length() || 1 ); - setFromMatrixColumn: function ( m, index ) { + }, - return this.fromArray( m.elements, index * 4 ); + setLength: function ( length ) { - }, + return this.normalize().multiplyScalar( length ); - equals: function ( v ) { + }, - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); + lerp: function ( v, alpha ) { - }, + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; - fromArray: function ( array, offset ) { + return this; - if ( offset === undefined ) { offset = 0; } + }, - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; + lerpVectors: function ( v1, v2, alpha ) { - return this; + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; + this.w = v1.w + ( v2.w - v1.w ) * alpha; - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + equals: function ( v ) { - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - return array; + }, - }, + fromArray: function ( array, offset ) { - fromBufferAttribute: function ( attribute, index, offset ) { + if ( offset === undefined ) offset = 0; - if ( offset !== undefined ) { + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); + return this; - } + }, - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); + toArray: function ( array, offset ) { - return this; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - } ); + return array; - /** - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw - */ + }, - var _vector$1 = new Vector3(); + fromBufferAttribute: function ( attribute, index, offset ) { - function Matrix3() { + if ( offset !== undefined ) { - this.elements = [ + console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + } - ]; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); - if ( arguments.length > 0 ) { + return this; - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + }, - } + random: function () { - } + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); - Object.assign( Matrix3.prototype, { + return this; - isMatrix3: true, + } - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { +} ); - var te = this.elements; +/** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; +/* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers +*/ +function WebGLRenderTarget( width, height, options ) { - return this; + this.width = width; + this.height = height; - }, + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - identity: function () { + this.viewport = new Vector4( 0, 0, width, height ); - this.set( + options = options || {}; - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - ); + this.texture.image = {}; + this.texture.image.width = width; + this.texture.image.height = height; - return this; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; - }, + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - clone: function () { +} - return new this.constructor().fromArray( this.elements ); +WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - }, + constructor: WebGLRenderTarget, - copy: function ( m ) { + isWebGLRenderTarget: true, - var te = this.elements; - var me = m.elements; + setSize: function ( width, height ) { - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; - te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; - te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + if ( this.width !== width || this.height !== height ) { - return this; + this.width = width; + this.height = height; - }, + this.texture.image.width = width; + this.texture.image.height = height; - setFromMatrix4: function ( m ) { + this.dispose(); - var me = m.elements; + } - this.set( + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + }, - ); + clone: function () { - return this; + return new this.constructor().copy( this ); - }, + }, - applyToBufferAttribute: function ( attribute ) { + copy: function ( source ) { - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + this.width = source.width; + this.height = source.height; - _vector$1.x = attribute.getX( i ); - _vector$1.y = attribute.getY( i ); - _vector$1.z = attribute.getZ( i ); + this.viewport.copy( source.viewport ); - _vector$1.applyMatrix3( this ); + this.texture = source.texture.clone(); - attribute.setXYZ( i, _vector$1.x, _vector$1.y, _vector$1.z ); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - } + return this; - return attribute; + }, - }, + dispose: function () { - multiply: function ( m ) { + this.dispatchEvent( { type: 'dispose' } ); - return this.multiplyMatrices( this, m ); + } - }, +} ); - premultiply: function ( m ) { +/** + * @author Mugen87 / https://github.com/Mugen87 + * @author Matt DesLauriers / @mattdesl + */ - return this.multiplyMatrices( m, this ); +function WebGLMultisampleRenderTarget( width, height, options ) { - }, + WebGLRenderTarget.call( this, width, height, options ); - multiplyMatrices: function ( a, b ) { + this.samples = 4; - var ae = a.elements; - var be = b.elements; - var te = this.elements; +} - var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; - var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; - var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; +WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), { - var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; - var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; - var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + constructor: WebGLMultisampleRenderTarget, - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; - te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; - te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + isWebGLMultisampleRenderTarget: true, - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; - te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; - te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + copy: function ( source ) { - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; - te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; - te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + WebGLRenderTarget.prototype.copy.call( this, source ); - return this; + this.samples = source.samples; - }, + return this; - multiplyScalar: function ( s ) { + } - var te = this.elements; +} ); - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - return this; +function Quaternion( x, y, z, w ) { - }, + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; - determinant: function () { +} - var te = this.elements; +Object.assign( Quaternion, { - var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + slerp: function ( qa, qb, qm, t ) { - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + return qm.copy( qa ).slerp( qb, t ); - }, + }, - getInverse: function ( matrix, throwOnDegenerate ) { + slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { - if ( matrix && matrix.isMatrix4 ) { + // fuzz-free, array-based Quaternion SLERP operation - console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." ); + var x0 = src0[ srcOffset0 + 0 ], + y0 = src0[ srcOffset0 + 1 ], + z0 = src0[ srcOffset0 + 2 ], + w0 = src0[ srcOffset0 + 3 ], - } + x1 = src1[ srcOffset1 + 0 ], + y1 = src1[ srcOffset1 + 1 ], + z1 = src1[ srcOffset1 + 2 ], + w1 = src1[ srcOffset1 + 3 ]; - var me = matrix.elements, - te = this.elements, + if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], - n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], - n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], + var s = 1 - t, - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, - det = n11 * t11 + n21 * t12 + n31 * t13; + dir = ( cos >= 0 ? 1 : - 1 ), + sqrSin = 1 - cos * cos; - if ( det === 0 ) { + // Skip the Slerp for tiny steps to avoid numeric problems: + if ( sqrSin > Number.EPSILON ) { - var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0"; + var sin = Math.sqrt( sqrSin ), + len = Math.atan2( sin, cos * dir ); - if ( throwOnDegenerate === true ) { + s = Math.sin( s * len ) / sin; + t = Math.sin( t * len ) / sin; - throw new Error( msg ); + } - } else { + var tDir = t * dir; - console.warn( msg ); + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; - } + // Normalize in case we just did a lerp: + if ( s === 1 - t ) { - return this.identity(); + var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); + + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; } - var detInv = 1 / det; + } - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + dst[ dstOffset ] = x0; + dst[ dstOffset + 1 ] = y0; + dst[ dstOffset + 2 ] = z0; + dst[ dstOffset + 3 ] = w0; - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + }, - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + multiplyQuaternionsFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) { - return this; + var x0 = src0[ srcOffset0 ]; + var y0 = src0[ srcOffset0 + 1 ]; + var z0 = src0[ srcOffset0 + 2 ]; + var w0 = src0[ srcOffset0 + 3 ]; - }, + var x1 = src1[ srcOffset1 ]; + var y1 = src1[ srcOffset1 + 1 ]; + var z1 = src1[ srcOffset1 + 2 ]; + var w1 = src1[ srcOffset1 + 3 ]; - transpose: function () { + dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; - var tmp, m = this.elements; + return dst; - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + } - return this; +} ); - }, +Object.defineProperties( Quaternion.prototype, { - getNormalMatrix: function ( matrix4 ) { + x: { - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + get: function () { - }, + return this._x; - transposeIntoArray: function ( r ) { + }, - var m = this.elements; + set: function ( value ) { - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; + this._x = value; + this._onChangeCallback(); - return this; + } - }, + }, - setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) { + y: { - var c = Math.cos( rotation ); - var s = Math.sin( rotation ); + get: function () { - this.set( - sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, - - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, - 0, 0, 1 - ); + return this._y; }, - scale: function ( sx, sy ) { + set: function ( value ) { - var te = this.elements; + this._y = value; + this._onChangeCallback(); - te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; - te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; + } - return this; + }, - }, + z: { - rotate: function ( theta ) { + get: function () { - var c = Math.cos( theta ); - var s = Math.sin( theta ); + return this._z; - var te = this.elements; + }, - var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; - var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; + set: function ( value ) { - te[ 0 ] = c * a11 + s * a21; - te[ 3 ] = c * a12 + s * a22; - te[ 6 ] = c * a13 + s * a23; + this._z = value; + this._onChangeCallback(); - te[ 1 ] = - s * a11 + c * a21; - te[ 4 ] = - s * a12 + c * a22; - te[ 7 ] = - s * a13 + c * a23; + } - return this; + }, - }, + w: { - translate: function ( tx, ty ) { + get: function () { - var te = this.elements; + return this._w; - te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; - te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; + }, - return this; + set: function ( value ) { - }, + this._w = value; + this._onChangeCallback(); - equals: function ( matrix ) { + } - var te = this.elements; - var me = matrix.elements; + } - for ( var i = 0; i < 9; i ++ ) { +} ); - if ( te[ i ] !== me[ i ] ) { return false; } +Object.assign( Quaternion.prototype, { - } + isQuaternion: true, - return true; + set: function ( x, y, z, w ) { - }, + this._x = x; + this._y = y; + this._z = z; + this._w = w; - fromArray: function ( array, offset ) { + this._onChangeCallback(); - if ( offset === undefined ) { offset = 0; } + return this; - for ( var i = 0; i < 9; i ++ ) { + }, - this.elements[ i ] = array[ i + offset ]; + clone: function () { - } + return new this.constructor( this._x, this._y, this._z, this._w ); - return this; + }, - }, + copy: function ( quaternion ) { - toArray: function ( array, offset ) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + this._onChangeCallback(); - var te = this.elements; + return this; - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + }, - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + setFromEuler: function ( euler, update ) { - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + if ( ! ( euler && euler.isEuler ) ) { - return array; + throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); } - } ); + var x = euler._x, y = euler._y, z = euler._z, order = euler.order; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m - var _canvas; + var cos = Math.cos; + var sin = Math.sin; - var ImageUtils = { + var c1 = cos( x / 2 ); + var c2 = cos( y / 2 ); + var c3 = cos( z / 2 ); - getDataURL: function ( image ) { + var s1 = sin( x / 2 ); + var s2 = sin( y / 2 ); + var s3 = sin( z / 2 ); - var canvas; + switch ( order ) { - if ( typeof HTMLCanvasElement == 'undefined' ) { + case 'XYZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - return image.src; + case 'YXZ': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; - } else if ( image instanceof HTMLCanvasElement ) { + case 'ZXY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - canvas = image; + case 'ZYX': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; - } else { + case 'YZX': + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; - if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); } + case 'XZY': + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; - _canvas.width = image.width; - _canvas.height = image.height; + default: + console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order ); - var context = _canvas.getContext( '2d' ); + } - if ( image instanceof ImageData ) { + if ( update !== false ) this._onChangeCallback(); - context.putImageData( image, 0, 0 ); + return this; - } else { + }, - context.drawImage( image, 0, 0, image.width, image.height ); + setFromAxisAngle: function ( axis, angle ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm - canvas = _canvas; + // assumes axis is normalized - } + var halfAngle = angle / 2, s = Math.sin( halfAngle ); - if ( canvas.width > 2048 || canvas.height > 2048 ) { + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); - return canvas.toDataURL( 'image/jpeg', 0.6 ); + this._onChangeCallback(); - } else { + return this; - return canvas.toDataURL( 'image/png' ); + }, - } + setFromRotationMatrix: function ( m ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - }; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - */ + var te = m.elements, - var textureId = 0; + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], - function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + trace = m11 + m22 + m33, + s; - Object.defineProperty( this, 'id', { value: textureId ++ } ); + if ( trace > 0 ) { - this.uuid = _Math.generateUUID(); + s = 0.5 / Math.sqrt( trace + 1.0 ); - this.name = ''; + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; - this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; - this.mipmaps = []; + } else if ( m11 > m22 && m11 > m33 ) { - this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); - this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; + this._w = ( m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = ( m12 + m21 ) / s; + this._z = ( m13 + m31 ) / s; - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter; + } else if ( m22 > m33 ) { - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); - this.format = format !== undefined ? format : RGBAFormat; - this.type = type !== undefined ? type : UnsignedByteType; + this._w = ( m13 - m31 ) / s; + this._x = ( m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = ( m23 + m32 ) / s; - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); - this.center = new Vector2( 0, 0 ); - this.rotation = 0; + } else { - this.matrixAutoUpdate = true; - this.matrix = new Matrix3(); + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : LinearEncoding; + } - this.version = 0; - this.onUpdate = null; + this._onChangeCallback(); - } + return this; - Texture.DEFAULT_IMAGE = undefined; - Texture.DEFAULT_MAPPING = UVMapping; + }, - Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + setFromUnitVectors: function ( vFrom, vTo ) { - constructor: Texture, + // assumes direction vectors vFrom and vTo are normalized - isTexture: true, + var EPS = 0.000001; - updateMatrix: function () { + var r = vFrom.dot( vTo ) + 1; - this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); + if ( r < EPS ) { - }, + r = 0; - clone: function () { + if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { - return new this.constructor().copy( this ); + this._x = - vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; - }, + } else { - copy: function ( source ) { + this._x = 0; + this._y = - vFrom.z; + this._z = vFrom.y; + this._w = r; - this.name = source.name; + } - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + } else { - this.mapping = source.mapping; + // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + } - this.anisotropy = source.anisotropy; + return this.normalize(); - this.format = source.format; - this.type = source.type; + }, - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); - this.center.copy( source.center ); - this.rotation = source.rotation; + angleTo: function ( q ) { - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrix.copy( source.matrix ); + return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + }, - return this; + rotateTowards: function ( q, step ) { - }, + var angle = this.angleTo( q ); - toJSON: function ( meta ) { + if ( angle === 0 ) return this; - var isRootObject = ( meta === undefined || typeof meta === 'string' ); + var t = Math.min( 1, step / angle ); - if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { + this.slerp( q, t ); - return meta.textures[ this.uuid ]; + return this; - } + }, - var output = { + inverse: function () { - metadata: { - version: 4.5, - type: 'Texture', - generator: 'Texture.toJSON' - }, + // quaternion is assumed to have unit length - uuid: this.uuid, - name: this.name, + return this.conjugate(); - mapping: this.mapping, + }, - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - center: [ this.center.x, this.center.y ], - rotation: this.rotation, + conjugate: function () { - wrap: [ this.wrapS, this.wrapT ], + this._x *= - 1; + this._y *= - 1; + this._z *= - 1; - format: this.format, - type: this.type, - encoding: this.encoding, + this._onChangeCallback(); - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + return this; - flipY: this.flipY, + }, - premultiplyAlpha: this.premultiplyAlpha, - unpackAlignment: this.unpackAlignment + dot: function ( v ) { - }; + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; - if ( this.image !== undefined ) { + }, - // TODO: Move to THREE.Image + lengthSq: function () { - var image = this.image; + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - if ( image.uuid === undefined ) { + }, - image.uuid = _Math.generateUUID(); // UGH + length: function () { - } + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); - if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { + }, - var url; + normalize: function () { - if ( Array.isArray( image ) ) { + var l = this.length(); - // process array of images e.g. CubeTexture + if ( l === 0 ) { - url = []; + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; - for ( var i = 0, l = image.length; i < l; i ++ ) { + } else { - url.push( ImageUtils.getDataURL( image[ i ] ) ); + l = 1 / l; - } + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; - } else { + } - // process single image + this._onChangeCallback(); - url = ImageUtils.getDataURL( image ); + return this; - } + }, - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: url - }; + multiply: function ( q, p ) { - } + if ( p !== undefined ) { - output.image = image.uuid; + console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); - } + } - if ( ! isRootObject ) { + return this.multiplyQuaternions( this, q ); - meta.textures[ this.uuid ] = output; + }, - } + premultiply: function ( q ) { - return output; + return this.multiplyQuaternions( q, this ); - }, + }, - dispose: function () { + multiplyQuaternions: function ( a, b ) { - this.dispatchEvent( { type: 'dispose' } ); + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm - }, + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; - transformUv: function ( uv ) { + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; - if ( this.mapping !== UVMapping ) { return uv; } + this._onChangeCallback(); - uv.applyMatrix3( this.matrix ); + return this; - if ( uv.x < 0 || uv.x > 1 ) { + }, - switch ( this.wrapS ) { + slerp: function ( qb, t ) { - case RepeatWrapping: + if ( t === 0 ) return this; + if ( t === 1 ) return this.copy( qb ); - uv.x = uv.x - Math.floor( uv.x ); - break; + var x = this._x, y = this._y, z = this._z, w = this._w; - case ClampToEdgeWrapping: + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ - uv.x = uv.x < 0 ? 0 : 1; - break; + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; - case MirroredRepeatWrapping: + if ( cosHalfTheta < 0 ) { - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + this._w = - qb._w; + this._x = - qb._x; + this._y = - qb._y; + this._z = - qb._z; - uv.x = Math.ceil( uv.x ) - uv.x; + cosHalfTheta = - cosHalfTheta; - } else { + } else { - uv.x = uv.x - Math.floor( uv.x ); + this.copy( qb ); - } - break; + } - } + if ( cosHalfTheta >= 1.0 ) { - } + this._w = w; + this._x = x; + this._y = y; + this._z = z; - if ( uv.y < 0 || uv.y > 1 ) { + return this; - switch ( this.wrapT ) { + } - case RepeatWrapping: + var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; - uv.y = uv.y - Math.floor( uv.y ); - break; + if ( sqrSinHalfTheta <= Number.EPSILON ) { - case ClampToEdgeWrapping: + var s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; - uv.y = uv.y < 0 ? 0 : 1; - break; + this.normalize(); + this._onChangeCallback(); - case MirroredRepeatWrapping: + return this; - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + } - uv.y = Math.ceil( uv.y ) - uv.y; + var sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); + var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; - } else { + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); - uv.y = uv.y - Math.floor( uv.y ); + this._onChangeCallback(); - } - break; + return this; - } + }, - } + equals: function ( quaternion ) { - if ( this.flipY ) { + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); - uv.y = 1 - uv.y; + }, - } + fromArray: function ( array, offset ) { - return uv; + if ( offset === undefined ) offset = 0; - } + this._x = array[ offset ]; + this._y = array[ offset + 1 ]; + this._z = array[ offset + 2 ]; + this._w = array[ offset + 3 ]; - } ); + this._onChangeCallback(); - Object.defineProperty( Texture.prototype, "needsUpdate", { + return this; - set: function ( value ) { + }, - if ( value === true ) { this.version ++; } + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } ); + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._w; - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + return array; - function Vector4( x, y, z, w ) { + }, - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + fromBufferAttribute: function ( attribute, index ) { - } + this._x = attribute.getX( index ); + this._y = attribute.getY( index ); + this._z = attribute.getZ( index ); + this._w = attribute.getW( index ); - Object.defineProperties( Vector4.prototype, { + return this; - "width": { + }, - get: function () { + _onChange: function ( callback ) { - return this.z; + this._onChangeCallback = callback; - }, + return this; - set: function ( value ) { + }, - this.z = value; + _onChangeCallback: function () {} - } +} ); - }, +/** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - "height": { +var _vector = new Vector3(); +var _quaternion = new Quaternion(); - get: function () { +function Vector3( x, y, z ) { - return this.w; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; - }, +} - set: function ( value ) { +Object.assign( Vector3.prototype, { - this.w = value; + isVector3: true, - } + set: function ( x, y, z ) { - } + this.x = x; + this.y = y; + this.z = z; - } ); + return this; - Object.assign( Vector4.prototype, { + }, - isVector4: true, + setScalar: function ( scalar ) { - set: function ( x, y, z, w ) { + this.x = scalar; + this.y = scalar; + this.z = scalar; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + return this; - return this; + }, - }, + setX: function ( x ) { - setScalar: function ( scalar ) { + this.x = x; - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + return this; - return this; + }, - }, + setY: function ( y ) { - setX: function ( x ) { + this.y = y; - this.x = x; + return this; - return this; + }, - }, + setZ: function ( z ) { - setY: function ( y ) { + this.z = z; - this.y = y; + return this; - return this; + }, - }, + setComponent: function ( index, value ) { - setZ: function ( z ) { + switch ( index ) { - this.z = z; + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + default: throw new Error( 'index is out of range: ' + index ); - return this; + } - }, + return this; - setW: function ( w ) { + }, - this.w = w; + getComponent: function ( index ) { - return this; + switch ( index ) { - }, + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + default: throw new Error( 'index is out of range: ' + index ); - setComponent: function ( index, value ) { + } - switch ( index ) { + }, - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); + clone: function () { - } + return new this.constructor( this.x, this.y, this.z ); - return this; + }, - }, + copy: function ( v ) { - getComponent: function ( index ) { + this.x = v.x; + this.y = v.y; + this.z = v.z; - switch ( index ) { + return this; - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); + }, - } + add: function ( v, w ) { - }, + if ( w !== undefined ) { - clone: function () { + console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - return new this.constructor( this.x, this.y, this.z, this.w ); + } - }, + this.x += v.x; + this.y += v.y; + this.z += v.z; - copy: function ( v ) { + return this; - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + }, - return this; + addScalar: function ( s ) { - }, + this.x += s; + this.y += s; + this.z += s; - add: function ( v, w ) { + return this; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + addVectors: function ( a, b ) { - } + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + return this; - return this; + }, - }, + addScaledVector: function ( v, s ) { - addScalar: function ( s ) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; - this.x += s; - this.y += s; - this.z += s; - this.w += s; + return this; - return this; + }, - }, + sub: function ( v, w ) { - addVectors: function ( a, b ) { + if ( w !== undefined ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - return this; + } - }, + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; - addScaledVector: function ( v, s ) { + return this; - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + }, - return this; + subScalar: function ( s ) { - }, + this.x -= s; + this.y -= s; + this.z -= s; - sub: function ( v, w ) { + return this; - if ( w !== undefined ) { + }, - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + subVectors: function ( a, b ) { - } + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + return this; - return this; + }, - }, + multiply: function ( v, w ) { - subScalar: function ( s ) { + if ( w !== undefined ) { - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); + return this.multiplyVectors( v, w ); - return this; + } - }, + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; - subVectors: function ( a, b ) { + return this; - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + }, - return this; + multiplyScalar: function ( scalar ) { - }, + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; - multiplyScalar: function ( scalar ) { + return this; - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + }, - return this; + multiplyVectors: function ( a, b ) { - }, + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; - applyMatrix4: function ( m ) { + return this; - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + }, - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + applyEuler: function ( euler ) { - return this; + if ( ! ( euler && euler.isEuler ) ) { - }, + console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); - divideScalar: function ( scalar ) { + } - return this.multiplyScalar( 1 / scalar ); + return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); - }, + }, - setAxisAngleFromQuaternion: function ( q ) { + applyAxisAngle: function ( axis, angle ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); - // q is assumed to be normalized + }, - this.w = 2 * Math.acos( q.w ); + applyMatrix3: function ( m ) { - var s = Math.sqrt( 1 - q.w * q.w ); + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - if ( s < 0.0001 ) { + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; + this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; - this.x = 1; - this.y = 0; - this.z = 0; + return this; - } else { + }, - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + applyNormalMatrix: function ( m ) { - } + return this.applyMatrix3( m ).normalize(); - return this; + }, - }, + applyMatrix4: function ( m ) { - setAxisAngleFromRotationMatrix: function ( m ) { + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; + this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + return this; - te = m.elements, + }, - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + applyQuaternion: function ( q ) { - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + var x = this.x, y = this.y, z = this.z; + var qx = q.x, qy = q.y, qz = q.z, qw = q.w; - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + // calculate quat * vector - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; + var iw = - qx * x - qy * y - qz * z; - // this singularity is identity matrix so angle = 0 + // calculate result * inverse quat - this.set( 1, 0, 0, 0 ); + this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; + this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; + this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; - return this; // zero angle, arbitrary axis + return this; - } + }, - // otherwise this singularity is angle = 180 + project: function ( camera ) { - angle = Math.PI; + return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; + }, - if ( ( xx > yy ) && ( xx > zz ) ) { + unproject: function ( camera ) { - // m11 is the largest diagonal term + return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); - if ( xx < epsilon ) { + }, - x = 0; - y = 0.707106781; - z = 0.707106781; + transformDirection: function ( m ) { - } else { + // input: THREE.Matrix4 affine matrix + // vector interpreted as a direction - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + var x = this.x, y = this.y, z = this.z; + var e = m.elements; - } + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; - } else if ( yy > zz ) { + return this.normalize(); - // m22 is the largest diagonal term + }, - if ( yy < epsilon ) { + divide: function ( v ) { - x = 0.707106781; - y = 0; - z = 0.707106781; + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; - } else { + return this; - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + }, - } + divideScalar: function ( scalar ) { - } else { + return this.multiplyScalar( 1 / scalar ); - // m33 is the largest diagonal term so base result on this + }, - if ( zz < epsilon ) { + min: function ( v ) { - x = 0.707106781; - y = 0.707106781; - z = 0; + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); - } else { + return this; - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + }, - } + max: function ( v ) { - } + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); - this.set( x, y, z, angle ); + return this; - return this; // return 180 deg rotation + }, - } + clamp: function ( min, max ) { - // as we have reached here there are no singularities so we can handle normally + // assumes min < max, componentwise - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - if ( Math.abs( s ) < 0.001 ) { s = 1; } + return this; - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case + }, - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + clampScalar: function ( minVal, maxVal ) { - return this; + this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); + this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); + this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - }, + return this; - min: function ( v ) { + }, - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); + clampLength: function ( min, max ) { - return this; + var length = this.length(); - }, + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - max: function ( v ) { + }, - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); + floor: function () { - return this; + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); - }, + return this; - clamp: function ( min, max ) { + }, - // assumes min < max, componentwise + ceil: function () { - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); - return this; + return this; - }, + }, - clampScalar: function ( minVal, maxVal ) { + round: function () { - this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); - this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); - this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); - this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); - return this; + return this; - }, + }, - clampLength: function ( min, max ) { + roundToZero: function () { - var length = this.length(); + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + return this; - }, + }, - floor: function () { + negate: function () { - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; - return this; + return this; - }, + }, - ceil: function () { + dot: function ( v ) { - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + return this.x * v.x + this.y * v.y + this.z * v.z; - return this; + }, - }, + // TODO lengthSquared? - round: function () { + lengthSq: function () { - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); + return this.x * this.x + this.y * this.y + this.z * this.z; - return this; + }, - }, + length: function () { - roundToZero: function () { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); + }, - return this; + manhattanLength: function () { - }, + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); - negate: function () { + }, - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; + normalize: function () { - return this; + return this.divideScalar( this.length() || 1 ); - }, + }, - dot: function ( v ) { + setLength: function ( length ) { - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + return this.normalize().multiplyScalar( length ); - }, + }, - lengthSq: function () { + lerp: function ( v, alpha ) { - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; - }, + return this; - length: function () { + }, - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); + lerpVectors: function ( v1, v2, alpha ) { - }, + this.x = v1.x + ( v2.x - v1.x ) * alpha; + this.y = v1.y + ( v2.y - v1.y ) * alpha; + this.z = v1.z + ( v2.z - v1.z ) * alpha; - manhattanLength: function () { + return this; - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); + }, - }, + cross: function ( v, w ) { - normalize: function () { + if ( w !== undefined ) { - return this.divideScalar( this.length() || 1 ); + console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); + return this.crossVectors( v, w ); - }, + } - setLength: function ( length ) { + return this.crossVectors( this, v ); - return this.normalize().multiplyScalar( length ); + }, - }, + crossVectors: function ( a, b ) { - lerp: function ( v, alpha ) { + var ax = a.x, ay = a.y, az = a.z; + var bx = b.x, by = b.y, bz = b.z; - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; - return this; + return this; - }, + }, - lerpVectors: function ( v1, v2, alpha ) { + projectOnVector: function ( v ) { - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); + var denominator = v.lengthSq(); - }, + if ( denominator === 0 ) return this.set( 0, 0, 0 ); - equals: function ( v ) { + var scalar = v.dot( this ) / denominator; - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); + return this.copy( v ).multiplyScalar( scalar ); - }, + }, - fromArray: function ( array, offset ) { + projectOnPlane: function ( planeNormal ) { - if ( offset === undefined ) { offset = 0; } + _vector.copy( this ).projectOnVector( planeNormal ); - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; + return this.sub( _vector ); - return this; + }, - }, + reflect: function ( normal ) { - toArray: function ( array, offset ) { + // reflect incident vector off plane orthogonal to normal + // normal is assumed to have unit length - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + }, - return array; + angleTo: function ( v ) { - }, + var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); - fromBufferAttribute: function ( attribute, index, offset ) { + if ( denominator === 0 ) return Math.PI / 2; - if ( offset !== undefined ) { + var theta = this.dot( v ) / denominator; - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); + // clamp, to handle numerical problems - } + return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); + }, - return this; + distanceTo: function ( v ) { - } + return Math.sqrt( this.distanceToSquared( v ) ); - } ); + }, - /** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ + distanceToSquared: function ( v ) { - /* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers - */ - function WebGLRenderTarget( width, height, options ) { + var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; - this.width = width; - this.height = height; + return dx * dx + dy * dy + dz * dz; - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; + }, - this.viewport = new Vector4( 0, 0, width, height ); + manhattanDistanceTo: function ( v ) { - options = options || {}; + return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); - this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); + }, - this.texture.image = {}; - this.texture.image.width = width; - this.texture.image.height = height; + setFromSpherical: function ( s ) { - this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; - this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; + }, - } + setFromSphericalCoords: function ( radius, phi, theta ) { - WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + var sinPhiRadius = Math.sin( phi ) * radius; - constructor: WebGLRenderTarget, + this.x = sinPhiRadius * Math.sin( theta ); + this.y = Math.cos( phi ) * radius; + this.z = sinPhiRadius * Math.cos( theta ); - isWebGLRenderTarget: true, + return this; - setSize: function ( width, height ) { + }, - if ( this.width !== width || this.height !== height ) { + setFromCylindrical: function ( c ) { - this.width = width; - this.height = height; + return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); - this.texture.image.width = width; - this.texture.image.height = height; + }, - this.dispose(); + setFromCylindricalCoords: function ( radius, theta, y ) { - } + this.x = radius * Math.sin( theta ); + this.y = y; + this.z = radius * Math.cos( theta ); - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); + return this; - }, + }, - clone: function () { + setFromMatrixPosition: function ( m ) { - return new this.constructor().copy( this ); + var e = m.elements; - }, + this.x = e[ 12 ]; + this.y = e[ 13 ]; + this.z = e[ 14 ]; - copy: function ( source ) { + return this; - this.width = source.width; - this.height = source.height; + }, - this.viewport.copy( source.viewport ); + setFromMatrixScale: function ( m ) { - this.texture = source.texture.clone(); + var sx = this.setFromMatrixColumn( m, 0 ).length(); + var sy = this.setFromMatrixColumn( m, 1 ).length(); + var sz = this.setFromMatrixColumn( m, 2 ).length(); - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; + this.x = sx; + this.y = sy; + this.z = sz; - return this; + return this; - }, + }, - dispose: function () { + setFromMatrixColumn: function ( m, index ) { - this.dispatchEvent( { type: 'dispose' } ); + return this.fromArray( m.elements, index * 4 ); - } + }, - } ); + setFromMatrix3Column: function ( m, index ) { - /** - * @author Mugen87 / https://github.com/Mugen87 - * @author Matt DesLauriers / @mattdesl - */ + return this.fromArray( m.elements, index * 3 ); - function WebGLMultisampleRenderTarget( width, height, options ) { + }, - WebGLRenderTarget.call( this, width, height, options ); + equals: function ( v ) { - this.samples = 4; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); - } + }, - WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), { + fromArray: function ( array, offset ) { - constructor: WebGLMultisampleRenderTarget, + if ( offset === undefined ) offset = 0; - isWebGLMultisampleRenderTarget: true, + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; - copy: function ( source ) { + return this; - WebGLRenderTarget.prototype.copy.call( this, source ); + }, - this.samples = source.samples; + toArray: function ( array, offset ) { - return this; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - } + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; - } ); + return array; - var _v1 = new Vector3(); - var _m1 = new Matrix4(); - var _zero = new Vector3( 0, 0, 0 ); - var _one = new Vector3( 1, 1, 1 ); - var _x = new Vector3(); - var _y = new Vector3(); - var _z = new Vector3(); + }, - /** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + fromBufferAttribute: function ( attribute, index, offset ) { - function Matrix4() { + if ( offset !== undefined ) { - this.elements = [ + console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + } - ]; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); - if ( arguments.length > 0 ) { + return this; - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + }, - } + random: function () { + + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + + return this; } - Object.assign( Matrix4.prototype, { +} ); - isMatrix4: true, +var _v1 = new Vector3(); +var _m1 = new Matrix4(); +var _zero = new Vector3( 0, 0, 0 ); +var _one = new Vector3( 1, 1, 1 ); +var _x = new Vector3(); +var _y = new Vector3(); +var _z = new Vector3(); - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author jordi_ros / http://plattsoft.com + * @author D1plo1d / http://github.com/D1plo1d + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author timknip / http://www.floorplanner.com/ + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - var te = this.elements; +function Matrix4() { - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + this.elements = [ - return this; + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - }, + ]; - identity: function () { + if ( arguments.length > 0 ) { - this.set( + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + } - ); +} - return this; +Object.assign( Matrix4.prototype, { - }, + isMatrix4: true, - clone: function () { + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - return new Matrix4().fromArray( this.elements ); + var te = this.elements; - }, + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - copy: function ( m ) { + return this; - var te = this.elements; - var me = m.elements; + }, - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + identity: function () { - return this; + this.set( - }, + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - copyPosition: function ( m ) { + ); - var te = this.elements, me = m.elements; + return this; - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + }, - return this; + clone: function () { - }, + return new Matrix4().fromArray( this.elements ); - extractBasis: function ( xAxis, yAxis, zAxis ) { + }, - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + copy: function ( m ) { - return this; + var te = this.elements; + var me = m.elements; - }, + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; - makeBasis: function ( xAxis, yAxis, zAxis ) { + return this; - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 - ); + }, - return this; + copyPosition: function ( m ) { - }, + var te = this.elements, me = m.elements; - extractRotation: function ( m ) { + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - // this method does not support reflection matrices + return this; - var te = this.elements; - var me = m.elements; + }, - var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); + extractBasis: function ( xAxis, yAxis, zAxis ) { - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; - te[ 3 ] = 0; + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; - te[ 7 ] = 0; + return this; - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; - te[ 11 ] = 0; + }, - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + makeBasis: function ( xAxis, yAxis, zAxis ) { - return this; + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); - }, + return this; - makeRotationFromEuler: function ( euler ) { + }, - if ( ! ( euler && euler.isEuler ) ) { + extractRotation: function ( m ) { - console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + // this method does not support reflection matrices - } + var te = this.elements; + var me = m.elements; - var te = this.elements; + var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; + te[ 3 ] = 0; - if ( euler.order === 'XYZ' ) { + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; + te[ 7 ] = 0; - var ae = a * e, af = a * f, be = b * e, bf = b * f; + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; + te[ 11 ] = 0; - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + return this; - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + }, - } else if ( euler.order === 'YXZ' ) { + makeRotationFromEuler: function ( euler ) { - var ce = c * e, cf = c * f, de = d * e, df = d * f; + if ( ! ( euler && euler.isEuler ) ) { - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + } - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + var te = this.elements; - } else if ( euler.order === 'ZXY' ) { + var x = euler.x, y = euler.y, z = euler.z; + var a = Math.cos( x ), b = Math.sin( x ); + var c = Math.cos( y ), d = Math.sin( y ); + var e = Math.cos( z ), f = Math.sin( z ); - var ce = c * e, cf = c * f, de = d * e, df = d * f; + if ( euler.order === 'XYZ' ) { - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - } else if ( euler.order === 'ZYX' ) { + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - var ae = a * e, af = a * f, be = b * e, bf = b * f; + } else if ( euler.order === 'YXZ' ) { - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - } else if ( euler.order === 'YZX' ) { + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } else if ( euler.order === 'ZXY' ) { - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - } else if ( euler.order === 'XZY' ) { + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + } else if ( euler.order === 'ZYX' ) { - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - } + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - // bottom row - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + } else if ( euler.order === 'YZX' ) { - // last column - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - return this; + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - }, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - makeRotationFromQuaternion: function ( q ) { + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - return this.compose( _zero, q, _one ); + } else if ( euler.order === 'XZY' ) { - }, + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - lookAt: function ( eye, target, up ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - var te = this.elements; + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - _z.subVectors( eye, target ); + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - if ( _z.lengthSq() === 0 ) { + } - // eye and target are in the same position + // bottom row + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - _z.z = 1; + // last column + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - } + return this; - _z.normalize(); - _x.crossVectors( up, _z ); + }, - if ( _x.lengthSq() === 0 ) { + makeRotationFromQuaternion: function ( q ) { - // up and z are parallel + return this.compose( _zero, q, _one ); - if ( Math.abs( up.z ) === 1 ) { + }, - _z.x += 0.0001; + lookAt: function ( eye, target, up ) { - } else { + var te = this.elements; - _z.z += 0.0001; + _z.subVectors( eye, target ); - } + if ( _z.lengthSq() === 0 ) { - _z.normalize(); - _x.crossVectors( up, _z ); + // eye and target are in the same position - } + _z.z = 1; - _x.normalize(); - _y.crossVectors( _z, _x ); + } - te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; - te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; - te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; + _z.normalize(); + _x.crossVectors( up, _z ); - return this; + if ( _x.lengthSq() === 0 ) { - }, + // up and z are parallel + + if ( Math.abs( up.z ) === 1 ) { - multiply: function ( m, n ) { + _z.x += 0.0001; - if ( n !== undefined ) { + } else { - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + _z.z += 0.0001; } - return this.multiplyMatrices( this, m ); + _z.normalize(); + _x.crossVectors( up, _z ); - }, + } - premultiply: function ( m ) { + _x.normalize(); + _y.crossVectors( _z, _x ); - return this.multiplyMatrices( m, this ); + te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; + te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; + te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; - }, + return this; - multiplyMatrices: function ( a, b ) { + }, - var ae = a.elements; - var be = b.elements; - var te = this.elements; + multiply: function ( m, n ) { - var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + if ( n !== undefined ) { - var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + } - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + return this.multiplyMatrices( this, m ); - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + }, - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + premultiply: function ( m ) { - return this; + return this.multiplyMatrices( m, this ); - }, + }, - multiplyScalar: function ( s ) { + multiplyMatrices: function ( a, b ) { - var te = this.elements; + var ae = a.elements; + var be = b.elements; + var te = this.elements; - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - return this; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - }, + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - applyToBufferAttribute: function ( attribute ) { + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - _v1.x = attribute.getX( i ); - _v1.y = attribute.getY( i ); - _v1.z = attribute.getZ( i ); + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; - _v1.applyMatrix4( this ); + return this; - attribute.setXYZ( i, _v1.x, _v1.y, _v1.z ); + }, - } + multiplyScalar: function ( s ) { - return attribute; + var te = this.elements; - }, + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; - determinant: function () { - - var te = this.elements; - - var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) + return this; - ); + }, + + determinant: function () { + + var te = this.elements; + + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) - }, + ); - transpose: function () { + }, - var te = this.elements; - var tmp; + transpose: function () { - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + var te = this.elements; + var tmp; - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; - return this; + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; - }, + return this; - setPosition: function ( x, y, z ) { + }, - var te = this.elements; + setPosition: function ( x, y, z ) { - if ( x.isVector3 ) { + var te = this.elements; - te[ 12 ] = x.x; - te[ 13 ] = x.y; - te[ 14 ] = x.z; + if ( x.isVector3 ) { - } else { + te[ 12 ] = x.x; + te[ 13 ] = x.y; + te[ 14 ] = x.z; - te[ 12 ] = x; - te[ 13 ] = y; - te[ 14 ] = z; + } else { - } + te[ 12 ] = x; + te[ 13 ] = y; + te[ 14 ] = z; - return this; + } - }, + return this; - getInverse: function ( m, throwOnDegenerate ) { + }, - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + getInverse: function ( m, throwOnDegenerate ) { - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], - n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], - n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], - n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], + if ( throwOnDegenerate !== undefined ) { - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." ); - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + } - if ( det === 0 ) { + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0"; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - if ( throwOnDegenerate === true ) { + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - throw new Error( msg ); + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - } else { + if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - console.warn( msg ); + var detInv = 1 / det; - } + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - return this.identity(); + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - } + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - var detInv = 1 / det; + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + return this; - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + }, - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + scale: function ( v ) { - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + var te = this.elements; + var x = v.x, y = v.y, z = v.z; - return this; + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; - }, + return this; - scale: function ( v ) { + }, - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + getMaxScaleOnAxis: function () { - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + var te = this.elements; - return this; + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; - }, + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); - getMaxScaleOnAxis: function () { + }, - var te = this.elements; + makeTranslation: function ( x, y, z ) { - var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + this.set( - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 - }, + ); - makeTranslation: function ( x, y, z ) { + return this; - this.set( + }, - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + makeRotationX: function ( theta ) { - ); + var c = Math.cos( theta ), s = Math.sin( theta ); - return this; + this.set( - }, + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - makeRotationX: function ( theta ) { + ); - var c = Math.cos( theta ), s = Math.sin( theta ); + return this; - this.set( + }, - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + makeRotationY: function ( theta ) { - ); + var c = Math.cos( theta ), s = Math.sin( theta ); - return this; + this.set( - }, + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - makeRotationY: function ( theta ) { + ); - var c = Math.cos( theta ), s = Math.sin( theta ); + return this; - this.set( + }, - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + makeRotationZ: function ( theta ) { - ); + var c = Math.cos( theta ), s = Math.sin( theta ); - return this; + this.set( - }, + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - makeRotationZ: function ( theta ) { + ); - var c = Math.cos( theta ), s = Math.sin( theta ); + return this; - this.set( + }, - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + makeRotationAxis: function ( axis, angle ) { - ); + // Based on http://www.gamedev.net/reference/articles/article1199.asp - return this; + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - }, + this.set( - makeRotationAxis: function ( axis, angle ) { + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - // Based on http://www.gamedev.net/reference/articles/article1199.asp + ); - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; + return this; - this.set( + }, - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 + makeScale: function ( x, y, z ) { - ); + this.set( - return this; + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - }, + ); - makeScale: function ( x, y, z ) { + return this; - this.set( + }, - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + makeShear: function ( x, y, z ) { - ); + this.set( - return this; + 1, y, z, 0, + x, 1, z, 0, + x, y, 1, 0, + 0, 0, 0, 1 - }, + ); - makeShear: function ( x, y, z ) { + return this; - this.set( + }, - 1, y, z, 0, - x, 1, z, 0, - x, y, 1, 0, - 0, 0, 0, 1 + compose: function ( position, quaternion, scale ) { - ); + var te = this.elements; - return this; + var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + var x2 = x + x, y2 = y + y, z2 = z + z; + var xx = x * x2, xy = x * y2, xz = x * z2; + var yy = y * y2, yz = y * z2, zz = z * z2; + var wx = w * x2, wy = w * y2, wz = w * z2; - }, + var sx = scale.x, sy = scale.y, sz = scale.z; - compose: function ( position, quaternion, scale ) { + te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; + te[ 1 ] = ( xy + wz ) * sx; + te[ 2 ] = ( xz - wy ) * sx; + te[ 3 ] = 0; - var te = this.elements; + te[ 4 ] = ( xy - wz ) * sy; + te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; + te[ 6 ] = ( yz + wx ) * sy; + te[ 7 ] = 0; - var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + te[ 8 ] = ( xz + wy ) * sz; + te[ 9 ] = ( yz - wx ) * sz; + te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; + te[ 11 ] = 0; - var sx = scale.x, sy = scale.y, sz = scale.z; + te[ 12 ] = position.x; + te[ 13 ] = position.y; + te[ 14 ] = position.z; + te[ 15 ] = 1; - te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; - te[ 1 ] = ( xy + wz ) * sx; - te[ 2 ] = ( xz - wy ) * sx; - te[ 3 ] = 0; + return this; - te[ 4 ] = ( xy - wz ) * sy; - te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; - te[ 6 ] = ( yz + wx ) * sy; - te[ 7 ] = 0; + }, - te[ 8 ] = ( xz + wy ) * sz; - te[ 9 ] = ( yz - wx ) * sz; - te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; - te[ 11 ] = 0; + decompose: function ( position, quaternion, scale ) { - te[ 12 ] = position.x; - te[ 13 ] = position.y; - te[ 14 ] = position.z; - te[ 15 ] = 1; + var te = this.elements; - return this; + var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - }, + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) sx = - sx; - decompose: function ( position, quaternion, scale ) { + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - var te = this.elements; + // scale the rotation part + _m1.copy( this ); - var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) { sx = - sx; } + _m1.elements[ 0 ] *= invSX; + _m1.elements[ 1 ] *= invSX; + _m1.elements[ 2 ] *= invSX; - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + _m1.elements[ 4 ] *= invSY; + _m1.elements[ 5 ] *= invSY; + _m1.elements[ 6 ] *= invSY; - // scale the rotation part - _m1.copy( this ); + _m1.elements[ 8 ] *= invSZ; + _m1.elements[ 9 ] *= invSZ; + _m1.elements[ 10 ] *= invSZ; - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + quaternion.setFromRotationMatrix( _m1 ); - _m1.elements[ 0 ] *= invSX; - _m1.elements[ 1 ] *= invSX; - _m1.elements[ 2 ] *= invSX; + scale.x = sx; + scale.y = sy; + scale.z = sz; - _m1.elements[ 4 ] *= invSY; - _m1.elements[ 5 ] *= invSY; - _m1.elements[ 6 ] *= invSY; + return this; - _m1.elements[ 8 ] *= invSZ; - _m1.elements[ 9 ] *= invSZ; - _m1.elements[ 10 ] *= invSZ; + }, - quaternion.setFromRotationMatrix( _m1 ); + makePerspective: function ( left, right, top, bottom, near, far ) { - scale.x = sx; - scale.y = sy; - scale.z = sz; + if ( far === undefined ) { - return this; + console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); - }, + } - makePerspective: function ( left, right, top, bottom, near, far ) { + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - if ( far === undefined ) { + var a = ( right + left ) / ( right - left ); + var b = ( top + bottom ) / ( top - bottom ); + var c = - ( far + near ) / ( far - near ); + var d = - 2 * far * near / ( far - near ); - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; - } + return this; - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + }, - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); + makeOrthographic: function ( left, right, top, bottom, near, far ) { - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - return this; + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; - }, + te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; - makeOrthographic: function ( left, right, top, bottom, near, far ) { + return this; - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + }, - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + equals: function ( matrix ) { - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + var te = this.elements; + var me = matrix.elements; - return this; + for ( var i = 0; i < 16; i ++ ) { - }, + if ( te[ i ] !== me[ i ] ) return false; - equals: function ( matrix ) { + } - var te = this.elements; - var me = matrix.elements; + return true; - for ( var i = 0; i < 16; i ++ ) { + }, - if ( te[ i ] !== me[ i ] ) { return false; } + fromArray: function ( array, offset ) { - } + if ( offset === undefined ) offset = 0; - return true; + for ( var i = 0; i < 16; i ++ ) { - }, + this.elements[ i ] = array[ i + offset ]; - fromArray: function ( array, offset ) { + } - if ( offset === undefined ) { offset = 0; } + return this; - for ( var i = 0; i < 16; i ++ ) { + }, - this.elements[ i ] = array[ i + offset ]; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return this; + var te = this.elements; - }, + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - toArray: function ( array, offset ) { + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - var te = this.elements; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + return array; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + } - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; +} ); - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - return array; +var _matrix = new Matrix4(); +var _quaternion$1 = new Quaternion(); - } +function Euler( x, y, z, order ) { - } ); + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ +} - var _matrix = new Matrix4(); - var _quaternion$1 = new Quaternion(); +Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - function Euler( x, y, z, order ) { +Euler.DefaultOrder = 'XYZ'; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || Euler.DefaultOrder; +Object.defineProperties( Euler.prototype, { - } + x: { - Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + get: function () { - Euler.DefaultOrder = 'XYZ'; + return this._x; - Object.defineProperties( Euler.prototype, { + }, - x: { + set: function ( value ) { - get: function () { + this._x = value; + this._onChangeCallback(); - return this._x; + } - }, + }, - set: function ( value ) { + y: { - this._x = value; - this._onChangeCallback(); + get: function () { - } + return this._y; }, - y: { + set: function ( value ) { - get: function () { + this._y = value; + this._onChangeCallback(); - return this._y; + } - }, + }, - set: function ( value ) { + z: { - this._y = value; - this._onChangeCallback(); + get: function () { - } + return this._z; }, - z: { + set: function ( value ) { - get: function () { + this._z = value; + this._onChangeCallback(); - return this._z; + } - }, + }, - set: function ( value ) { + order: { - this._z = value; - this._onChangeCallback(); + get: function () { - } + return this._order; }, - order: { - - get: function () { - - return this._order; - - }, + set: function ( value ) { - set: function ( value ) { + this._order = value; + this._onChangeCallback(); - this._order = value; - this._onChangeCallback(); + } - } + } - } +} ); - } ); +Object.assign( Euler.prototype, { - Object.assign( Euler.prototype, { + isEuler: true, - isEuler: true, + set: function ( x, y, z, order ) { - set: function ( x, y, z, order ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + this._onChangeCallback(); - this._onChangeCallback(); + return this; - return this; + }, - }, + clone: function () { - clone: function () { + return new this.constructor( this._x, this._y, this._z, this._order ); - return new this.constructor( this._x, this._y, this._z, this._order ); + }, - }, + copy: function ( euler ) { - copy: function ( euler ) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + this._onChangeCallback(); - this._onChangeCallback(); + return this; - return this; + }, - }, + setFromRotationMatrix: function ( m, order, update ) { - setFromRotationMatrix: function ( m, order, update ) { + var clamp = MathUtils.clamp; - var clamp = _Math.clamp; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + var te = m.elements; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - var te = m.elements; - var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + order = order || this._order; - order = order || this._order; + switch ( order ) { - if ( order === 'XYZ' ) { + case 'XYZ': this._y = Math.asin( clamp( m13, - 1, 1 ) ); @@ -4936,7 +5054,9 @@ } - } else if ( order === 'YXZ' ) { + break; + + case 'YXZ': this._x = Math.asin( - clamp( m23, - 1, 1 ) ); @@ -4952,7 +5072,9 @@ } - } else if ( order === 'ZXY' ) { + break; + + case 'ZXY': this._x = Math.asin( clamp( m32, - 1, 1 ) ); @@ -4968,7 +5090,9 @@ } - } else if ( order === 'ZYX' ) { + break; + + case 'ZYX': this._y = Math.asin( - clamp( m31, - 1, 1 ) ); @@ -4984,7 +5108,9 @@ } - } else if ( order === 'YZX' ) { + break; + + case 'YZX': this._z = Math.asin( clamp( m21, - 1, 1 ) ); @@ -5000,7 +5126,9 @@ } - } else if ( order === 'XZY' ) { + break; + + case 'XZY': this._z = Math.asin( - clamp( m12, - 1, 1 ) ); @@ -5016,24470 +5144,24334 @@ } - } else { + break; - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + default: - } + console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order ); - this._order = order; + } - if ( update !== false ) { this._onChangeCallback(); } + this._order = order; - return this; + if ( update !== false ) this._onChangeCallback(); - }, + return this; - setFromQuaternion: function ( q, order, update ) { + }, - _matrix.makeRotationFromQuaternion( q ); + setFromQuaternion: function ( q, order, update ) { - return this.setFromRotationMatrix( _matrix, order, update ); + _matrix.makeRotationFromQuaternion( q ); - }, + return this.setFromRotationMatrix( _matrix, order, update ); - setFromVector3: function ( v, order ) { + }, - return this.set( v.x, v.y, v.z, order || this._order ); + setFromVector3: function ( v, order ) { - }, + return this.set( v.x, v.y, v.z, order || this._order ); - reorder: function ( newOrder ) { + }, - // WARNING: this discards revolution information -bhouston + reorder: function ( newOrder ) { - _quaternion$1.setFromEuler( this ); + // WARNING: this discards revolution information -bhouston - return this.setFromQuaternion( _quaternion$1, newOrder ); + _quaternion$1.setFromEuler( this ); - }, + return this.setFromQuaternion( _quaternion$1, newOrder ); - equals: function ( euler ) { + }, - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + equals: function ( euler ) { - }, + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); - fromArray: function ( array ) { + }, - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; } + fromArray: function ( array ) { - this._onChangeCallback(); + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - return this; + this._onChangeCallback(); - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + toArray: function ( array, offset ) { - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - return array; + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - }, + return array; - toVector3: function ( optionalResult ) { + }, - if ( optionalResult ) { + toVector3: function ( optionalResult ) { - return optionalResult.set( this._x, this._y, this._z ); + if ( optionalResult ) { - } else { + return optionalResult.set( this._x, this._y, this._z ); - return new Vector3( this._x, this._y, this._z ); + } else { - } + return new Vector3( this._x, this._y, this._z ); - }, + } - _onChange: function ( callback ) { + }, - this._onChangeCallback = callback; + _onChange: function ( callback ) { - return this; + this._onChangeCallback = callback; - }, + return this; - _onChangeCallback: function () {} + }, - } ); + _onChangeCallback: function () {} - /** - * @author mrdoob / http://mrdoob.com/ - */ +} ); - function Layers() { +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.mask = 1 | 0; +function Layers() { - } + this.mask = 1 | 0; - Object.assign( Layers.prototype, { +} - set: function ( channel ) { +Object.assign( Layers.prototype, { - this.mask = 1 << channel | 0; + set: function ( channel ) { - }, + this.mask = 1 << channel | 0; - enable: function ( channel ) { + }, - this.mask |= 1 << channel | 0; + enable: function ( channel ) { - }, + this.mask |= 1 << channel | 0; - enableAll: function () { + }, - this.mask = 0xffffffff | 0; + enableAll: function () { - }, + this.mask = 0xffffffff | 0; - toggle: function ( channel ) { + }, - this.mask ^= 1 << channel | 0; + toggle: function ( channel ) { - }, + this.mask ^= 1 << channel | 0; - disable: function ( channel ) { + }, - this.mask &= ~ ( 1 << channel | 0 ); + disable: function ( channel ) { - }, + this.mask &= ~ ( 1 << channel | 0 ); - disableAll: function () { + }, - this.mask = 0; + disableAll: function () { - }, + this.mask = 0; - test: function ( layers ) { + }, - return ( this.mask & layers.mask ) !== 0; + test: function ( layers ) { - } + return ( this.mask & layers.mask ) !== 0; - } ); + } - var _object3DId = 0; +} ); - var _v1$1 = new Vector3(); - var _q1 = new Quaternion(); - var _m1$1 = new Matrix4(); - var _target = new Vector3(); +let _object3DId = 0; - var _position = new Vector3(); - var _scale = new Vector3(); - var _quaternion$2 = new Quaternion(); +const _v1$1 = new Vector3(); +const _q1 = new Quaternion(); +const _m1$1 = new Matrix4(); +const _target = new Vector3(); - var _xAxis = new Vector3( 1, 0, 0 ); - var _yAxis = new Vector3( 0, 1, 0 ); - var _zAxis = new Vector3( 0, 0, 1 ); +const _position = new Vector3(); +const _scale = new Vector3(); +const _quaternion$2 = new Quaternion(); - var _addedEvent = { type: 'added' }; - var _removedEvent = { type: 'removed' }; +const _xAxis = new Vector3( 1, 0, 0 ); +const _yAxis = new Vector3( 0, 1, 0 ); +const _zAxis = new Vector3( 0, 0, 1 ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author elephantatwork / www.elephantatwork.ch - */ +const _addedEvent = { type: 'added' }; +const _removedEvent = { type: 'removed' }; - function Object3D() { +/** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author elephantatwork / www.elephantatwork.ch + */ - Object.defineProperty( this, 'id', { value: _object3DId ++ } ); +function Object3D() { - this.uuid = _Math.generateUUID(); + Object.defineProperty( this, 'id', { value: _object3DId ++ } ); - this.name = ''; - this.type = 'Object3D'; + this.uuid = MathUtils.generateUUID(); - this.parent = null; - this.children = []; + this.name = ''; + this.type = 'Object3D'; - this.up = Object3D.DefaultUp.clone(); + this.parent = null; + this.children = []; - var position = new Vector3(); - var rotation = new Euler(); - var quaternion = new Quaternion(); - var scale = new Vector3( 1, 1, 1 ); + this.up = Object3D.DefaultUp.clone(); - function onRotationChange() { + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - quaternion.setFromEuler( rotation, false ); + function onRotationChange() { - } + quaternion.setFromEuler( rotation, false ); - function onQuaternionChange() { + } - rotation.setFromQuaternion( quaternion, undefined, false ); + function onQuaternionChange() { - } + rotation.setFromQuaternion( quaternion, undefined, false ); - rotation._onChange( onRotationChange ); - quaternion._onChange( onQuaternionChange ); + } - Object.defineProperties( this, { - position: { - configurable: true, - enumerable: true, - value: position - }, - rotation: { - configurable: true, - enumerable: true, - value: rotation - }, - quaternion: { - configurable: true, - enumerable: true, - value: quaternion - }, - scale: { - configurable: true, - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() - } - } ); + rotation._onChange( onRotationChange ); + quaternion._onChange( onQuaternionChange ); - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); + Object.defineProperties( this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - this.layers = new Layers(); - this.visible = true; + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - this.castShadow = false; - this.receiveShadow = false; + this.layers = new Layers(); + this.visible = true; - this.frustumCulled = true; - this.renderOrder = 0; + this.castShadow = false; + this.receiveShadow = false; - this.userData = {}; + this.frustumCulled = true; + this.renderOrder = 0; - } + this.userData = {}; - Object3D.DefaultUp = new Vector3( 0, 1, 0 ); - Object3D.DefaultMatrixAutoUpdate = true; +} - Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { +Object3D.DefaultUp = new Vector3( 0, 1, 0 ); +Object3D.DefaultMatrixAutoUpdate = true; - constructor: Object3D, +Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - isObject3D: true, + constructor: Object3D, - onBeforeRender: function () {}, - onAfterRender: function () {}, + isObject3D: true, - applyMatrix: function ( matrix ) { + onBeforeRender: function () {}, + onAfterRender: function () {}, - if ( this.matrixAutoUpdate ) { this.updateMatrix(); } + applyMatrix4: function ( matrix ) { - this.matrix.premultiply( matrix ); + if ( this.matrixAutoUpdate ) this.updateMatrix(); - this.matrix.decompose( this.position, this.quaternion, this.scale ); + this.matrix.premultiply( matrix ); - }, + this.matrix.decompose( this.position, this.quaternion, this.scale ); - applyQuaternion: function ( q ) { + }, - this.quaternion.premultiply( q ); + applyQuaternion: function ( q ) { - return this; + this.quaternion.premultiply( q ); - }, + return this; - setRotationFromAxisAngle: function ( axis, angle ) { + }, - // assumes axis is normalized + setRotationFromAxisAngle: function ( axis, angle ) { - this.quaternion.setFromAxisAngle( axis, angle ); + // assumes axis is normalized - }, + this.quaternion.setFromAxisAngle( axis, angle ); - setRotationFromEuler: function ( euler ) { + }, - this.quaternion.setFromEuler( euler, true ); + setRotationFromEuler: function ( euler ) { - }, + this.quaternion.setFromEuler( euler, true ); - setRotationFromMatrix: function ( m ) { + }, - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + setRotationFromMatrix: function ( m ) { - this.quaternion.setFromRotationMatrix( m ); + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - }, + this.quaternion.setFromRotationMatrix( m ); - setRotationFromQuaternion: function ( q ) { + }, - // assumes q is normalized + setRotationFromQuaternion: function ( q ) { - this.quaternion.copy( q ); + // assumes q is normalized - }, + this.quaternion.copy( q ); - rotateOnAxis: function ( axis, angle ) { + }, - // rotate object on axis in object space - // axis is assumed to be normalized + rotateOnAxis: function ( axis, angle ) { - _q1.setFromAxisAngle( axis, angle ); + // rotate object on axis in object space + // axis is assumed to be normalized - this.quaternion.multiply( _q1 ); + _q1.setFromAxisAngle( axis, angle ); - return this; + this.quaternion.multiply( _q1 ); - }, + return this; - rotateOnWorldAxis: function ( axis, angle ) { + }, - // rotate object on axis in world space - // axis is assumed to be normalized - // method assumes no rotated parent + rotateOnWorldAxis: function ( axis, angle ) { - _q1.setFromAxisAngle( axis, angle ); + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent - this.quaternion.premultiply( _q1 ); + _q1.setFromAxisAngle( axis, angle ); - return this; + this.quaternion.premultiply( _q1 ); - }, + return this; - rotateX: function ( angle ) { + }, - return this.rotateOnAxis( _xAxis, angle ); + rotateX: function ( angle ) { - }, + return this.rotateOnAxis( _xAxis, angle ); - rotateY: function ( angle ) { + }, - return this.rotateOnAxis( _yAxis, angle ); + rotateY: function ( angle ) { - }, + return this.rotateOnAxis( _yAxis, angle ); - rotateZ: function ( angle ) { + }, - return this.rotateOnAxis( _zAxis, angle ); + rotateZ: function ( angle ) { - }, + return this.rotateOnAxis( _zAxis, angle ); - translateOnAxis: function ( axis, distance ) { + }, - // translate object by distance along axis in object space - // axis is assumed to be normalized + translateOnAxis: function ( axis, distance ) { - _v1$1.copy( axis ).applyQuaternion( this.quaternion ); + // translate object by distance along axis in object space + // axis is assumed to be normalized - this.position.add( _v1$1.multiplyScalar( distance ) ); + _v1$1.copy( axis ).applyQuaternion( this.quaternion ); - return this; + this.position.add( _v1$1.multiplyScalar( distance ) ); - }, + return this; - translateX: function ( distance ) { + }, - return this.translateOnAxis( _xAxis, distance ); + translateX: function ( distance ) { - }, + return this.translateOnAxis( _xAxis, distance ); - translateY: function ( distance ) { + }, - return this.translateOnAxis( _yAxis, distance ); + translateY: function ( distance ) { - }, + return this.translateOnAxis( _yAxis, distance ); - translateZ: function ( distance ) { + }, - return this.translateOnAxis( _zAxis, distance ); + translateZ: function ( distance ) { - }, + return this.translateOnAxis( _zAxis, distance ); - localToWorld: function ( vector ) { + }, - return vector.applyMatrix4( this.matrixWorld ); + localToWorld: function ( vector ) { - }, + return vector.applyMatrix4( this.matrixWorld ); - worldToLocal: function ( vector ) { + }, - return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) ); + worldToLocal: function ( vector ) { - }, + return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) ); - lookAt: function ( x, y, z ) { + }, - // This method does not support objects having non-uniformly-scaled parent(s) + lookAt: function ( x, y, z ) { - if ( x.isVector3 ) { + // This method does not support objects having non-uniformly-scaled parent(s) - _target.copy( x ); + if ( x.isVector3 ) { - } else { + _target.copy( x ); - _target.set( x, y, z ); - - } - - var parent = this.parent; - - this.updateWorldMatrix( true, false ); - - _position.setFromMatrixPosition( this.matrixWorld ); + } else { - if ( this.isCamera || this.isLight ) { + _target.set( x, y, z ); - _m1$1.lookAt( _position, _target, this.up ); + } - } else { + var parent = this.parent; - _m1$1.lookAt( _target, _position, this.up ); + this.updateWorldMatrix( true, false ); - } + _position.setFromMatrixPosition( this.matrixWorld ); - this.quaternion.setFromRotationMatrix( _m1$1 ); + if ( this.isCamera || this.isLight ) { - if ( parent ) { + _m1$1.lookAt( _position, _target, this.up ); - _m1$1.extractRotation( parent.matrixWorld ); - _q1.setFromRotationMatrix( _m1$1 ); - this.quaternion.premultiply( _q1.inverse() ); + } else { - } + _m1$1.lookAt( _target, _position, this.up ); - }, + } - add: function ( object ) { + this.quaternion.setFromRotationMatrix( _m1$1 ); - if ( arguments.length > 1 ) { + if ( parent ) { - for ( var i = 0; i < arguments.length; i ++ ) { + _m1$1.extractRotation( parent.matrixWorld ); + _q1.setFromRotationMatrix( _m1$1 ); + this.quaternion.premultiply( _q1.inverse() ); - this.add( arguments[ i ] ); + } - } + }, - return this; + add: function ( object ) { - } + if ( arguments.length > 1 ) { - if ( object === this ) { + for ( var i = 0; i < arguments.length; i ++ ) { - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + this.add( arguments[ i ] ); } - if ( ( object && object.isObject3D ) ) { + return this; - if ( object.parent !== null ) { + } - object.parent.remove( object ); + if ( object === this ) { - } + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - object.parent = this; - this.children.push( object ); + } - object.dispatchEvent( _addedEvent ); + if ( ( object && object.isObject3D ) ) { - } else { + if ( object.parent !== null ) { - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + object.parent.remove( object ); } - return this; - - }, - - remove: function ( object ) { + object.parent = this; + this.children.push( object ); - if ( arguments.length > 1 ) { + object.dispatchEvent( _addedEvent ); - for ( var i = 0; i < arguments.length; i ++ ) { + } else { - this.remove( arguments[ i ] ); + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - } + } - return this; + return this; - } + }, - var index = this.children.indexOf( object ); + remove: function ( object ) { - if ( index !== - 1 ) { + if ( arguments.length > 1 ) { - object.parent = null; - this.children.splice( index, 1 ); + for ( var i = 0; i < arguments.length; i ++ ) { - object.dispatchEvent( _removedEvent ); + this.remove( arguments[ i ] ); } return this; - }, + } - attach: function ( object ) { + var index = this.children.indexOf( object ); - // adds object as a child of this, while maintaining the object's world transform + if ( index !== - 1 ) { - this.updateWorldMatrix( true, false ); + object.parent = null; + this.children.splice( index, 1 ); - _m1$1.getInverse( this.matrixWorld ); + object.dispatchEvent( _removedEvent ); - if ( object.parent !== null ) { + } - object.parent.updateWorldMatrix( true, false ); + return this; - _m1$1.multiply( object.parent.matrixWorld ); + }, - } + attach: function ( object ) { - object.applyMatrix( _m1$1 ); + // adds object as a child of this, while maintaining the object's world transform - object.updateWorldMatrix( false, false ); + this.updateWorldMatrix( true, false ); - this.add( object ); + _m1$1.getInverse( this.matrixWorld ); - return this; + if ( object.parent !== null ) { - }, + object.parent.updateWorldMatrix( true, false ); - getObjectById: function ( id ) { + _m1$1.multiply( object.parent.matrixWorld ); - return this.getObjectByProperty( 'id', id ); + } - }, + object.applyMatrix4( _m1$1 ); - getObjectByName: function ( name ) { + object.updateWorldMatrix( false, false ); - return this.getObjectByProperty( 'name', name ); + this.add( object ); - }, + return this; - getObjectByProperty: function ( name, value ) { + }, - if ( this[ name ] === value ) { return this; } + getObjectById: function ( id ) { - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + return this.getObjectByProperty( 'id', id ); - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + }, - if ( object !== undefined ) { + getObjectByName: function ( name ) { - return object; + return this.getObjectByProperty( 'name', name ); - } + }, - } + getObjectByProperty: function ( name, value ) { - return undefined; + if ( this[ name ] === value ) return this; - }, + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - getWorldPosition: function ( target ) { + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - if ( target === undefined ) { + if ( object !== undefined ) { - console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); - target = new Vector3(); + return object; } - this.updateMatrixWorld( true ); - - return target.setFromMatrixPosition( this.matrixWorld ); + } - }, + return undefined; - getWorldQuaternion: function ( target ) { + }, - if ( target === undefined ) { + getWorldPosition: function ( target ) { - console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); - target = new Quaternion(); + if ( target === undefined ) { - } + console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); + target = new Vector3(); - this.updateMatrixWorld( true ); + } - this.matrixWorld.decompose( _position, target, _scale ); + this.updateMatrixWorld( true ); - return target; + return target.setFromMatrixPosition( this.matrixWorld ); - }, + }, - getWorldScale: function ( target ) { + getWorldQuaternion: function ( target ) { - if ( target === undefined ) { + if ( target === undefined ) { - console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); - target = new Vector3(); + console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); + target = new Quaternion(); - } + } - this.updateMatrixWorld( true ); + this.updateMatrixWorld( true ); - this.matrixWorld.decompose( _position, _quaternion$2, target ); + this.matrixWorld.decompose( _position, target, _scale ); - return target; + return target; - }, + }, - getWorldDirection: function ( target ) { + getWorldScale: function ( target ) { - if ( target === undefined ) { + if ( target === undefined ) { - console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); - target = new Vector3(); + console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); + target = new Vector3(); - } + } - this.updateMatrixWorld( true ); + this.updateMatrixWorld( true ); - var e = this.matrixWorld.elements; + this.matrixWorld.decompose( _position, _quaternion$2, target ); - return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); + return target; - }, + }, - raycast: function () {}, + getWorldDirection: function ( target ) { - traverse: function ( callback ) { + if ( target === undefined ) { - callback( this ); + console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); + target = new Vector3(); - var children = this.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + this.updateMatrixWorld( true ); - children[ i ].traverse( callback ); + var e = this.matrixWorld.elements; - } + return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); - }, + }, - traverseVisible: function ( callback ) { + raycast: function () {}, - if ( this.visible === false ) { return; } + traverse: function ( callback ) { - callback( this ); + callback( this ); - var children = this.children; + var children = this.children; - for ( var i = 0, l = children.length; i < l; i ++ ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - children[ i ].traverseVisible( callback ); + children[ i ].traverse( callback ); - } + } - }, + }, - traverseAncestors: function ( callback ) { + traverseVisible: function ( callback ) { - var parent = this.parent; + if ( this.visible === false ) return; - if ( parent !== null ) { + callback( this ); - callback( parent ); + var children = this.children; - parent.traverseAncestors( callback ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + children[ i ].traverseVisible( callback ); - }, + } - updateMatrix: function () { + }, - this.matrix.compose( this.position, this.quaternion, this.scale ); + traverseAncestors: function ( callback ) { - this.matrixWorldNeedsUpdate = true; + var parent = this.parent; - }, + if ( parent !== null ) { - updateMatrixWorld: function ( force ) { + callback( parent ); - if ( this.matrixAutoUpdate ) { this.updateMatrix(); } + parent.traverseAncestors( callback ); - if ( this.matrixWorldNeedsUpdate || force ) { + } - if ( this.parent === null ) { + }, - this.matrixWorld.copy( this.matrix ); + updateMatrix: function () { - } else { + this.matrix.compose( this.position, this.quaternion, this.scale ); - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + this.matrixWorldNeedsUpdate = true; - } + }, - this.matrixWorldNeedsUpdate = false; + updateMatrixWorld: function ( force ) { - force = true; + if ( this.matrixAutoUpdate ) this.updateMatrix(); - } + if ( this.matrixWorldNeedsUpdate || force ) { - // update children + if ( this.parent === null ) { - var children = this.children; + this.matrixWorld.copy( this.matrix ); - for ( var i = 0, l = children.length; i < l; i ++ ) { + } else { - children[ i ].updateMatrixWorld( force ); + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } - }, - - updateWorldMatrix: function ( updateParents, updateChildren ) { + this.matrixWorldNeedsUpdate = false; - var parent = this.parent; + force = true; - if ( updateParents === true && parent !== null ) { + } - parent.updateWorldMatrix( true, false ); + // update children - } + var children = this.children; - if ( this.matrixAutoUpdate ) { this.updateMatrix(); } + for ( var i = 0, l = children.length; i < l; i ++ ) { - if ( this.parent === null ) { + children[ i ].updateMatrixWorld( force ); - this.matrixWorld.copy( this.matrix ); + } - } else { + }, - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + updateWorldMatrix: function ( updateParents, updateChildren ) { - } + var parent = this.parent; - // update children + if ( updateParents === true && parent !== null ) { - if ( updateChildren === true ) { + parent.updateWorldMatrix( true, false ); - var children = this.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + if ( this.matrixAutoUpdate ) this.updateMatrix(); - children[ i ].updateWorldMatrix( false, true ); + if ( this.parent === null ) { - } + this.matrixWorld.copy( this.matrix ); - } + } else { - }, + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - toJSON: function ( meta ) { + } - // meta is a string when called from JSON.stringify - var isRootObject = ( meta === undefined || typeof meta === 'string' ); + // update children - var output = {}; + if ( updateChildren === true ) { - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + var children = this.children; - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {}, - shapes: {} - }; + for ( var i = 0, l = children.length; i < l; i ++ ) { - output.metadata = { - version: 4.5, - type: 'Object', - generator: 'Object3D.toJSON' - }; + children[ i ].updateWorldMatrix( false, true ); } - // standard Object3D serialization - - var object = {}; - - object.uuid = this.uuid; - object.type = this.type; - - if ( this.name !== '' ) { object.name = this.name; } - if ( this.castShadow === true ) { object.castShadow = true; } - if ( this.receiveShadow === true ) { object.receiveShadow = true; } - if ( this.visible === false ) { object.visible = false; } - if ( this.frustumCulled === false ) { object.frustumCulled = false; } - if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; } - if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; } + } - object.layers = this.layers.mask; - object.matrix = this.matrix.toArray(); + }, - if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; } + toJSON: function ( meta ) { - // object specific properties + // meta is a string when called from JSON.stringify + var isRootObject = ( meta === undefined || typeof meta === 'string' ); - if ( this.isMesh && this.drawMode !== TrianglesDrawMode ) { object.drawMode = this.drawMode; } + var output = {}; - if ( this.isInstancedMesh ) { + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - object.type = 'InstancedMesh'; - object.count = this.count; - object.instanceMatrix = this.instanceMatrix.toJSON(); + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {} + }; - } + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; - // + } - function serialize( library, element ) { + // standard Object3D serialization - if ( library[ element.uuid ] === undefined ) { + var object = {}; - library[ element.uuid ] = element.toJSON( meta ); + object.uuid = this.uuid; + object.type = this.type; - } + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - return element.uuid; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); - } + if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false; - if ( this.isMesh || this.isLine || this.isPoints ) { + // object specific properties - object.geometry = serialize( meta.geometries, this.geometry ); + if ( this.isInstancedMesh ) { - var parameters = this.geometry.parameters; + object.type = 'InstancedMesh'; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); - if ( parameters !== undefined && parameters.shapes !== undefined ) { + } - var shapes = parameters.shapes; + // - if ( Array.isArray( shapes ) ) { + function serialize( library, element ) { - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + if ( library[ element.uuid ] === undefined ) { - var shape = shapes[ i ]; + library[ element.uuid ] = element.toJSON( meta ); - serialize( meta.shapes, shape ); + } - } + return element.uuid; - } else { + } - serialize( meta.shapes, shapes ); + if ( this.isMesh || this.isLine || this.isPoints ) { - } + object.geometry = serialize( meta.geometries, this.geometry ); - } + var parameters = this.geometry.parameters; - } + if ( parameters !== undefined && parameters.shapes !== undefined ) { - if ( this.material !== undefined ) { + var shapes = parameters.shapes; - if ( Array.isArray( this.material ) ) { + if ( Array.isArray( shapes ) ) { - var uuids = []; + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - for ( var i = 0, l = this.material.length; i < l; i ++ ) { + var shape = shapes[ i ]; - uuids.push( serialize( meta.materials, this.material[ i ] ) ); + serialize( meta.shapes, shape ); } - object.material = uuids; - } else { - object.material = serialize( meta.materials, this.material ); + serialize( meta.shapes, shapes ); } } - // + } - if ( this.children.length > 0 ) { + if ( this.material !== undefined ) { - object.children = []; + if ( Array.isArray( this.material ) ) { - for ( var i = 0; i < this.children.length; i ++ ) { + var uuids = []; - object.children.push( this.children[ i ].toJSON( meta ).object ); + for ( var i = 0, l = this.material.length; i < l; i ++ ) { - } + uuids.push( serialize( meta.materials, this.material[ i ] ) ); - } + } - if ( isRootObject ) { + object.material = uuids; - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); - var shapes = extractFromCache( meta.shapes ); + } else { - if ( geometries.length > 0 ) { output.geometries = geometries; } - if ( materials.length > 0 ) { output.materials = materials; } - if ( textures.length > 0 ) { output.textures = textures; } - if ( images.length > 0 ) { output.images = images; } - if ( shapes.length > 0 ) { output.shapes = shapes; } + object.material = serialize( meta.materials, this.material ); } - output.object = object; + } - return output; + // - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + if ( this.children.length > 0 ) { - var values = []; - for ( var key in cache ) { + object.children = []; - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + for ( var i = 0; i < this.children.length; i ++ ) { - } - return values; + object.children.push( this.children[ i ].toJSON( meta ).object ); } - }, + } - clone: function ( recursive ) { + if ( isRootObject ) { - return new this.constructor().copy( this, recursive ); + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); + var shapes = extractFromCache( meta.shapes ); - }, + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; + if ( shapes.length > 0 ) output.shapes = shapes; - copy: function ( source, recursive ) { + } - if ( recursive === undefined ) { recursive = true; } + output.object = object; - this.name = source.name; + return output; - this.up.copy( source.up ); + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + var values = []; + for ( var key in cache ) { - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + } - this.layers.mask = source.layers.mask; - this.visible = source.visible; + return values; - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + } - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + }, - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + clone: function ( recursive ) { - if ( recursive === true ) { + return new this.constructor().copy( this, recursive ); - for ( var i = 0; i < source.children.length; i ++ ) { + }, - var child = source.children[ i ]; - this.add( child.clone() ); + copy: function ( source, recursive ) { - } + if ( recursive === undefined ) recursive = true; - } + this.name = source.name; - return this; + this.up.copy( source.up ); - } + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - } ); + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - function Scene() { + this.layers.mask = source.layers.mask; + this.visible = source.visible; - Object3D.call( this ); + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - this.type = 'Scene'; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - this.background = null; - this.fog = null; - this.overrideMaterial = null; + this.userData = JSON.parse( JSON.stringify( source.userData ) ); + + if ( recursive === true ) { - this.autoUpdate = true; // checked by the renderer + for ( var i = 0; i < source.children.length; i ++ ) { - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + var child = source.children[ i ]; + this.add( child.clone() ); - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + } } + return this; + } - Scene.prototype = Object.assign( Object.create( Object3D.prototype ), { +} ); - constructor: Scene, +/** + * @author mrdoob / http://mrdoob.com/ + */ - isScene: true, +function Scene() { - copy: function ( source, recursive ) { + Object3D.call( this ); - Object3D.prototype.copy.call( this, source, recursive ); + this.type = 'Scene'; - if ( source.background !== null ) { this.background = source.background.clone(); } - if ( source.fog !== null ) { this.fog = source.fog.clone(); } - if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); } + this.background = null; + this.environment = null; + this.fog = null; - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + this.overrideMaterial = null; - return this; + this.autoUpdate = true; // checked by the renderer - }, + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - toJSON: function ( meta ) { + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef - var data = Object3D.prototype.toJSON.call( this, meta ); + } - if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); } - if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); } +} - return data; +Scene.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: Scene, - dispose: function () { + isScene: true, - this.dispatchEvent( { type: 'dispose' } ); + copy: function ( source, recursive ) { - } + Object3D.prototype.copy.call( this, source, recursive ); - } ); + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.environment !== null ) this.environment = source.environment.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); - var _points = [ - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3() - ]; + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); - var _vector$2 = new Vector3(); + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - var _box = new Box3(); + return this; - // triangle centered vertices + }, - var _v0 = new Vector3(); - var _v1$2 = new Vector3(); - var _v2 = new Vector3(); + toJSON: function ( meta ) { - // triangle edge vectors + var data = Object3D.prototype.toJSON.call( this, meta ); - var _f0 = new Vector3(); - var _f1 = new Vector3(); - var _f2 = new Vector3(); + if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); + if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta ); + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); - var _center = new Vector3(); - var _extents = new Vector3(); - var _triangleNormal = new Vector3(); - var _testAxis = new Vector3(); + return data; - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + }, - function Box3( min, max ) { + dispose: function () { - this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); + this.dispatchEvent( { type: 'dispose' } ); } +} ); - Object.assign( Box3.prototype, { +var _points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() +]; - isBox3: true, +var _vector$1 = new Vector3(); - set: function ( min, max ) { +var _box = new Box3(); - this.min.copy( min ); - this.max.copy( max ); +// triangle centered vertices - return this; +var _v0 = new Vector3(); +var _v1$2 = new Vector3(); +var _v2 = new Vector3(); - }, +// triangle edge vectors - setFromArray: function ( array ) { +var _f0 = new Vector3(); +var _f1 = new Vector3(); +var _f2 = new Vector3(); - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; +var _center = new Vector3(); +var _extents = new Vector3(); +var _triangleNormal = new Vector3(); +var _testAxis = new Vector3(); - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; +/** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - for ( var i = 0, l = array.length; i < l; i += 3 ) { +function Box3( min, max ) { - var x = array[ i ]; - var y = array[ i + 1 ]; - var z = array[ i + 2 ]; + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - if ( x < minX ) { minX = x; } - if ( y < minY ) { minY = y; } - if ( z < minZ ) { minZ = z; } +} - if ( x > maxX ) { maxX = x; } - if ( y > maxY ) { maxY = y; } - if ( z > maxZ ) { maxZ = z; } - } +Object.assign( Box3.prototype, { - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + isBox3: true, - return this; + set: function ( min, max ) { - }, + this.min.copy( min ); + this.max.copy( max ); - setFromBufferAttribute: function ( attribute ) { + return this; - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + }, - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + setFromArray: function ( array ) { - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - var x = attribute.getX( i ); - var y = attribute.getY( i ); - var z = attribute.getZ( i ); + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - if ( x < minX ) { minX = x; } - if ( y < minY ) { minY = y; } - if ( z < minZ ) { minZ = z; } + for ( var i = 0, l = array.length; i < l; i += 3 ) { - if ( x > maxX ) { maxX = x; } - if ( y > maxY ) { maxY = y; } - if ( z > maxZ ) { maxZ = z; } + var x = array[ i ]; + var y = array[ i + 1 ]; + var z = array[ i + 2 ]; - } + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - return this; + } - }, + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - setFromPoints: function ( points ) { + return this; - this.makeEmpty(); + }, - for ( var i = 0, il = points.length; i < il; i ++ ) { + setFromBufferAttribute: function ( attribute ) { - this.expandByPoint( points[ i ] ); + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - } + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - return this; + for ( var i = 0, l = attribute.count; i < l; i ++ ) { - }, + var x = attribute.getX( i ); + var y = attribute.getY( i ); + var z = attribute.getZ( i ); - setFromCenterAndSize: function ( center, size ) { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - var halfSize = _vector$2.copy( size ).multiplyScalar( 0.5 ); + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + } - return this; + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - }, + return this; - setFromObject: function ( object ) { + }, - this.makeEmpty(); + setFromPoints: function ( points ) { - return this.expandByObject( object ); + this.makeEmpty(); - }, + for ( var i = 0, il = points.length; i < il; i ++ ) { - clone: function () { + this.expandByPoint( points[ i ] ); - return new this.constructor().copy( this ); + } - }, + return this; - copy: function ( box ) { + }, - this.min.copy( box.min ); - this.max.copy( box.max ); + setFromCenterAndSize: function ( center, size ) { - return this; + var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 ); - }, + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - makeEmpty: function () { + return this; - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + }, - return this; + setFromObject: function ( object ) { - }, + this.makeEmpty(); - isEmpty: function () { + return this.expandByObject( object ); - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + }, - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + clone: function () { - }, + return new this.constructor().copy( this ); - getCenter: function ( target ) { + }, - if ( target === undefined ) { + copy: function ( box ) { - console.warn( 'THREE.Box3: .getCenter() target is now required' ); - target = new Vector3(); + this.min.copy( box.min ); + this.max.copy( box.max ); - } + return this; - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + }, - }, + makeEmpty: function () { - getSize: function ( target ) { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - if ( target === undefined ) { + return this; - console.warn( 'THREE.Box3: .getSize() target is now required' ); - target = new Vector3(); + }, - } + isEmpty: function () { - return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - }, + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - expandByPoint: function ( point ) { + }, - this.min.min( point ); - this.max.max( point ); + getCenter: function ( target ) { - return this; + if ( target === undefined ) { - }, + console.warn( 'THREE.Box3: .getCenter() target is now required' ); + target = new Vector3(); - expandByVector: function ( vector ) { + } - this.min.sub( vector ); - this.max.add( vector ); + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - return this; + }, - }, + getSize: function ( target ) { - expandByScalar: function ( scalar ) { + if ( target === undefined ) { - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + console.warn( 'THREE.Box3: .getSize() target is now required' ); + target = new Vector3(); - return this; + } - }, + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); - expandByObject: function ( object ) { + }, - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + expandByPoint: function ( point ) { - object.updateWorldMatrix( false, false ); + this.min.min( point ); + this.max.max( point ); - var geometry = object.geometry; + return this; - if ( geometry !== undefined ) { + }, - if ( geometry.boundingBox === null ) { + expandByVector: function ( vector ) { - geometry.computeBoundingBox(); + this.min.sub( vector ); + this.max.add( vector ); - } + return this; - _box.copy( geometry.boundingBox ); - _box.applyMatrix4( object.matrixWorld ); + }, - this.expandByPoint( _box.min ); - this.expandByPoint( _box.max ); + expandByScalar: function ( scalar ) { - } + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - var children = object.children; + return this; - for ( var i = 0, l = children.length; i < l; i ++ ) { + }, - this.expandByObject( children[ i ] ); + expandByObject: function ( object ) { - } + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - return this; + object.updateWorldMatrix( false, false ); - }, + var geometry = object.geometry; - containsPoint: function ( point ) { + if ( geometry !== undefined ) { - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ? false : true; + if ( geometry.boundingBox === null ) { - }, + geometry.computeBoundingBox(); - containsBox: function ( box ) { + } - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; + _box.copy( geometry.boundingBox ); + _box.applyMatrix4( object.matrixWorld ); - }, + this.union( _box ); - getParameter: function ( point, target ) { + } - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + var children = object.children; - if ( target === undefined ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - console.warn( 'THREE.Box3: .getParameter() target is now required' ); - target = new Vector3(); + this.expandByObject( children[ i ] ); - } + } - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); + return this; - }, + }, - intersectsBox: function ( box ) { + containsPoint: function ( point ) { - // using 6 splitting planes to rule out intersections. - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ? false : true; + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ? false : true; - }, + }, - intersectsSphere: function ( sphere ) { + containsBox: function ( box ) { - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, _vector$2 ); + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y && + this.min.z <= box.min.z && box.max.z <= this.max.z; - // If that point is inside the sphere, the AABB and sphere intersect. - return _vector$2.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + }, - }, + getParameter: function ( point, target ) { - intersectsPlane: function ( plane ) { + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. + if ( target === undefined ) { - var min, max; + console.warn( 'THREE.Box3: .getParameter() target is now required' ); + target = new Vector3(); - if ( plane.normal.x > 0 ) { + } - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); - } else { + }, - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + intersectsBox: function ( box ) { - } + // using 6 splitting planes to rule out intersections. + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ? false : true; - if ( plane.normal.y > 0 ) { + }, - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + intersectsSphere: function ( sphere ) { - } else { + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, _vector$1 ); - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + // If that point is inside the sphere, the AABB and sphere intersect. + return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - } + }, - if ( plane.normal.z > 0 ) { + intersectsPlane: function ( plane ) { - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. - } else { + var min, max; - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + if ( plane.normal.x > 0 ) { - } + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; - return ( min <= - plane.constant && max >= - plane.constant ); + } else { - }, + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - intersectsTriangle: function ( triangle ) { + } - if ( this.isEmpty() ) { + if ( plane.normal.y > 0 ) { - return false; + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - } + } else { - // compute box center and extents - this.getCenter( _center ); - _extents.subVectors( this.max, _center ); + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; - // translate triangle to aabb origin - _v0.subVectors( triangle.a, _center ); - _v1$2.subVectors( triangle.b, _center ); - _v2.subVectors( triangle.c, _center ); + } - // compute edge vectors for triangle - _f0.subVectors( _v1$2, _v0 ); - _f1.subVectors( _v2, _v1$2 ); - _f2.subVectors( _v0, _v2 ); + if ( plane.normal.z > 0 ) { - // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb - // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation - // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) - var axes = [ - 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, - _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 - ]; - if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - return false; + } else { - } + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - // test 3 face normals from the aabb - axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { + } - return false; + return ( min <= - plane.constant && max >= - plane.constant ); - } + }, - // finally testing the face normal of the triangle - // use already existing triangle edge vectors here - _triangleNormal.crossVectors( _f0, _f1 ); - axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; + intersectsTriangle: function ( triangle ) { - return satForAxes( axes, _v0, _v1$2, _v2, _extents ); + if ( this.isEmpty() ) { - }, + return false; - clampPoint: function ( point, target ) { + } - if ( target === undefined ) { + // compute box center and extents + this.getCenter( _center ); + _extents.subVectors( this.max, _center ); - console.warn( 'THREE.Box3: .clampPoint() target is now required' ); - target = new Vector3(); + // translate triangle to aabb origin + _v0.subVectors( triangle.a, _center ); + _v1$2.subVectors( triangle.b, _center ); + _v2.subVectors( triangle.c, _center ); - } + // compute edge vectors for triangle + _f0.subVectors( _v1$2, _v0 ); + _f1.subVectors( _v2, _v1$2 ); + _f2.subVectors( _v0, _v2 ); - return target.copy( point ).clamp( this.min, this.max ); + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + var axes = [ + 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, + _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, + - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 + ]; + if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { - }, + return false; - distanceToPoint: function ( point ) { + } - var clampedPoint = _vector$2.copy( point ).clamp( this.min, this.max ); + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { - return clampedPoint.sub( point ).length(); + return false; - }, + } - getBoundingSphere: function ( target ) { + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + _triangleNormal.crossVectors( _f0, _f1 ); + axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; - if ( target === undefined ) { + return satForAxes( axes, _v0, _v1$2, _v2, _extents ); - console.error( 'THREE.Box3: .getBoundingSphere() target is now required' ); - //target = new Sphere(); // removed to avoid cyclic dependency + }, - } + clampPoint: function ( point, target ) { - this.getCenter( target.center ); + if ( target === undefined ) { - target.radius = this.getSize( _vector$2 ).length() * 0.5; + console.warn( 'THREE.Box3: .clampPoint() target is now required' ); + target = new Vector3(); - return target; + } - }, + return target.copy( point ).clamp( this.min, this.max ); - intersect: function ( box ) { + }, - this.min.max( box.min ); - this.max.min( box.max ); + distanceToPoint: function ( point ) { - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if ( this.isEmpty() ) { this.makeEmpty(); } + var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max ); - return this; + return clampedPoint.sub( point ).length(); - }, + }, - union: function ( box ) { + getBoundingSphere: function ( target ) { - this.min.min( box.min ); - this.max.max( box.max ); + if ( target === undefined ) { - return this; + console.error( 'THREE.Box3: .getBoundingSphere() target is now required' ); + //target = new Sphere(); // removed to avoid cyclic dependency - }, + } - applyMatrix4: function ( matrix ) { + this.getCenter( target.center ); - // transform of empty box is an empty box. - if ( this.isEmpty() ) { return this; } + target.radius = this.getSize( _vector$1 ).length() * 0.5; - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + return target; - this.setFromPoints( _points ); + }, - return this; + intersect: function ( box ) { - }, + this.min.max( box.min ); + this.max.min( box.max ); - translate: function ( offset ) { + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if ( this.isEmpty() ) this.makeEmpty(); - this.min.add( offset ); - this.max.add( offset ); + return this; - return this; + }, - }, + union: function ( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); - equals: function ( box ) { + return this; - return box.min.equals( this.min ) && box.max.equals( this.max ); + }, - } + applyMatrix4: function ( matrix ) { - } ); + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; - function satForAxes( axes, v0, v1, v2, extents ) { + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - var i, j; + this.setFromPoints( _points ); - for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) { + return this; - _testAxis.fromArray( axes, i ); - // project the aabb onto the seperating axis - var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); - // project all 3 vertices of the triangle onto the seperating axis - var p0 = v0.dot( _testAxis ); - var p1 = v1.dot( _testAxis ); - var p2 = v2.dot( _testAxis ); - // actual test, basically see if either of the most extreme of the triangle points intersects r - if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { + }, - // points of the projected triangle are outside the projected half-length of the aabb - // the axis is seperating and we can exit - return false; + translate: function ( offset ) { - } + this.min.add( offset ); + this.max.add( offset ); - } + return this; - return true; + }, + + equals: function ( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); } - var _box$1 = new Box3(); +} ); - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ +function satForAxes( axes, v0, v1, v2, extents ) { - function Sphere( center, radius ) { + var i, j; - this.center = ( center !== undefined ) ? center : new Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) { - } + _testAxis.fromArray( axes, i ); + // project the aabb onto the seperating axis + var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); + // project all 3 vertices of the triangle onto the seperating axis + var p0 = v0.dot( _testAxis ); + var p1 = v1.dot( _testAxis ); + var p2 = v2.dot( _testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - Object.assign( Sphere.prototype, { + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is seperating and we can exit + return false; - set: function ( center, radius ) { + } - this.center.copy( center ); - this.radius = radius; + } - return this; + return true; - }, +} - setFromPoints: function ( points, optionalCenter ) { +var _box$1 = new Box3(); - var center = this.center; +/** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - if ( optionalCenter !== undefined ) { +function Sphere( center, radius ) { - center.copy( optionalCenter ); + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : - 1; - } else { +} - _box$1.setFromPoints( points ).getCenter( center ); +Object.assign( Sphere.prototype, { - } + set: function ( center, radius ) { - var maxRadiusSq = 0; + this.center.copy( center ); + this.radius = radius; - for ( var i = 0, il = points.length; i < il; i ++ ) { + return this; - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + }, - } + setFromPoints: function ( points, optionalCenter ) { - this.radius = Math.sqrt( maxRadiusSq ); + var center = this.center; - return this; + if ( optionalCenter !== undefined ) { - }, + center.copy( optionalCenter ); - clone: function () { + } else { - return new this.constructor().copy( this ); + _box$1.setFromPoints( points ).getCenter( center ); - }, + } - copy: function ( sphere ) { + var maxRadiusSq = 0; - this.center.copy( sphere.center ); - this.radius = sphere.radius; + for ( var i = 0, il = points.length; i < il; i ++ ) { - return this; + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - }, + } - empty: function () { + this.radius = Math.sqrt( maxRadiusSq ); - return ( this.radius <= 0 ); + return this; - }, + }, - containsPoint: function ( point ) { + clone: function () { - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + return new this.constructor().copy( this ); - }, + }, - distanceToPoint: function ( point ) { + copy: function ( sphere ) { - return ( point.distanceTo( this.center ) - this.radius ); + this.center.copy( sphere.center ); + this.radius = sphere.radius; - }, + return this; - intersectsSphere: function ( sphere ) { + }, - var radiusSum = this.radius + sphere.radius; + isEmpty: function () { - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + return ( this.radius < 0 ); - }, + }, - intersectsBox: function ( box ) { + makeEmpty: function () { - return box.intersectsSphere( this ); + this.center.set( 0, 0, 0 ); + this.radius = - 1; - }, + return this; - intersectsPlane: function ( plane ) { + }, - return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; + containsPoint: function ( point ) { - }, + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - clampPoint: function ( point, target ) { + }, - var deltaLengthSq = this.center.distanceToSquared( point ); + distanceToPoint: function ( point ) { - if ( target === undefined ) { + return ( point.distanceTo( this.center ) - this.radius ); - console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); - target = new Vector3(); + }, - } + intersectsSphere: function ( sphere ) { - target.copy( point ); + var radiusSum = this.radius + sphere.radius; - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - target.sub( this.center ).normalize(); - target.multiplyScalar( this.radius ).add( this.center ); + }, - } + intersectsBox: function ( box ) { - return target; + return box.intersectsSphere( this ); - }, + }, - getBoundingBox: function ( target ) { + intersectsPlane: function ( plane ) { - if ( target === undefined ) { + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; - console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); - target = new Box3(); + }, - } + clampPoint: function ( point, target ) { - target.set( this.center, this.center ); - target.expandByScalar( this.radius ); + var deltaLengthSq = this.center.distanceToSquared( point ); - return target; + if ( target === undefined ) { - }, + console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); + target = new Vector3(); - applyMatrix4: function ( matrix ) { + } - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + target.copy( point ); - return this; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - }, + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); - translate: function ( offset ) { + } - this.center.add( offset ); + return target; - return this; + }, - }, + getBoundingBox: function ( target ) { - equals: function ( sphere ) { + if ( target === undefined ) { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); + target = new Box3(); } - } ); + if ( this.isEmpty() ) { - var _vector$3 = new Vector3(); - var _segCenter = new Vector3(); - var _segDir = new Vector3(); - var _diff = new Vector3(); + // Empty sphere produces empty bounding box + target.makeEmpty(); + return target; - var _edge1 = new Vector3(); - var _edge2 = new Vector3(); - var _normal = new Vector3(); + } - /** - * @author bhouston / http://clara.io - */ + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); - function Ray( origin, direction ) { + return target; - this.origin = ( origin !== undefined ) ? origin : new Vector3(); - this.direction = ( direction !== undefined ) ? direction : new Vector3(); + }, - } + applyMatrix4: function ( matrix ) { - Object.assign( Ray.prototype, { + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); - set: function ( origin, direction ) { + return this; - this.origin.copy( origin ); - this.direction.copy( direction ); + }, - return this; + translate: function ( offset ) { - }, + this.center.add( offset ); - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - }, + equals: function ( sphere ) { - copy: function ( ray ) { + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + } - return this; +} ); - }, +var _vector$2 = new Vector3(); +var _segCenter = new Vector3(); +var _segDir = new Vector3(); +var _diff = new Vector3(); - at: function ( t, target ) { +var _edge1 = new Vector3(); +var _edge2 = new Vector3(); +var _normal = new Vector3(); - if ( target === undefined ) { +/** + * @author bhouston / http://clara.io + */ - console.warn( 'THREE.Ray: .at() target is now required' ); - target = new Vector3(); +function Ray( origin, direction ) { - } + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 ); - return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); +} - }, +Object.assign( Ray.prototype, { - lookAt: function ( v ) { + set: function ( origin, direction ) { - this.direction.copy( v ).sub( this.origin ).normalize(); + this.origin.copy( origin ); + this.direction.copy( direction ); - return this; + return this; - }, + }, - recast: function ( t ) { + clone: function () { - this.origin.copy( this.at( t, _vector$3 ) ); + return new this.constructor().copy( this ); - return this; + }, - }, + copy: function ( ray ) { - closestPointToPoint: function ( point, target ) { + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); - target = new Vector3(); + }, - } + at: function ( t, target ) { - target.subVectors( point, this.origin ); + if ( target === undefined ) { - var directionDistance = target.dot( this.direction ); + console.warn( 'THREE.Ray: .at() target is now required' ); + target = new Vector3(); - if ( directionDistance < 0 ) { + } - return target.copy( this.origin ); + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - } + }, - return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + lookAt: function ( v ) { - }, + this.direction.copy( v ).sub( this.origin ).normalize(); - distanceToPoint: function ( point ) { + return this; - return Math.sqrt( this.distanceSqToPoint( point ) ); + }, - }, + recast: function ( t ) { - distanceSqToPoint: function ( point ) { + this.origin.copy( this.at( t, _vector$2 ) ); - var directionDistance = _vector$3.subVectors( point, this.origin ).dot( this.direction ); + return this; - // point behind the ray + }, - if ( directionDistance < 0 ) { + closestPointToPoint: function ( point, target ) { - return this.origin.distanceToSquared( point ); + if ( target === undefined ) { - } + console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); + target = new Vector3(); - _vector$3.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + } - return _vector$3.distanceToSquared( point ); + target.subVectors( point, this.origin ); - }, + var directionDistance = target.dot( this.direction ); - distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + if ( directionDistance < 0 ) { - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + return target.copy( this.origin ); - _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - _segDir.copy( v1 ).sub( v0 ).normalize(); - _diff.copy( this.origin ).sub( _segCenter ); + } - var segExtent = v0.distanceTo( v1 ) * 0.5; - var a01 = - this.direction.dot( _segDir ); - var b0 = _diff.dot( this.direction ); - var b1 = - _diff.dot( _segDir ); - var c = _diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - if ( det > 0 ) { + }, - // The ray and segment are not parallel. + distanceToPoint: function ( point ) { - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + return Math.sqrt( this.distanceSqToPoint( point ) ); - if ( s0 >= 0 ) { + }, - if ( s1 >= - extDet ) { + distanceSqToPoint: function ( point ) { - if ( s1 <= extDet ) { + var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction ); - // region 0 - // Minimum at interior points of ray and segment. + // point behind the ray - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + if ( directionDistance < 0 ) { - } else { + return this.origin.distanceToSquared( point ); - // region 1 + } - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - } + return _vector$2.distanceToSquared( point ); - } else { + }, - // region 5 + distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment - } + _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + _segDir.copy( v1 ).sub( v0 ).normalize(); + _diff.copy( this.origin ).sub( _segCenter ); - } else { + var segExtent = v0.distanceTo( v1 ) * 0.5; + var a01 = - this.direction.dot( _segDir ); + var b0 = _diff.dot( this.direction ); + var b1 = - _diff.dot( _segDir ); + var c = _diff.lengthSq(); + var det = Math.abs( 1 - a01 * a01 ); + var s0, s1, sqrDist, extDet; - if ( s1 <= - extDet ) { + if ( det > 0 ) { - // region 4 + // The ray and segment are not parallel. - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + + if ( s0 >= 0 ) { - } else if ( s1 <= extDet ) { + if ( s1 >= - extDet ) { - // region 3 + if ( s1 <= extDet ) { - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + // region 0 + // Minimum at interior points of ray and segment. + + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; } else { - // region 2 + // region 1 - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } + } else { + + // region 5 + + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } } else { - // Ray and segment are parallel. + if ( s1 <= - extDet ) { - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + // region 4 - } + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - if ( optionalPointOnRay ) { + } else if ( s1 <= extDet ) { - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + // region 3 - } + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - if ( optionalPointOnSegment ) { + } else { - optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); + // region 2 - } + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return sqrDist; + } - }, + } - intersectSphere: function ( sphere, target ) { + } else { - _vector$3.subVectors( sphere.center, this.origin ); - var tca = _vector$3.dot( this.direction ); - var d2 = _vector$3.dot( _vector$3 ) - tca * tca; - var radius2 = sphere.radius * sphere.radius; + // Ray and segment are parallel. - if ( d2 > radius2 ) { return null; } + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - var thc = Math.sqrt( radius2 - d2 ); + } - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + if ( optionalPointOnRay ) { - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) { return null; } + } - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) { return this.at( t1, target ); } + if ( optionalPointOnSegment ) { - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, target ); + optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); - }, + } - intersectsSphere: function ( sphere ) { + return sqrDist; - return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); + }, - }, + intersectSphere: function ( sphere, target ) { - distanceToPlane: function ( plane ) { + _vector$2.subVectors( sphere.center, this.origin ); + var tca = _vector$2.dot( this.direction ); + var d2 = _vector$2.dot( _vector$2 ) - tca * tca; + var radius2 = sphere.radius * sphere.radius; - var denominator = plane.normal.dot( this.direction ); + if ( d2 > radius2 ) return null; - if ( denominator === 0 ) { + var thc = Math.sqrt( radius2 - d2 ); - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - return 0; + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - } + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - // Null is preferable to undefined since undefined means.... it is undefined + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, target ); - return null; + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); - } + }, - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + intersectsSphere: function ( sphere ) { - // Return if the ray never intersects the plane + return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); - return t >= 0 ? t : null; + }, - }, + distanceToPlane: function ( plane ) { - intersectPlane: function ( plane, target ) { + var denominator = plane.normal.dot( this.direction ); - var t = this.distanceToPlane( plane ); + if ( denominator === 0 ) { - if ( t === null ) { + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - return null; + return 0; } - return this.at( t, target ); - - }, + // Null is preferable to undefined since undefined means.... it is undefined - intersectsPlane: function ( plane ) { + return null; - // check if the ray lies on the plane first + } - var distToPoint = plane.distanceToPoint( this.origin ); + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - if ( distToPoint === 0 ) { + // Return if the ray never intersects the plane - return true; + return t >= 0 ? t : null; - } + }, - var denominator = plane.normal.dot( this.direction ); + intersectPlane: function ( plane, target ) { - if ( denominator * distToPoint < 0 ) { + var t = this.distanceToPlane( plane ); - return true; + if ( t === null ) { - } + return null; - // ray origin is behind the plane (and is pointing behind it) + } - return false; + return this.at( t, target ); - }, + }, - intersectBox: function ( box, target ) { + intersectsPlane: function ( plane ) { - var tmin, tmax, tymin, tymax, tzmin, tzmax; + // check if the ray lies on the plane first - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + var distToPoint = plane.distanceToPoint( this.origin ); - var origin = this.origin; + if ( distToPoint === 0 ) { - if ( invdirx >= 0 ) { + return true; - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; + } - } else { + var denominator = plane.normal.dot( this.direction ); - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; + if ( denominator * distToPoint < 0 ) { - } + return true; - if ( invdiry >= 0 ) { + } - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; + // ray origin is behind the plane (and is pointing behind it) - } else { + return false; - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; + }, - } + intersectBox: function ( box, target ) { - if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; } + var tmin, tmax, tymin, tymax, tzmin, tzmax; - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; } + var origin = this.origin; - if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; } + if ( invdirx >= 0 ) { - if ( invdirz >= 0 ) { + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + } else { - } else { + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + } - } + if ( invdiry >= 0 ) { - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; } + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; } + } else { - if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; } + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - //return point closest to the ray (positive side) + } - if ( tmax < 0 ) { return null; } + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - return this.at( tmin >= 0 ? tmin : tmax, target ); + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - }, + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - intersectsBox: function ( box ) { + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - return this.intersectBox( box, _vector$3 ) !== null; + if ( invdirz >= 0 ) { - }, + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - intersectTriangle: function ( a, b, c, backfaceCulling, target ) { + } else { - // Compute the offset origin, edges, and normal. + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + } - _edge1.subVectors( b, a ); - _edge2.subVectors( c, a ); - _normal.crossVectors( _edge1, _edge2 ); + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( _normal ); - var sign; + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - if ( DdN > 0 ) { + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - if ( backfaceCulling ) { return null; } - sign = 1; + //return point closest to the ray (positive side) - } else if ( DdN < 0 ) { + if ( tmax < 0 ) return null; - sign = - 1; - DdN = - DdN; + return this.at( tmin >= 0 ? tmin : tmax, target ); - } else { + }, - return null; + intersectsBox: function ( box ) { - } + return this.intersectBox( box, _vector$2 ) !== null; - _diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); + }, - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + intersectTriangle: function ( a, b, c, backfaceCulling, target ) { - return null; + // Compute the offset origin, edges, and normal. - } + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); + _edge1.subVectors( b, a ); + _edge2.subVectors( c, a ); + _normal.crossVectors( _edge1, _edge2 ); - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + var DdN = this.direction.dot( _normal ); + var sign; - return null; + if ( DdN > 0 ) { - } + if ( backfaceCulling ) return null; + sign = 1; - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + } else if ( DdN < 0 ) { - return null; + sign = - 1; + DdN = - DdN; - } + } else { - // Line intersects triangle, check if ray does. - var QdN = - sign * _diff.dot( _normal ); + return null; - // t < 0, no intersection - if ( QdN < 0 ) { + } - return null; + _diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); - } + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - // Ray intersects triangle. - return this.at( QdN / DdN, target ); + return null; - }, + } - applyMatrix4: function ( matrix4 ) { + var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - return this; + return null; - }, + } - equals: function ( ray ) { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + return null; } - } ); + // Line intersects triangle, check if ray does. + var QdN = - sign * _diff.dot( _normal ); - /** - * @author bhouston / http://clara.io - */ + // t < 0, no intersection + if ( QdN < 0 ) { - var _vector1 = new Vector3(); - var _vector2 = new Vector3(); - var _normalMatrix = new Matrix3(); + return null; - function Plane( normal, constant ) { + } - // normal is assumed to be normalized + // Ray intersects triangle. + return this.at( QdN / DdN, target ); - this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + }, - } + applyMatrix4: function ( matrix4 ) { - Object.assign( Plane.prototype, { + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); - isPlane: true, + return this; - set: function ( normal, constant ) { + }, - this.normal.copy( normal ); - this.constant = constant; + equals: function ( ray ) { - return this; + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - }, + } - setComponents: function ( x, y, z, w ) { +} ); - this.normal.set( x, y, z ); - this.constant = w; +/** + * @author bhouston / http://clara.io + */ - return this; +var _vector1 = new Vector3(); +var _vector2 = new Vector3(); +var _normalMatrix = new Matrix3(); - }, +function Plane( normal, constant ) { - setFromNormalAndCoplanarPoint: function ( normal, point ) { + // normal is assumed to be normalized - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - return this; +} - }, +Object.assign( Plane.prototype, { - setFromCoplanarPoints: function ( a, b, c ) { + isPlane: true, - var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); + set: function ( normal, constant ) { - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + this.normal.copy( normal ); + this.constant = constant; - this.setFromNormalAndCoplanarPoint( normal, a ); + return this; - return this; + }, - }, + setComponents: function ( x, y, z, w ) { - clone: function () { + this.normal.set( x, y, z ); + this.constant = w; - return new this.constructor().copy( this ); + return this; - }, + }, - copy: function ( plane ) { + setFromNormalAndCoplanarPoint: function ( normal, point ) { - this.normal.copy( plane.normal ); - this.constant = plane.constant; + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); - return this; + return this; - }, + }, - normalize: function () { + setFromCoplanarPoints: function ( a, b, c ) { - // Note: will lead to a divide by zero if the plane is invalid. + var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - return this; + this.setFromNormalAndCoplanarPoint( normal, a ); - }, + return this; - negate: function () { + }, - this.constant *= - 1; - this.normal.negate(); + clone: function () { - return this; + return new this.constructor().copy( this ); - }, + }, - distanceToPoint: function ( point ) { + copy: function ( plane ) { - return this.normal.dot( point ) + this.constant; + this.normal.copy( plane.normal ); + this.constant = plane.constant; - }, + return this; - distanceToSphere: function ( sphere ) { + }, - return this.distanceToPoint( sphere.center ) - sphere.radius; + normalize: function () { - }, + // Note: will lead to a divide by zero if the plane is invalid. - projectPoint: function ( point, target ) { + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - if ( target === undefined ) { + return this; - console.warn( 'THREE.Plane: .projectPoint() target is now required' ); - target = new Vector3(); + }, - } + negate: function () { - return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); + this.constant *= - 1; + this.normal.negate(); - }, + return this; - intersectLine: function ( line, target ) { + }, - if ( target === undefined ) { + distanceToPoint: function ( point ) { - console.warn( 'THREE.Plane: .intersectLine() target is now required' ); - target = new Vector3(); + return this.normal.dot( point ) + this.constant; - } + }, - var direction = line.delta( _vector1 ); + distanceToSphere: function ( sphere ) { - var denominator = this.normal.dot( direction ); + return this.distanceToPoint( sphere.center ) - sphere.radius; - if ( denominator === 0 ) { + }, - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + projectPoint: function ( point, target ) { - return target.copy( line.start ); + if ( target === undefined ) { - } + console.warn( 'THREE.Plane: .projectPoint() target is now required' ); + target = new Vector3(); - // Unsure if this is the correct method to handle this case. - return undefined; + } - } + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + }, - if ( t < 0 || t > 1 ) { + intersectLine: function ( line, target ) { - return undefined; + if ( target === undefined ) { - } + console.warn( 'THREE.Plane: .intersectLine() target is now required' ); + target = new Vector3(); - return target.copy( direction ).multiplyScalar( t ).add( line.start ); + } - }, + var direction = line.delta( _vector1 ); - intersectsLine: function ( line ) { + var denominator = this.normal.dot( direction ); - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + if ( denominator === 0 ) { - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + return target.copy( line.start ); - }, + } - intersectsBox: function ( box ) { + // Unsure if this is the correct method to handle this case. + return undefined; - return box.intersectsPlane( this ); + } - }, + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - intersectsSphere: function ( sphere ) { + if ( t < 0 || t > 1 ) { - return sphere.intersectsPlane( this ); + return undefined; - }, - - coplanarPoint: function ( target ) { - - if ( target === undefined ) { - - console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); - target = new Vector3(); + } - } + return target.copy( direction ).multiplyScalar( t ).add( line.start ); - return target.copy( this.normal ).multiplyScalar( - this.constant ); + }, - }, + intersectsLine: function ( line ) { - applyMatrix4: function ( matrix, optionalNormalMatrix ) { + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + }, - this.constant = - referencePoint.dot( normal ); + intersectsBox: function ( box ) { - return this; + return box.intersectsPlane( this ); - }, + }, - translate: function ( offset ) { + intersectsSphere: function ( sphere ) { - this.constant -= offset.dot( this.normal ); + return sphere.intersectsPlane( this ); - return this; + }, - }, + coplanarPoint: function ( target ) { - equals: function ( plane ) { + if ( target === undefined ) { - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); + target = new Vector3(); } - } ); + return target.copy( this.normal ).multiplyScalar( - this.constant ); - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + }, - var _v0$1 = new Vector3(); - var _v1$3 = new Vector3(); - var _v2$1 = new Vector3(); - var _v3 = new Vector3(); + applyMatrix4: function ( matrix, optionalNormalMatrix ) { - var _vab = new Vector3(); - var _vac = new Vector3(); - var _vbc = new Vector3(); - var _vap = new Vector3(); - var _vbp = new Vector3(); - var _vcp = new Vector3(); + var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); - function Triangle( a, b, c ) { + var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); - this.a = ( a !== undefined ) ? a : new Vector3(); - this.b = ( b !== undefined ) ? b : new Vector3(); - this.c = ( c !== undefined ) ? c : new Vector3(); + var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - } + this.constant = - referencePoint.dot( normal ); - Object.assign( Triangle, { + return this; - getNormal: function ( a, b, c, target ) { + }, - if ( target === undefined ) { + translate: function ( offset ) { - console.warn( 'THREE.Triangle: .getNormal() target is now required' ); - target = new Vector3(); + this.constant -= offset.dot( this.normal ); - } + return this; - target.subVectors( c, b ); - _v0$1.subVectors( a, b ); - target.cross( _v0$1 ); + }, - var targetLengthSq = target.lengthSq(); - if ( targetLengthSq > 0 ) { + equals: function ( plane ) { - return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); - } + } - return target.set( 0, 0, 0 ); +} ); - }, +/** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - getBarycoord: function ( point, a, b, c, target ) { +var _v0$1 = new Vector3(); +var _v1$3 = new Vector3(); +var _v2$1 = new Vector3(); +var _v3 = new Vector3(); - _v0$1.subVectors( c, a ); - _v1$3.subVectors( b, a ); - _v2$1.subVectors( point, a ); +var _vab = new Vector3(); +var _vac = new Vector3(); +var _vbc = new Vector3(); +var _vap = new Vector3(); +var _vbp = new Vector3(); +var _vcp = new Vector3(); - var dot00 = _v0$1.dot( _v0$1 ); - var dot01 = _v0$1.dot( _v1$3 ); - var dot02 = _v0$1.dot( _v2$1 ); - var dot11 = _v1$3.dot( _v1$3 ); - var dot12 = _v1$3.dot( _v2$1 ); +function Triangle( a, b, c ) { - var denom = ( dot00 * dot11 - dot01 * dot01 ); + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - if ( target === undefined ) { +} - console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); - target = new Vector3(); +Object.assign( Triangle, { - } + getNormal: function ( a, b, c, target ) { - // collinear or singular triangle - if ( denom === 0 ) { + if ( target === undefined ) { - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return target.set( - 2, - 1, - 1 ); + console.warn( 'THREE.Triangle: .getNormal() target is now required' ); + target = new Vector3(); - } + } - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + target.subVectors( c, b ); + _v0$1.subVectors( a, b ); + target.cross( _v0$1 ); - // barycentric coordinates must always sum to 1 - return target.set( 1 - u - v, v, u ); + var targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { - }, + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - containsPoint: function ( point, a, b, c ) { + } - Triangle.getBarycoord( point, a, b, c, _v3 ); + return target.set( 0, 0, 0 ); - return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); + }, - }, + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + getBarycoord: function ( point, a, b, c, target ) { - getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) { + _v0$1.subVectors( c, a ); + _v1$3.subVectors( b, a ); + _v2$1.subVectors( point, a ); - this.getBarycoord( point, p1, p2, p3, _v3 ); + var dot00 = _v0$1.dot( _v0$1 ); + var dot01 = _v0$1.dot( _v1$3 ); + var dot02 = _v0$1.dot( _v2$1 ); + var dot11 = _v1$3.dot( _v1$3 ); + var dot12 = _v1$3.dot( _v2$1 ); - target.set( 0, 0 ); - target.addScaledVector( uv1, _v3.x ); - target.addScaledVector( uv2, _v3.y ); - target.addScaledVector( uv3, _v3.z ); + var denom = ( dot00 * dot11 - dot01 * dot01 ); - return target; + if ( target === undefined ) { - }, + console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); + target = new Vector3(); - isFrontFacing: function ( a, b, c, direction ) { + } - _v0$1.subVectors( c, b ); - _v1$3.subVectors( a, b ); + // collinear or singular triangle + if ( denom === 0 ) { - // strictly front facing - return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return target.set( - 2, - 1, - 1 ); } - } ); + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - Object.assign( Triangle.prototype, { + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); - set: function ( a, b, c ) { + }, - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + containsPoint: function ( point, a, b, c ) { - return this; + Triangle.getBarycoord( point, a, b, c, _v3 ); - }, + return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + }, - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) { - return this; + this.getBarycoord( point, p1, p2, p3, _v3 ); - }, + target.set( 0, 0 ); + target.addScaledVector( uv1, _v3.x ); + target.addScaledVector( uv2, _v3.y ); + target.addScaledVector( uv3, _v3.z ); - clone: function () { + return target; - return new this.constructor().copy( this ); + }, - }, + isFrontFacing: function ( a, b, c, direction ) { - copy: function ( triangle ) { + _v0$1.subVectors( c, b ); + _v1$3.subVectors( a, b ); - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + // strictly front facing + return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; - return this; + } - }, +} ); - getArea: function () { +Object.assign( Triangle.prototype, { - _v0$1.subVectors( this.c, this.b ); - _v1$3.subVectors( this.a, this.b ); + set: function ( a, b, c ) { - return _v0$1.cross( _v1$3 ).length() * 0.5; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - }, + return this; - getMidpoint: function ( target ) { + }, - if ( target === undefined ) { + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); - target = new Vector3(); + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); - } + return this; - return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + }, - }, + clone: function () { - getNormal: function ( target ) { + return new this.constructor().copy( this ); - return Triangle.getNormal( this.a, this.b, this.c, target ); + }, - }, + copy: function ( triangle ) { - getPlane: function ( target ) { + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - if ( target === undefined ) { + return this; - console.warn( 'THREE.Triangle: .getPlane() target is now required' ); - target = new Plane(); + }, - } + getArea: function () { - return target.setFromCoplanarPoints( this.a, this.b, this.c ); + _v0$1.subVectors( this.c, this.b ); + _v1$3.subVectors( this.a, this.b ); - }, + return _v0$1.cross( _v1$3 ).length() * 0.5; - getBarycoord: function ( point, target ) { + }, - return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); + getMidpoint: function ( target ) { - }, + if ( target === undefined ) { - getUV: function ( point, uv1, uv2, uv3, target ) { + console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); + target = new Vector3(); - return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); + } - }, + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - containsPoint: function ( point ) { + }, - return Triangle.containsPoint( point, this.a, this.b, this.c ); + getNormal: function ( target ) { - }, + return Triangle.getNormal( this.a, this.b, this.c, target ); - isFrontFacing: function ( direction ) { + }, - return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); + getPlane: function ( target ) { - }, + if ( target === undefined ) { - intersectsBox: function ( box ) { + console.warn( 'THREE.Triangle: .getPlane() target is now required' ); + target = new Plane(); - return box.intersectsTriangle( this ); + } - }, + return target.setFromCoplanarPoints( this.a, this.b, this.c ); - closestPointToPoint: function ( p, target ) { + }, - if ( target === undefined ) { + getBarycoord: function ( point, target ) { - console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); - target = new Vector3(); + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); - } + }, - var a = this.a, b = this.b, c = this.c; - var v, w; + getUV: function ( point, uv1, uv2, uv3, target ) { - // algorithm thanks to Real-Time Collision Detection by Christer Ericson, - // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., - // under the accompanying license; see chapter 5.1.5 for detailed explanation. - // basically, we're distinguishing which of the voronoi regions of the triangle - // the point lies in with the minimum amount of redundant computation. + return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); - _vab.subVectors( b, a ); - _vac.subVectors( c, a ); - _vap.subVectors( p, a ); - var d1 = _vab.dot( _vap ); - var d2 = _vac.dot( _vap ); - if ( d1 <= 0 && d2 <= 0 ) { + }, - // vertex region of A; barycentric coords (1, 0, 0) - return target.copy( a ); + containsPoint: function ( point ) { - } + return Triangle.containsPoint( point, this.a, this.b, this.c ); - _vbp.subVectors( p, b ); - var d3 = _vab.dot( _vbp ); - var d4 = _vac.dot( _vbp ); - if ( d3 >= 0 && d4 <= d3 ) { + }, - // vertex region of B; barycentric coords (0, 1, 0) - return target.copy( b ); + isFrontFacing: function ( direction ) { - } + return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); - var vc = d1 * d4 - d3 * d2; - if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { + }, - v = d1 / ( d1 - d3 ); - // edge region of AB; barycentric coords (1-v, v, 0) - return target.copy( a ).addScaledVector( _vab, v ); + intersectsBox: function ( box ) { - } + return box.intersectsTriangle( this ); - _vcp.subVectors( p, c ); - var d5 = _vab.dot( _vcp ); - var d6 = _vac.dot( _vcp ); - if ( d6 >= 0 && d5 <= d6 ) { + }, - // vertex region of C; barycentric coords (0, 0, 1) - return target.copy( c ); + closestPointToPoint: function ( p, target ) { - } + if ( target === undefined ) { - var vb = d5 * d2 - d1 * d6; - if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { + console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); + target = new Vector3(); - w = d2 / ( d2 - d6 ); - // edge region of AC; barycentric coords (1-w, 0, w) - return target.copy( a ).addScaledVector( _vac, w ); + } - } + var a = this.a, b = this.b, c = this.c; + var v, w; - var va = d3 * d6 - d5 * d4; - if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { + // algorithm thanks to Real-Time Collision Detection by Christer Ericson, + // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., + // under the accompanying license; see chapter 5.1.5 for detailed explanation. + // basically, we're distinguishing which of the voronoi regions of the triangle + // the point lies in with the minimum amount of redundant computation. - _vbc.subVectors( c, b ); - w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); - // edge region of BC; barycentric coords (0, 1-w, w) - return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC + _vab.subVectors( b, a ); + _vac.subVectors( c, a ); + _vap.subVectors( p, a ); + var d1 = _vab.dot( _vap ); + var d2 = _vac.dot( _vap ); + if ( d1 <= 0 && d2 <= 0 ) { - } + // vertex region of A; barycentric coords (1, 0, 0) + return target.copy( a ); - // face region - var denom = 1 / ( va + vb + vc ); - // u = va * denom - v = vb * denom; - w = vc * denom; + } - return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); + _vbp.subVectors( p, b ); + var d3 = _vab.dot( _vbp ); + var d4 = _vac.dot( _vbp ); + if ( d3 >= 0 && d4 <= d3 ) { - }, + // vertex region of B; barycentric coords (0, 1, 0) + return target.copy( b ); + + } - equals: function ( triangle ) { + var vc = d1 * d4 - d3 * d2; + if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + v = d1 / ( d1 - d3 ); + // edge region of AB; barycentric coords (1-v, v, 0) + return target.copy( a ).addScaledVector( _vab, v ); } - } ); + _vcp.subVectors( p, c ); + var d5 = _vab.dot( _vcp ); + var d6 = _vac.dot( _vcp ); + if ( d6 >= 0 && d5 <= d6 ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + // vertex region of C; barycentric coords (0, 0, 1) + return target.copy( c ); + + } - var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + var vb = d5 * d2 - d1 * d6; + if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { - var _hslA = { h: 0, s: 0, l: 0 }; - var _hslB = { h: 0, s: 0, l: 0 }; + w = d2 / ( d2 - d6 ); + // edge region of AC; barycentric coords (1-w, 0, w) + return target.copy( a ).addScaledVector( _vac, w ); - function Color( r, g, b ) { + } - if ( g === undefined && b === undefined ) { + var va = d3 * d6 - d5 * d4; + if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { - // r is THREE.Color, hex or string - return this.set( r ); + _vbc.subVectors( c, b ); + w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); + // edge region of BC; barycentric coords (0, 1-w, w) + return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC } - return this.setRGB( r, g, b ); + // face region + var denom = 1 / ( va + vb + vc ); + // u = va * denom + v = vb * denom; + w = vc * denom; - } + return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); - function hue2rgb( p, q, t ) { + }, - if ( t < 0 ) { t += 1; } - if ( t > 1 ) { t -= 1; } - if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; } - if ( t < 1 / 2 ) { return q; } - if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); } - return p; + equals: function ( triangle ) { - } + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - function SRGBToLinear( c ) { + } - return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); +} ); - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - function LinearToSRGB( c ) { +var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; +var _hslA = { h: 0, s: 0, l: 0 }; +var _hslB = { h: 0, s: 0, l: 0 }; - } +function Color( r, g, b ) { - Object.assign( Color.prototype, { + if ( g === undefined && b === undefined ) { - isColor: true, + // r is THREE.Color, hex or string + return this.set( r ); - r: 1, g: 1, b: 1, + } - set: function ( value ) { + return this.setRGB( r, g, b ); - if ( value && value.isColor ) { +} - this.copy( value ); +function hue2rgb( p, q, t ) { - } else if ( typeof value === 'number' ) { + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; - this.setHex( value ); +} - } else if ( typeof value === 'string' ) { +function SRGBToLinear( c ) { - this.setStyle( value ); + return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); - } +} - return this; +function LinearToSRGB( c ) { - }, + return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; - setScalar: function ( scalar ) { +} - this.r = scalar; - this.g = scalar; - this.b = scalar; +Object.assign( Color.prototype, { - return this; + isColor: true, - }, + r: 1, g: 1, b: 1, - setHex: function ( hex ) { + set: function ( value ) { - hex = Math.floor( hex ); + if ( value && value.isColor ) { - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + this.copy( value ); - return this; + } else if ( typeof value === 'number' ) { - }, + this.setHex( value ); - setRGB: function ( r, g, b ) { + } else if ( typeof value === 'string' ) { - this.r = r; - this.g = g; - this.b = b; + this.setStyle( value ); - return this; + } - }, + return this; - setHSL: function ( h, s, l ) { + }, - // h,s,l ranges are in 0.0 - 1.0 - h = _Math.euclideanModulo( h, 1 ); - s = _Math.clamp( s, 0, 1 ); - l = _Math.clamp( l, 0, 1 ); + setScalar: function ( scalar ) { - if ( s === 0 ) { + this.r = scalar; + this.g = scalar; + this.b = scalar; - this.r = this.g = this.b = l; + return this; - } else { + }, - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + setHex: function ( hex ) { - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + hex = Math.floor( hex ); - } + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - return this; + return this; - }, + }, - setStyle: function ( style ) { + setRGB: function ( r, g, b ) { - function handleAlpha( string ) { + this.r = r; + this.g = g; + this.b = b; - if ( string === undefined ) { return; } + return this; - if ( parseFloat( string ) < 1 ) { + }, - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + setHSL: function ( h, s, l ) { - } + // h,s,l ranges are in 0.0 - 1.0 + h = MathUtils.euclideanModulo( h, 1 ); + s = MathUtils.clamp( s, 0, 1 ); + l = MathUtils.clamp( l, 0, 1 ); - } + if ( s === 0 ) { + this.r = this.g = this.b = l; - var m; + } else { - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - // rgb / hsl + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + } - switch ( name ) { + return this; - case 'rgb': - case 'rgba': + }, - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + setStyle: function ( style ) { - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; + function handleAlpha( string ) { - handleAlpha( color[ 5 ] ); + if ( string === undefined ) return; - return this; + if ( parseFloat( string ) < 1 ) { - } + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + } - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + } - handleAlpha( color[ 5 ] ); - return this; + var m; - } + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - break; + // rgb / hsl - case 'hsl': - case 'hsla': + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + switch ( name ) { - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ) / 360; - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + case 'rgb': + case 'rgba': - handleAlpha( color[ 5 ] ); + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - return this.setHSL( h, s, l ); + // rgb(255,0,0) rgba(255,0,0,0.5) + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - } + handleAlpha( color[ 5 ] ); - break; + return this; - } + } - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - // hex color + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; + this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; + this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - var hex = m[ 1 ]; - var size = hex.length; + handleAlpha( color[ 5 ] ); - if ( size === 3 ) { + return this; - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; + } - return this; + break; - } else if ( size === 6 ) { + case 'hsl': + case 'hsla': - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - return this; + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + var h = parseFloat( color[ 1 ] ) / 360; + var s = parseInt( color[ 2 ], 10 ) / 100; + var l = parseInt( color[ 3 ], 10 ) / 100; - } + handleAlpha( color[ 5 ] ); - } + return this.setHSL( h, s, l ); - if ( style && style.length > 0 ) { + } - return this.setColorName( style ); + break; } - return this; - - }, + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - setColorName: function ( style ) { + // hex color - // color keywords - var hex = _colorKeywords[ style ]; + var hex = m[ 1 ]; + var size = hex.length; - if ( hex !== undefined ) { + if ( size === 3 ) { - // red - this.setHex( hex ); + // #ff0 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - } else { + return this; - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + } else if ( size === 6 ) { - } + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - return this; + return this; - }, + } - clone: function () { + } - return new this.constructor( this.r, this.g, this.b ); + if ( style && style.length > 0 ) { - }, + return this.setColorName( style ); - copy: function ( color ) { + } - this.r = color.r; - this.g = color.g; - this.b = color.b; + return this; - return this; + }, - }, + setColorName: function ( style ) { - copyGammaToLinear: function ( color, gammaFactor ) { + // color keywords + var hex = _colorKeywords[ style ]; - if ( gammaFactor === undefined ) { gammaFactor = 2.0; } + if ( hex !== undefined ) { - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + // red + this.setHex( hex ); - return this; + } else { - }, + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - copyLinearToGamma: function ( color, gammaFactor ) { + } - if ( gammaFactor === undefined ) { gammaFactor = 2.0; } + return this; - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + }, - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + clone: function () { - return this; + return new this.constructor( this.r, this.g, this.b ); - }, + }, - convertGammaToLinear: function ( gammaFactor ) { + copy: function ( color ) { - this.copyGammaToLinear( this, gammaFactor ); + this.r = color.r; + this.g = color.g; + this.b = color.b; - return this; + return this; - }, + }, - convertLinearToGamma: function ( gammaFactor ) { + copyGammaToLinear: function ( color, gammaFactor ) { - this.copyLinearToGamma( this, gammaFactor ); + if ( gammaFactor === undefined ) gammaFactor = 2.0; - return this; + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - }, + return this; - copySRGBToLinear: function ( color ) { + }, - this.r = SRGBToLinear( color.r ); - this.g = SRGBToLinear( color.g ); - this.b = SRGBToLinear( color.b ); + copyLinearToGamma: function ( color, gammaFactor ) { - return this; + if ( gammaFactor === undefined ) gammaFactor = 2.0; - }, + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - copyLinearToSRGB: function ( color ) { + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - this.r = LinearToSRGB( color.r ); - this.g = LinearToSRGB( color.g ); - this.b = LinearToSRGB( color.b ); + return this; - return this; + }, - }, + convertGammaToLinear: function ( gammaFactor ) { - convertSRGBToLinear: function () { + this.copyGammaToLinear( this, gammaFactor ); - this.copySRGBToLinear( this ); + return this; - return this; + }, - }, + convertLinearToGamma: function ( gammaFactor ) { - convertLinearToSRGB: function () { + this.copyLinearToGamma( this, gammaFactor ); - this.copyLinearToSRGB( this ); + return this; - return this; + }, - }, + copySRGBToLinear: function ( color ) { - getHex: function () { + this.r = SRGBToLinear( color.r ); + this.g = SRGBToLinear( color.g ); + this.b = SRGBToLinear( color.b ); - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + return this; - }, + }, - getHexString: function () { + copyLinearToSRGB: function ( color ) { - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + this.r = LinearToSRGB( color.r ); + this.g = LinearToSRGB( color.g ); + this.b = LinearToSRGB( color.b ); - }, + return this; - getHSL: function ( target ) { + }, - // h,s,l ranges are in 0.0 - 1.0 + convertSRGBToLinear: function () { - if ( target === undefined ) { + this.copySRGBToLinear( this ); - console.warn( 'THREE.Color: .getHSL() target is now required' ); - target = { h: 0, s: 0, l: 0 }; + return this; - } + }, - var r = this.r, g = this.g, b = this.b; + convertLinearToSRGB: function () { - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + this.copyLinearToSRGB( this ); - var hue, saturation; - var lightness = ( min + max ) / 2.0; + return this; - if ( min === max ) { + }, - hue = 0; - saturation = 0; + getHex: function () { - } else { + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - var delta = max - min; + }, - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + getHexString: function () { - switch ( max ) { + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; + }, - } + getHSL: function ( target ) { - hue /= 6; + // h,s,l ranges are in 0.0 - 1.0 - } + if ( target === undefined ) { - target.h = hue; - target.s = saturation; - target.l = lightness; + console.warn( 'THREE.Color: .getHSL() target is now required' ); + target = { h: 0, s: 0, l: 0 }; - return target; + } - }, + var r = this.r, g = this.g, b = this.b; - getStyle: function () { + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + var hue, saturation; + var lightness = ( min + max ) / 2.0; - }, + if ( min === max ) { - offsetHSL: function ( h, s, l ) { + hue = 0; + saturation = 0; - this.getHSL( _hslA ); + } else { - _hslA.h += h; _hslA.s += s; _hslA.l += l; + var delta = max - min; - this.setHSL( _hslA.h, _hslA.s, _hslA.l ); + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); - return this; + switch ( max ) { - }, + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; - add: function ( color ) { + } - this.r += color.r; - this.g += color.g; - this.b += color.b; + hue /= 6; - return this; + } - }, + target.h = hue; + target.s = saturation; + target.l = lightness; - addColors: function ( color1, color2 ) { + return target; - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + }, - return this; + getStyle: function () { - }, + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - addScalar: function ( s ) { + }, - this.r += s; - this.g += s; - this.b += s; + offsetHSL: function ( h, s, l ) { - return this; + this.getHSL( _hslA ); - }, + _hslA.h += h; _hslA.s += s; _hslA.l += l; - sub: function ( color ) { + this.setHSL( _hslA.h, _hslA.s, _hslA.l ); - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); + return this; - return this; + }, - }, + add: function ( color ) { - multiply: function ( color ) { + this.r += color.r; + this.g += color.g; + this.b += color.b; - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + return this; - return this; + }, - }, + addColors: function ( color1, color2 ) { - multiplyScalar: function ( s ) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - this.r *= s; - this.g *= s; - this.b *= s; + return this; - return this; + }, - }, + addScalar: function ( s ) { - lerp: function ( color, alpha ) { + this.r += s; + this.g += s; + this.b += s; - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + return this; - return this; + }, - }, + sub: function ( color ) { - lerpHSL: function ( color, alpha ) { + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); - this.getHSL( _hslA ); - color.getHSL( _hslB ); + return this; - var h = _Math.lerp( _hslA.h, _hslB.h, alpha ); - var s = _Math.lerp( _hslA.s, _hslB.s, alpha ); - var l = _Math.lerp( _hslA.l, _hslB.l, alpha ); + }, - this.setHSL( h, s, l ); + multiply: function ( color ) { - return this; + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - }, + return this; - equals: function ( c ) { + }, - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + multiplyScalar: function ( s ) { - }, + this.r *= s; + this.g *= s; + this.b *= s; - fromArray: function ( array, offset ) { + return this; - if ( offset === undefined ) { offset = 0; } + }, - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + lerp: function ( color, alpha ) { - return this; + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - }, + return this; - toArray: function ( array, offset ) { + }, - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + lerpHSL: function ( color, alpha ) { - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + this.getHSL( _hslA ); + color.getHSL( _hslB ); - return array; + var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); + var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); + var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); - }, + this.setHSL( h, s, l ); - toJSON: function () { + return this; - return this.getHex(); + }, - } + equals: function ( c ) { - } ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - Color.NAMES = _colorKeywords; + }, - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + fromArray: function ( array, offset ) { - function Face3( a, b, c, normal, color, materialIndex ) { + if ( offset === undefined ) offset = 0; - this.a = a; - this.b = b; - this.c = c; + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; - this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + return this; - this.color = ( color && color.isColor ) ? color : new Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + }, - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + toArray: function ( array, offset ) { - } + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - Object.assign( Face3.prototype, { + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; - clone: function () { + return array; - return new this.constructor().copy( this ); + }, - }, + toJSON: function () { - copy: function ( source ) { + return this.getHex(); - this.a = source.a; - this.b = source.b; - this.c = source.c; + } - this.normal.copy( source.normal ); - this.color.copy( source.color ); +} ); - this.materialIndex = source.materialIndex; +Color.NAMES = _colorKeywords; - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); +function Face3( a, b, c, normal, color, materialIndex ) { - } + this.a = a; + this.b = b; + this.c = c; - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { + this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + this.color = ( color && color.isColor ) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - } + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - return this; +} - } +Object.assign( Face3.prototype, { - } ); + clone: function () { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + return new this.constructor().copy( this ); - var materialId = 0; + }, - function Material() { + copy: function ( source ) { - Object.defineProperty( this, 'id', { value: materialId ++ } ); + this.a = source.a; + this.b = source.b; + this.c = source.c; - this.uuid = _Math.generateUUID(); + this.normal.copy( source.normal ); + this.color.copy( source.color ); - this.name = ''; - this.type = 'Material'; + this.materialIndex = source.materialIndex; - this.fog = true; + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - this.blending = NormalBlending; - this.side = FrontSide; - this.flatShading = false; - this.vertexTangents = false; - this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - this.opacity = 1; - this.transparent = false; + } - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); - this.stencilWriteMask = 0xff; - this.stencilFunc = AlwaysStencilFunc; - this.stencilRef = 0; - this.stencilFuncMask = 0xff; - this.stencilFail = KeepStencilOp; - this.stencilZFail = KeepStencilOp; - this.stencilZPass = KeepStencilOp; - this.stencilWrite = false; + } - this.clippingPlanes = null; - this.clipIntersection = false; - this.clipShadows = false; + return this; - this.shadowSide = null; + } - this.colorWrite = true; +} ); - this.precision = null; // override the renderer's default precision for this material +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; +var materialId = 0; - this.dithering = false; +function Material() { - this.alphaTest = 0; - this.premultipliedAlpha = false; + Object.defineProperty( this, 'id', { value: materialId ++ } ); - this.visible = true; + this.uuid = MathUtils.generateUUID(); - this.toneMapped = true; + this.name = ''; + this.type = 'Material'; - this.userData = {}; + this.fog = true; - this.needsUpdate = true; + this.blending = NormalBlending; + this.side = FrontSide; + this.flatShading = false; + this.vertexColors = false; - } + this.opacity = 1; + this.transparent = false; - Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - constructor: Material, + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - isMaterial: true, + this.stencilWriteMask = 0xff; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 0xff; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; - onBeforeCompile: function () {}, + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; - setValues: function ( values ) { + this.shadowSide = null; - if ( values === undefined ) { return; } + this.colorWrite = true; - for ( var key in values ) { + this.precision = null; // override the renderer's default precision for this material - var newValue = values[ key ]; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - if ( newValue === undefined ) { + this.dithering = false; - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + this.alphaTest = 0; + this.premultipliedAlpha = false; - } + this.visible = true; - // for backward compatability if shading is set in the constructor - if ( key === 'shading' ) { + this.toneMapped = true; - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( newValue === FlatShading ) ? true : false; - continue; + this.userData = {}; - } + this.version = 0; - var currentValue = this[ key ]; +} - if ( currentValue === undefined ) { +Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + constructor: Material, - } + isMaterial: true, - if ( currentValue && currentValue.isColor ) { + onBeforeCompile: function () {}, - currentValue.set( newValue ); + setValues: function ( values ) { - } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + if ( values === undefined ) return; - currentValue.copy( newValue ); + for ( var key in values ) { - } else { + var newValue = values[ key ]; - this[ key ] = newValue; + if ( newValue === undefined ) { - } + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; } - }, - - toJSON: function ( meta ) { - - var isRoot = ( meta === undefined || typeof meta === 'string' ); + // for backward compatability if shading is set in the constructor + if ( key === 'shading' ) { - if ( isRoot ) { - - meta = { - textures: {}, - images: {} - }; + console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + this.flatShading = ( newValue === FlatShading ) ? true : false; + continue; } - var data = { - metadata: { - version: 4.5, - type: 'Material', - generator: 'Material.toJSON' - } - }; + var currentValue = this[ key ]; - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + if ( currentValue === undefined ) { + + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; - if ( this.name !== '' ) { data.name = this.name; } + } - if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); } + if ( currentValue && currentValue.isColor ) { - if ( this.roughness !== undefined ) { data.roughness = this.roughness; } - if ( this.metalness !== undefined ) { data.metalness = this.metalness; } + currentValue.set( newValue ); - if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); } - if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); } - if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; } + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { - if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); } - if ( this.shininess !== undefined ) { data.shininess = this.shininess; } - if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; } - if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; } + currentValue.copy( newValue ); - if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { + } else { - data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; - data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + this[ key ] = newValue; } - if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; } - if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; } - if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; } - if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; } + } - if ( this.aoMap && this.aoMap.isTexture ) { + }, - data.aoMap = this.aoMap.toJSON( meta ).uuid; - data.aoMapIntensity = this.aoMapIntensity; + toJSON: function ( meta ) { - } + var isRoot = ( meta === undefined || typeof meta === 'string' ); - if ( this.bumpMap && this.bumpMap.isTexture ) { + if ( isRoot ) { - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + meta = { + textures: {}, + images: {} + }; + + } + var data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' } + }; - if ( this.normalMap && this.normalMap.isTexture ) { + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalMapType = this.normalMapType; - data.normalScale = this.normalScale.toArray(); + if ( this.name !== '' ) data.name = this.name; - } + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); - if ( this.displacementMap && this.displacementMap.isTexture ) { + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex(); + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; - } + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat; + if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness; - if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; } - if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; } + if ( this.clearcoatMap && this.clearcoatMap.isTexture ) { - if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; } - if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; } + data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid; - if ( this.envMap && this.envMap.isTexture ) { + } - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap - data.refractionRatio = this.refractionRatio; + if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) { - if ( this.combine !== undefined ) { data.combine = this.combine; } - if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; } + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid; - } + } - if ( this.gradientMap && this.gradientMap.isTexture ) { + if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { - data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); - } + } - if ( this.size !== undefined ) { data.size = this.size; } - if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; } + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid; + if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.blending !== NormalBlending ) { data.blending = this.blending; } - if ( this.flatShading === true ) { data.flatShading = this.flatShading; } - if ( this.side !== FrontSide ) { data.side = this.side; } - if ( this.vertexColors !== NoColors ) { data.vertexColors = this.vertexColors; } + if ( this.aoMap && this.aoMap.isTexture ) { - if ( this.opacity < 1 ) { data.opacity = this.opacity; } - if ( this.transparent === true ) { data.transparent = this.transparent; } + data.aoMap = this.aoMap.toJSON( meta ).uuid; + data.aoMapIntensity = this.aoMapIntensity; - data.depthFunc = this.depthFunc; - data.depthTest = this.depthTest; - data.depthWrite = this.depthWrite; + } - data.stencilWrite = this.stencilWrite; - data.stencilWriteMask = this.stencilWriteMask; - data.stencilFunc = this.stencilFunc; - data.stencilRef = this.stencilRef; - data.stencilFuncMask = this.stencilFuncMask; - data.stencilFail = this.stencilFail; - data.stencilZFail = this.stencilZFail; - data.stencilZPass = this.stencilZPass; + if ( this.bumpMap && this.bumpMap.isTexture ) { - // rotation (SpriteMaterial) - if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; } + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - if ( this.polygonOffset === true ) { data.polygonOffset = true; } - if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; } - if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; } + } - if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; } - if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; } - if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; } - if ( this.scale !== undefined ) { data.scale = this.scale; } + if ( this.normalMap && this.normalMap.isTexture ) { - if ( this.dithering === true ) { data.dithering = true; } + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); - if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; } - if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; } + } - if ( this.wireframe === true ) { data.wireframe = this.wireframe; } - if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; } - if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; } - if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; } + if ( this.displacementMap && this.displacementMap.isTexture ) { - if ( this.morphTargets === true ) { data.morphTargets = true; } - if ( this.morphNormals === true ) { data.morphNormals = true; } - if ( this.skinning === true ) { data.skinning = true; } + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; - if ( this.visible === false ) { data.visible = false; } + } - if ( this.toneMapped === false ) { data.toneMapped = false; } + if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; } + if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - // TODO: Copied from Object3D.toJSON + if ( this.envMap && this.envMap.isTexture ) { - function extractFromCache( cache ) { + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap + data.refractionRatio = this.refractionRatio; - var values = []; + if ( this.combine !== undefined ) data.combine = this.combine; + if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity; - for ( var key in cache ) { + } - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + if ( this.gradientMap && this.gradientMap.isTexture ) { - } + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; - return values; + } - } + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - if ( isRoot ) { + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.flatShading === true ) data.flatShading = this.flatShading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors ) data.vertexColors = true; - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - if ( textures.length > 0 ) { data.textures = textures; } - if ( images.length > 0 ) { data.images = images; } + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; - } + data.stencilWrite = this.stencilWrite; + data.stencilWriteMask = this.stencilWriteMask; + data.stencilFunc = this.stencilFunc; + data.stencilRef = this.stencilRef; + data.stencilFuncMask = this.stencilFuncMask; + data.stencilFail = this.stencilFail; + data.stencilZFail = this.stencilZFail; + data.stencilZPass = this.stencilZPass; - return data; + // rotation (SpriteMaterial) + if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation; - }, + if ( this.polygonOffset === true ) data.polygonOffset = true; + if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor; + if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits; - clone: function () { + if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; - return new this.constructor().copy( this ); + if ( this.dithering === true ) data.dithering = true; - }, + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - copy: function ( source ) { + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - this.name = source.name; + if ( this.morphTargets === true ) data.morphTargets = true; + if ( this.morphNormals === true ) data.morphNormals = true; + if ( this.skinning === true ) data.skinning = true; - this.fog = source.fog; + if ( this.visible === false ) data.visible = false; - this.blending = source.blending; - this.side = source.side; - this.flatShading = source.flatShading; - this.vertexTangents = source.vertexTangents; - this.vertexColors = source.vertexColors; + if ( this.toneMapped === false ) data.toneMapped = false; - this.opacity = source.opacity; - this.transparent = source.transparent; + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + // TODO: Copied from Object3D.toJSON - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + function extractFromCache( cache ) { - this.stencilWriteMask = source.stencilWriteMask; - this.stencilFunc = source.stencilFunc; - this.stencilRef = source.stencilRef; - this.stencilFuncMask = source.stencilFuncMask; - this.stencilFail = source.stencilFail; - this.stencilZFail = source.stencilZFail; - this.stencilZPass = source.stencilZPass; - this.stencilWrite = source.stencilWrite; + var values = []; - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + for ( var key in cache ) { - if ( srcPlanes !== null ) { + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var n = srcPlanes.length; - dstPlanes = new Array( n ); + } - for ( var i = 0; i !== n; ++ i ) - { dstPlanes[ i ] = srcPlanes[ i ].clone(); } + return values; - } + } - this.clippingPlanes = dstPlanes; - this.clipIntersection = source.clipIntersection; - this.clipShadows = source.clipShadows; + if ( isRoot ) { - this.shadowSide = source.shadowSide; + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - this.colorWrite = source.colorWrite; + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - this.precision = source.precision; + } - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + return data; - this.dithering = source.dithering; + }, - this.alphaTest = source.alphaTest; - this.premultipliedAlpha = source.premultipliedAlpha; + clone: function () { - this.visible = source.visible; + return new this.constructor().copy( this ); - this.toneMapped = source.toneMapped; + }, - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + copy: function ( source ) { - return this; + this.name = source.name; - }, + this.fog = source.fog; - dispose: function () { + this.blending = source.blending; + this.side = source.side; + this.flatShading = source.flatShading; + this.vertexColors = source.vertexColors; - this.dispatchEvent( { type: 'dispose' } ); + this.opacity = source.opacity; + this.transparent = source.transparent; - } + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - } ); + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; - function MeshBasicMaterial( parameters ) { + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - Material.call( this ); + if ( srcPlanes !== null ) { - this.type = 'MeshBasicMaterial'; + var n = srcPlanes.length; + dstPlanes = new Array( n ); - this.color = new Color( 0xffffff ); // emissive + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; - this.aoMap = null; - this.aoMapIntensity = 1.0; + this.shadowSide = source.shadowSide; - this.specularMap = null; + this.colorWrite = source.colorWrite; - this.alphaMap = null; + this.precision = source.precision; - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.dithering = source.dithering; - this.skinning = false; - this.morphTargets = false; + this.alphaTest = source.alphaTest; + this.premultipliedAlpha = source.premultipliedAlpha; - this.setValues( parameters ); + this.visible = source.visible; - } + this.toneMapped = source.toneMapped; - MeshBasicMaterial.prototype = Object.create( Material.prototype ); - MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + return this; - MeshBasicMaterial.prototype.copy = function ( source ) { + }, - Material.prototype.copy.call( this, source ); + dispose: function () { - this.color.copy( source.color ); + this.dispatchEvent( { type: 'dispose' } ); - this.map = source.map; + } - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; +} ); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; +Object.defineProperty( Material.prototype, 'needsUpdate', { - this.specularMap = source.specularMap; + set: function ( value ) { - this.alphaMap = source.alphaMap; + if ( value === true ) this.version ++; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; +} ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * depthTest: , + * depthWrite: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: + * } + */ - return this; +function MeshBasicMaterial( parameters ) { - }; + Material.call( this ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.type = 'MeshBasicMaterial'; - function BufferAttribute( array, itemSize, normalized ) { + this.color = new Color( 0xffffff ); // emissive - if ( Array.isArray( array ) ) { + this.map = null; - throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + this.lightMap = null; + this.lightMapIntensity = 1.0; - } + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.name = ''; + this.specularMap = null; - this.array = array; - this.itemSize = itemSize; - this.count = array !== undefined ? array.length / itemSize : 0; - this.normalized = normalized === true; + this.alphaMap = null; - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - this.version = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - } + this.skinning = false; + this.morphTargets = false; - Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { + this.setValues( parameters ); - set: function ( value ) { +} - if ( value === true ) { this.version ++; } +MeshBasicMaterial.prototype = Object.create( Material.prototype ); +MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - } +MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - } ); +MeshBasicMaterial.prototype.copy = function ( source ) { - Object.assign( BufferAttribute.prototype, { + Material.prototype.copy.call( this, source ); - isBufferAttribute: true, + this.color.copy( source.color ); - onUploadCallback: function () {}, + this.map = source.map; - setUsage: function ( value ) { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.usage = value; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - return this; + this.specularMap = source.specularMap; - }, + this.alphaMap = source.alphaMap; - copy: function ( source ) { + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.name = source.name; - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; - this.count = source.count; - this.normalized = source.normalized; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.usage = source.usage; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - return this; + return this; - }, +}; - copyAt: function ( index1, attribute, index2 ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - index1 *= this.itemSize; - index2 *= attribute.itemSize; +var _vector$3 = new Vector3(); - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { +function BufferAttribute( array, itemSize, normalized ) { - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + if ( Array.isArray( array ) ) { - } + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); - return this; + } - }, + this.name = ''; - copyArray: function ( array ) { + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized === true; - this.array.set( array ); + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; - return this; + this.version = 0; - }, +} - copyColorsArray: function ( colors ) { +Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { - var array = this.array, offset = 0; + set: function ( value ) { - for ( var i = 0, l = colors.length; i < l; i ++ ) { + if ( value === true ) this.version ++; - var color = colors[ i ]; + } - if ( color === undefined ) { +} ); - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); +Object.assign( BufferAttribute.prototype, { - } + isBufferAttribute: true, - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; + onUploadCallback: function () {}, - } + setUsage: function ( value ) { - return this; + this.usage = value; - }, + return this; - copyVector2sArray: function ( vectors ) { + }, - var array = this.array, offset = 0; + copy: function ( source ) { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + this.name = source.name; + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; - var vector = vectors[ i ]; + this.usage = source.usage; - if ( vector === undefined ) { + return this; - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + }, - } + copyAt: function ( index1, attribute, index2 ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + index1 *= this.itemSize; + index2 *= attribute.itemSize; - } + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - return this; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - }, + } - copyVector3sArray: function ( vectors ) { + return this; - var array = this.array, offset = 0; + }, - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + copyArray: function ( array ) { - var vector = vectors[ i ]; + this.array.set( array ); - if ( vector === undefined ) { + return this; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + }, - } + copyColorsArray: function ( colors ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + var array = this.array, offset = 0; - } + for ( var i = 0, l = colors.length; i < l; i ++ ) { - return this; + var color = colors[ i ]; - }, + if ( color === undefined ) { - copyVector4sArray: function ( vectors ) { + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - var array = this.array, offset = 0; + } - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - var vector = vectors[ i ]; + } - if ( vector === undefined ) { + return this; - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + }, - } + copyVector2sArray: function ( vectors ) { - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + var array = this.array, offset = 0; - } + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - return this; + var vector = vectors[ i ]; - }, + if ( vector === undefined ) { - set: function ( value, offset ) { + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); - if ( offset === undefined ) { offset = 0; } + } - this.array.set( value, offset ); + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; - return this; + } - }, + return this; - getX: function ( index ) { + }, - return this.array[ index * this.itemSize ]; + copyVector3sArray: function ( vectors ) { - }, + var array = this.array, offset = 0; - setX: function ( index, x ) { + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - this.array[ index * this.itemSize ] = x; + var vector = vectors[ i ]; - return this; + if ( vector === undefined ) { - }, + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - getY: function ( index ) { + } - return this.array[ index * this.itemSize + 1 ]; + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - }, + } - setY: function ( index, y ) { + return this; - this.array[ index * this.itemSize + 1 ] = y; + }, - return this; + copyVector4sArray: function ( vectors ) { - }, + var array = this.array, offset = 0; - getZ: function ( index ) { + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - return this.array[ index * this.itemSize + 2 ]; + var vector = vectors[ i ]; - }, + if ( vector === undefined ) { - setZ: function ( index, z ) { + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - this.array[ index * this.itemSize + 2 ] = z; + } - return this; + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - }, + } - getW: function ( index ) { + return this; - return this.array[ index * this.itemSize + 3 ]; + }, - }, + applyMatrix3: function ( m ) { - setW: function ( index, w ) { + for ( var i = 0, l = this.count; i < l; i ++ ) { - this.array[ index * this.itemSize + 3 ] = w; + _vector$3.x = this.getX( i ); + _vector$3.y = this.getY( i ); + _vector$3.z = this.getZ( i ); - return this; + _vector$3.applyMatrix3( m ); - }, + this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); - setXY: function ( index, x, y ) { + } - index *= this.itemSize; + return this; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + }, - return this; + applyMatrix4: function ( m ) { - }, + for ( var i = 0, l = this.count; i < l; i ++ ) { - setXYZ: function ( index, x, y, z ) { + _vector$3.x = this.getX( i ); + _vector$3.y = this.getY( i ); + _vector$3.z = this.getZ( i ); - index *= this.itemSize; + _vector$3.applyMatrix4( m ); - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); - return this; + } - }, + return this; - setXYZW: function ( index, x, y, z, w ) { + }, - index *= this.itemSize; + applyNormalMatrix: function ( m ) { - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + for ( var i = 0, l = this.count; i < l; i ++ ) { - return this; + _vector$3.x = this.getX( i ); + _vector$3.y = this.getY( i ); + _vector$3.z = this.getZ( i ); - }, + _vector$3.applyNormalMatrix( m ); - onUpload: function ( callback ) { + this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); - this.onUploadCallback = callback; + } - return this; + return this; - }, + }, - clone: function () { + transformDirection: function ( m ) { - return new this.constructor( this.array, this.itemSize ).copy( this ); + for ( var i = 0, l = this.count; i < l; i ++ ) { - }, + _vector$3.x = this.getX( i ); + _vector$3.y = this.getY( i ); + _vector$3.z = this.getZ( i ); - toJSON: function () { + _vector$3.transformDirection( m ); - return { - itemSize: this.itemSize, - type: this.array.constructor.name, - array: Array.prototype.slice.call( this.array ), - normalized: this.normalized - }; + this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); } - } ); - - // + return this; - function Int8BufferAttribute( array, itemSize, normalized ) { + }, - BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); + set: function ( value, offset ) { - } + if ( offset === undefined ) offset = 0; - Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; + this.array.set( value, offset ); + return this; - function Uint8BufferAttribute( array, itemSize, normalized ) { + }, - BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); + getX: function ( index ) { - } + return this.array[ index * this.itemSize ]; - Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; + }, + setX: function ( index, x ) { - function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { + this.array[ index * this.itemSize ] = x; - BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); + return this; - } + }, - Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; + getY: function ( index ) { + return this.array[ index * this.itemSize + 1 ]; - function Int16BufferAttribute( array, itemSize, normalized ) { + }, - BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); + setY: function ( index, y ) { - } + this.array[ index * this.itemSize + 1 ] = y; - Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; + return this; + }, - function Uint16BufferAttribute( array, itemSize, normalized ) { + getZ: function ( index ) { - BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); + return this.array[ index * this.itemSize + 2 ]; - } + }, - Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; + setZ: function ( index, z ) { + this.array[ index * this.itemSize + 2 ] = z; - function Int32BufferAttribute( array, itemSize, normalized ) { + return this; - BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); + }, - } + getW: function ( index ) { - Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; + return this.array[ index * this.itemSize + 3 ]; + }, - function Uint32BufferAttribute( array, itemSize, normalized ) { + setW: function ( index, w ) { - BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); + this.array[ index * this.itemSize + 3 ] = w; - } + return this; - Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; + }, + setXY: function ( index, x, y ) { - function Float32BufferAttribute( array, itemSize, normalized ) { + index *= this.itemSize; - BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - } + return this; - Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; + }, + setXYZ: function ( index, x, y, z ) { - function Float64BufferAttribute( array, itemSize, normalized ) { + index *= this.itemSize; - BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; - } + return this; - Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + setXYZW: function ( index, x, y, z, w ) { - function DirectGeometry() { + index *= this.itemSize; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - this.groups = []; + return this; - this.morphTargets = {}; + }, - this.skinWeights = []; - this.skinIndices = []; + onUpload: function ( callback ) { - // this.lineDistances = []; + this.onUploadCallback = callback; - this.boundingBox = null; - this.boundingSphere = null; + return this; - // update flags + }, - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + clone: function () { - } + return new this.constructor( this.array, this.itemSize ).copy( this ); - Object.assign( DirectGeometry.prototype, { + }, - computeGroups: function ( geometry ) { + toJSON: function () { - var group; - var groups = []; - var materialIndex = undefined; + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.prototype.slice.call( this.array ), + normalized: this.normalized + }; - var faces = geometry.faces; + } - for ( var i = 0; i < faces.length; i ++ ) { +} ); - var face = faces[ i ]; +// - // materials +function Int8BufferAttribute( array, itemSize, normalized ) { - if ( face.materialIndex !== materialIndex ) { + BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); - materialIndex = face.materialIndex; +} - if ( group !== undefined ) { +Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; - group.count = ( i * 3 ) - group.start; - groups.push( group ); - } +function Uint8BufferAttribute( array, itemSize, normalized ) { - group = { - start: i * 3, - materialIndex: materialIndex - }; + BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); - } +} - } +Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; - if ( group !== undefined ) { - group.count = ( i * 3 ) - group.start; - groups.push( group ); +function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { - } + BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); - this.groups = groups; +} - }, +Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; - fromGeometry: function ( geometry ) { - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; +function Int16BufferAttribute( array, itemSize, normalized ) { - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); - // morphs +} - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; +Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; - var morphTargetsPosition; - if ( morphTargetsLength > 0 ) { +function Uint16BufferAttribute( array, itemSize, normalized ) { - morphTargetsPosition = []; + BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); - for ( var i = 0; i < morphTargetsLength; i ++ ) { +} - morphTargetsPosition[ i ] = { - name: morphTargets[ i ].name, - data: [] - }; +Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; - } - this.morphTargets.position = morphTargetsPosition; +function Int32BufferAttribute( array, itemSize, normalized ) { - } + BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; +} - var morphTargetsNormal; +Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; - if ( morphNormalsLength > 0 ) { - morphTargetsNormal = []; +function Uint32BufferAttribute( array, itemSize, normalized ) { - for ( var i = 0; i < morphNormalsLength; i ++ ) { + BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); - morphTargetsNormal[ i ] = { - name: morphNormals[ i ].name, - data: [] - }; +} - } +Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; - this.morphTargets.normal = morphTargetsNormal; - } +function Float32BufferAttribute( array, itemSize, normalized ) { - // skins + BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; +} - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; +Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; - // - if ( vertices.length > 0 && faces.length === 0 ) { +function Float64BufferAttribute( array, itemSize, normalized ) { - console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' ); + BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); - } +} - for ( var i = 0; i < faces.length; i ++ ) { +Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); +Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; - var face = faces[ i ]; +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); +function DirectGeometry() { - var vertexNormals = face.vertexNormals; + this.vertices = []; + this.normals = []; + this.colors = []; + this.uvs = []; + this.uvs2 = []; - if ( vertexNormals.length === 3 ) { + this.groups = []; - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + this.morphTargets = {}; - } else { + this.skinWeights = []; + this.skinIndices = []; - var normal = face.normal; + // this.lineDistances = []; - this.normals.push( normal, normal, normal ); + this.boundingBox = null; + this.boundingSphere = null; - } + // update flags - var vertexColors = face.vertexColors; + this.verticesNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.uvsNeedUpdate = false; + this.groupsNeedUpdate = false; - if ( vertexColors.length === 3 ) { +} - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); +Object.assign( DirectGeometry.prototype, { - } else { + computeGroups: function ( geometry ) { - var color = face.color; + var group; + var groups = []; + var materialIndex = undefined; - this.colors.push( color, color, color ); + var faces = geometry.faces; - } + for ( var i = 0; i < faces.length; i ++ ) { - if ( hasFaceVertexUv === true ) { + var face = faces[ i ]; - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + // materials - if ( vertexUvs !== undefined ) { + if ( face.materialIndex !== materialIndex ) { - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + materialIndex = face.materialIndex; - } else { + if ( group !== undefined ) { - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + group.count = ( i * 3 ) - group.start; + groups.push( group ); - this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); + } - } + group = { + start: i * 3, + materialIndex: materialIndex + }; - } + } - if ( hasFaceVertexUv2 === true ) { + } - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + if ( group !== undefined ) { - if ( vertexUvs !== undefined ) { + group.count = ( i * 3 ) - group.start; + groups.push( group ); - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + } - } else { + this.groups = groups; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + }, - this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); + fromGeometry: function ( geometry ) { - } + var faces = geometry.faces; + var vertices = geometry.vertices; + var faceVertexUvs = geometry.faceVertexUvs; - } + var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; - // morphs + // morphs - for ( var j = 0; j < morphTargetsLength; j ++ ) { + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - var morphTarget = morphTargets[ j ].vertices; + var morphTargetsPosition; - morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + if ( morphTargetsLength > 0 ) { - } + morphTargetsPosition = []; - for ( var j = 0; j < morphNormalsLength; j ++ ) { + for ( var i = 0; i < morphTargetsLength; i ++ ) { - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + morphTargetsPosition[ i ] = { + name: morphTargets[ i ].name, + data: [] + }; - morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c ); + } - } + this.morphTargets.position = morphTargetsPosition; - // skins + } - if ( hasSkinIndices ) { + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + var morphTargetsNormal; - } + if ( morphNormalsLength > 0 ) { - if ( hasSkinWeights ) { + morphTargetsNormal = []; - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + for ( var i = 0; i < morphNormalsLength; i ++ ) { - } + morphTargetsNormal[ i ] = { + name: morphNormals[ i ].name, + data: [] + }; } - this.computeGroups( geometry ); + this.morphTargets.normal = morphTargetsNormal; - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; - - if ( geometry.boundingSphere !== null ) { + } - this.boundingSphere = geometry.boundingSphere.clone(); + // skins - } + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - if ( geometry.boundingBox !== null ) { + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - this.boundingBox = geometry.boundingBox.clone(); + // - } + if ( vertices.length > 0 && faces.length === 0 ) { - return this; + console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' ); } - } ); - - /** - * @author mrdoob / http://mrdoob.com/ - */ + for ( var i = 0; i < faces.length; i ++ ) { - function arrayMax( array ) { + var face = faces[ i ]; - if ( array.length === 0 ) { return - Infinity; } + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - var max = array[ 0 ]; + var vertexNormals = face.vertexNormals; - for ( var i = 1, l = array.length; i < l; ++ i ) { + if ( vertexNormals.length === 3 ) { - if ( array[ i ] > max ) { max = array[ i ]; } + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - } + } else { - return max; + var normal = face.normal; - } + this.normals.push( normal, normal, normal ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + } - var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id + var vertexColors = face.vertexColors; - var _m1$2 = new Matrix4(); - var _obj = new Object3D(); - var _offset = new Vector3(); - var _box$2 = new Box3(); - var _boxMorphTargets = new Box3(); - var _vector$4 = new Vector3(); + if ( vertexColors.length === 3 ) { - function BufferGeometry() { + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } ); + } else { - this.uuid = _Math.generateUUID(); + var color = face.color; - this.name = ''; - this.type = 'BufferGeometry'; + this.colors.push( color, color, color ); - this.index = null; - this.attributes = {}; + } - this.morphAttributes = {}; - this.morphTargetsRelative = false; + if ( hasFaceVertexUv === true ) { - this.groups = []; + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - this.boundingBox = null; - this.boundingSphere = null; + if ( vertexUvs !== undefined ) { - this.drawRange = { start: 0, count: Infinity }; + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - this.userData = {}; + } else { - } + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - constructor: BufferGeometry, + } - isBufferGeometry: true, + } - getIndex: function () { + if ( hasFaceVertexUv2 === true ) { - return this.index; + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - }, + if ( vertexUvs !== undefined ) { - setIndex: function ( index ) { + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - if ( Array.isArray( index ) ) { + } else { - this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - } else { + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - this.index = index; + } } - }, + // morphs - getAttribute: function ( name ) { + for ( var j = 0; j < morphTargetsLength; j ++ ) { - return this.attributes[ name ]; + var morphTarget = morphTargets[ j ].vertices; - }, + morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); - setAttribute: function ( name, attribute ) { + } - this.attributes[ name ] = attribute; + for ( var j = 0; j < morphNormalsLength; j ++ ) { - return this; + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; - }, + morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c ); - deleteAttribute: function ( name ) { + } - delete this.attributes[ name ]; + // skins - return this; + if ( hasSkinIndices ) { - }, + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); - addGroup: function ( start, count, materialIndex ) { + } - this.groups.push( { + if ( hasSkinWeights ) { - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); - } ); + } - }, + } - clearGroups: function () { + this.computeGroups( geometry ); - this.groups = []; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - }, + if ( geometry.boundingSphere !== null ) { - setDrawRange: function ( start, count ) { + this.boundingSphere = geometry.boundingSphere.clone(); - this.drawRange.start = start; - this.drawRange.count = count; + } - }, + if ( geometry.boundingBox !== null ) { - applyMatrix: function ( matrix ) { + this.boundingBox = geometry.boundingBox.clone(); - var position = this.attributes.position; + } - if ( position !== undefined ) { + return this; - matrix.applyToBufferAttribute( position ); - position.needsUpdate = true; + } - } +} ); - var normal = this.attributes.normal; +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( normal !== undefined ) { +function arrayMax( array ) { - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + if ( array.length === 0 ) return - Infinity; - normalMatrix.applyToBufferAttribute( normal ); - normal.needsUpdate = true; + let max = array[ 0 ]; - } + for ( let i = 1, l = array.length; i < l; ++ i ) { - var tangent = this.attributes.tangent; + if ( array[ i ] > max ) max = array[ i ]; - if ( tangent !== undefined ) { + } - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + return max; - // Tangent is vec4, but the '.w' component is a sign value (+1/-1). - normalMatrix.applyToBufferAttribute( tangent ); - tangent.needsUpdate = true; +} - } +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - if ( this.boundingBox !== null ) { +var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id - this.computeBoundingBox(); +var _m1$2 = new Matrix4(); +var _obj = new Object3D(); +var _offset = new Vector3(); +var _box$2 = new Box3(); +var _boxMorphTargets = new Box3(); +var _vector$4 = new Vector3(); - } +function BufferGeometry() { - if ( this.boundingSphere !== null ) { + Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } ); - this.computeBoundingSphere(); + this.uuid = MathUtils.generateUUID(); - } + this.name = ''; + this.type = 'BufferGeometry'; - return this; + this.index = null; + this.attributes = {}; - }, + this.morphAttributes = {}; + this.morphTargetsRelative = false; - rotateX: function ( angle ) { + this.groups = []; - // rotate geometry around world x-axis + this.boundingBox = null; + this.boundingSphere = null; - _m1$2.makeRotationX( angle ); + this.drawRange = { start: 0, count: Infinity }; - this.applyMatrix( _m1$2 ); + this.userData = {}; - return this; +} - }, +BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - rotateY: function ( angle ) { + constructor: BufferGeometry, - // rotate geometry around world y-axis + isBufferGeometry: true, - _m1$2.makeRotationY( angle ); + getIndex: function () { - this.applyMatrix( _m1$2 ); + return this.index; - return this; + }, - }, + setIndex: function ( index ) { - rotateZ: function ( angle ) { + if ( Array.isArray( index ) ) { - // rotate geometry around world z-axis + this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); - _m1$2.makeRotationZ( angle ); + } else { - this.applyMatrix( _m1$2 ); + this.index = index; - return this; + } - }, + }, - translate: function ( x, y, z ) { + getAttribute: function ( name ) { - // translate geometry + return this.attributes[ name ]; - _m1$2.makeTranslation( x, y, z ); + }, - this.applyMatrix( _m1$2 ); + setAttribute: function ( name, attribute ) { - return this; + this.attributes[ name ] = attribute; - }, + return this; - scale: function ( x, y, z ) { + }, - // scale geometry + deleteAttribute: function ( name ) { - _m1$2.makeScale( x, y, z ); + delete this.attributes[ name ]; - this.applyMatrix( _m1$2 ); + return this; - return this; + }, - }, + addGroup: function ( start, count, materialIndex ) { - lookAt: function ( vector ) { + this.groups.push( { - _obj.lookAt( vector ); + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - _obj.updateMatrix(); + } ); - this.applyMatrix( _obj.matrix ); + }, - return this; + clearGroups: function () { - }, + this.groups = []; - center: function () { + }, - this.computeBoundingBox(); + setDrawRange: function ( start, count ) { - this.boundingBox.getCenter( _offset ).negate(); + this.drawRange.start = start; + this.drawRange.count = count; - this.translate( _offset.x, _offset.y, _offset.z ); + }, - return this; + applyMatrix4: function ( matrix ) { - }, + var position = this.attributes.position; - setFromObject: function ( object ) { + if ( position !== undefined ) { - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + position.applyMatrix4( matrix ); - var geometry = object.geometry; + position.needsUpdate = true; - if ( object.isPoints || object.isLine ) { + } - var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 ); - var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 ); + var normal = this.attributes.normal; - this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + if ( normal !== undefined ) { - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 ); + normal.applyNormalMatrix( normalMatrix ); - this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + normal.needsUpdate = true; - } + } - if ( geometry.boundingSphere !== null ) { + var tangent = this.attributes.tangent; - this.boundingSphere = geometry.boundingSphere.clone(); + if ( tangent !== undefined ) { - } + tangent.transformDirection( matrix ); - if ( geometry.boundingBox !== null ) { + tangent.needsUpdate = true; - this.boundingBox = geometry.boundingBox.clone(); + } - } + if ( this.boundingBox !== null ) { - } else if ( object.isMesh ) { + this.computeBoundingBox(); - if ( geometry && geometry.isGeometry ) { + } - this.fromGeometry( geometry ); + if ( this.boundingSphere !== null ) { - } + this.computeBoundingSphere(); - } + } - return this; + return this; - }, + }, - setFromPoints: function ( points ) { + rotateX: function ( angle ) { - var position = []; + // rotate geometry around world x-axis - for ( var i = 0, l = points.length; i < l; i ++ ) { + _m1$2.makeRotationX( angle ); - var point = points[ i ]; - position.push( point.x, point.y, point.z || 0 ); + this.applyMatrix4( _m1$2 ); - } + return this; - this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + }, - return this; + rotateY: function ( angle ) { - }, + // rotate geometry around world y-axis - updateFromObject: function ( object ) { + _m1$2.makeRotationY( angle ); - var geometry = object.geometry; + this.applyMatrix4( _m1$2 ); - if ( object.isMesh ) { + return this; - var direct = geometry.__directGeometry; + }, - if ( geometry.elementsNeedUpdate === true ) { + rotateZ: function ( angle ) { - direct = undefined; - geometry.elementsNeedUpdate = false; + // rotate geometry around world z-axis - } + _m1$2.makeRotationZ( angle ); - if ( direct === undefined ) { + this.applyMatrix4( _m1$2 ); - return this.fromGeometry( geometry ); + return this; - } + }, - direct.verticesNeedUpdate = geometry.verticesNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate; + translate: function ( x, y, z ) { - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + // translate geometry - geometry = direct; + _m1$2.makeTranslation( x, y, z ); - } + this.applyMatrix4( _m1$2 ); - var attribute; + return this; - if ( geometry.verticesNeedUpdate === true ) { + }, - attribute = this.attributes.position; + scale: function ( x, y, z ) { - if ( attribute !== undefined ) { + // scale geometry - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + _m1$2.makeScale( x, y, z ); - } + this.applyMatrix4( _m1$2 ); - geometry.verticesNeedUpdate = false; + return this; - } + }, - if ( geometry.normalsNeedUpdate === true ) { + lookAt: function ( vector ) { - attribute = this.attributes.normal; + _obj.lookAt( vector ); - if ( attribute !== undefined ) { + _obj.updateMatrix(); - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + this.applyMatrix4( _obj.matrix ); - } + return this; - geometry.normalsNeedUpdate = false; + }, - } + center: function () { - if ( geometry.colorsNeedUpdate === true ) { + this.computeBoundingBox(); - attribute = this.attributes.color; + this.boundingBox.getCenter( _offset ).negate(); - if ( attribute !== undefined ) { + this.translate( _offset.x, _offset.y, _offset.z ); - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + return this; - } + }, - geometry.colorsNeedUpdate = false; + setFromObject: function ( object ) { - } + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - if ( geometry.uvsNeedUpdate ) { + var geometry = object.geometry; - attribute = this.attributes.uv; + if ( object.isPoints || object.isLine ) { - if ( attribute !== undefined ) { + var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 ); - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - } + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - geometry.uvsNeedUpdate = false; + var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 ); - } + this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - if ( geometry.lineDistancesNeedUpdate ) { + } - attribute = this.attributes.lineDistance; + if ( geometry.boundingSphere !== null ) { - if ( attribute !== undefined ) { + this.boundingSphere = geometry.boundingSphere.clone(); - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + } - } + if ( geometry.boundingBox !== null ) { - geometry.lineDistancesNeedUpdate = false; + this.boundingBox = geometry.boundingBox.clone(); } - if ( geometry.groupsNeedUpdate ) { + } else if ( object.isMesh ) { - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + if ( geometry && geometry.isGeometry ) { - geometry.groupsNeedUpdate = false; + this.fromGeometry( geometry ); } - return this; + } - }, + return this; - fromGeometry: function ( geometry ) { + }, - geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); + setFromPoints: function ( points ) { - return this.fromDirectGeometry( geometry.__directGeometry ); + var position = []; - }, + for ( var i = 0, l = points.length; i < l; i ++ ) { - fromDirectGeometry: function ( geometry ) { + var point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); + + } - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); - if ( geometry.normals.length > 0 ) { + return this; - var normals = new Float32Array( geometry.normals.length * 3 ); - this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + }, - } + updateFromObject: function ( object ) { - if ( geometry.colors.length > 0 ) { + var geometry = object.geometry; - var colors = new Float32Array( geometry.colors.length * 3 ); - this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + if ( object.isMesh ) { - } + var direct = geometry.__directGeometry; - if ( geometry.uvs.length > 0 ) { + if ( geometry.elementsNeedUpdate === true ) { - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + direct = undefined; + geometry.elementsNeedUpdate = false; } - if ( geometry.uvs2.length > 0 ) { + if ( direct === undefined ) { - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + return this.fromGeometry( geometry ); } - // groups - - this.groups = geometry.groups; - - // morphs + direct.verticesNeedUpdate = geometry.verticesNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate; - for ( var name in geometry.morphTargets ) { + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + geometry = direct; - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + } - var morphTarget = morphTargets[ i ]; + var attribute; - var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 ); - attribute.name = morphTarget.name; + if ( geometry.verticesNeedUpdate === true ) { - array.push( attribute.copyVector3sArray( morphTarget.data ) ); + attribute = this.attributes.position; - } + if ( attribute !== undefined ) { - this.morphAttributes[ name ] = array; + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; } - // skinning + geometry.verticesNeedUpdate = false; - if ( geometry.skinIndices.length > 0 ) { + } - var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 ); - this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + if ( geometry.normalsNeedUpdate === true ) { - } + attribute = this.attributes.normal; - if ( geometry.skinWeights.length > 0 ) { + if ( attribute !== undefined ) { - var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 ); - this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; } - // + geometry.normalsNeedUpdate = false; - if ( geometry.boundingSphere !== null ) { + } - this.boundingSphere = geometry.boundingSphere.clone(); + if ( geometry.colorsNeedUpdate === true ) { - } + attribute = this.attributes.color; - if ( geometry.boundingBox !== null ) { + if ( attribute !== undefined ) { - this.boundingBox = geometry.boundingBox.clone(); + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; } - return this; + geometry.colorsNeedUpdate = false; - }, + } - computeBoundingBox: function () { + if ( geometry.uvsNeedUpdate ) { - if ( this.boundingBox === null ) { + attribute = this.attributes.uv; - this.boundingBox = new Box3(); + if ( attribute !== undefined ) { - } + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; - var position = this.attributes.position; - var morphAttributesPosition = this.morphAttributes.position; + } - if ( position !== undefined ) { + geometry.uvsNeedUpdate = false; - this.boundingBox.setFromBufferAttribute( position ); + } - // process morph attributes if present + if ( geometry.lineDistancesNeedUpdate ) { - if ( morphAttributesPosition ) { + attribute = this.attributes.lineDistance; - for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + if ( attribute !== undefined ) { - var morphAttribute = morphAttributesPosition[ i ]; - _box$2.setFromBufferAttribute( morphAttribute ); + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; - if ( this.morphTargetsRelative ) { + } - _vector$4.addVectors( this.boundingBox.min, _box$2.min ); - this.boundingBox.expandByPoint( _vector$4 ); + geometry.lineDistancesNeedUpdate = false; - _vector$4.addVectors( this.boundingBox.max, _box$2.max ); - this.boundingBox.expandByPoint( _vector$4 ); + } - } else { + if ( geometry.groupsNeedUpdate ) { - this.boundingBox.expandByPoint( _box$2.min ); - this.boundingBox.expandByPoint( _box$2.max ); + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - } + geometry.groupsNeedUpdate = false; - } + } - } + return this; - } else { + }, - this.boundingBox.makeEmpty(); + fromGeometry: function ( geometry ) { - } + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { + return this.fromDirectGeometry( geometry.__directGeometry ); - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); + }, - } + fromDirectGeometry: function ( geometry ) { - }, + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - computeBoundingSphere: function () { + if ( geometry.normals.length > 0 ) { - if ( this.boundingSphere === null ) { + var normals = new Float32Array( geometry.normals.length * 3 ); + this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); - this.boundingSphere = new Sphere(); + } - } + if ( geometry.colors.length > 0 ) { - var position = this.attributes.position; - var morphAttributesPosition = this.morphAttributes.position; + var colors = new Float32Array( geometry.colors.length * 3 ); + this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - if ( position ) { + } - // first, find the center of the bounding sphere + if ( geometry.uvs.length > 0 ) { - var center = this.boundingSphere.center; + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - _box$2.setFromBufferAttribute( position ); + } - // process morph attributes if present + if ( geometry.uvs2.length > 0 ) { - if ( morphAttributesPosition ) { + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + } - var morphAttribute = morphAttributesPosition[ i ]; - _boxMorphTargets.setFromBufferAttribute( morphAttribute ); + // groups - if ( this.morphTargetsRelative ) { + this.groups = geometry.groups; - _vector$4.addVectors( _box$2.min, _boxMorphTargets.min ); - _box$2.expandByPoint( _vector$4 ); + // morphs - _vector$4.addVectors( _box$2.max, _boxMorphTargets.max ); - _box$2.expandByPoint( _vector$4 ); + for ( var name in geometry.morphTargets ) { - } else { + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - _box$2.expandByPoint( _boxMorphTargets.min ); - _box$2.expandByPoint( _boxMorphTargets.max ); + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - } + var morphTarget = morphTargets[ i ]; - } + var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 ); + attribute.name = morphTarget.name; - } + array.push( attribute.copyVector3sArray( morphTarget.data ) ); - _box$2.getCenter( center ); + } - // second, try to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + this.morphAttributes[ name ] = array; - var maxRadiusSq = 0; + } - for ( var i = 0, il = position.count; i < il; i ++ ) { + // skinning - _vector$4.fromBufferAttribute( position, i ); + if ( geometry.skinIndices.length > 0 ) { - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 ); + this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - } + } - // process morph attributes if present + if ( geometry.skinWeights.length > 0 ) { - if ( morphAttributesPosition ) { + var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 ); + this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { + } - var morphAttribute = morphAttributesPosition[ i ]; - var morphTargetsRelative = this.morphTargetsRelative; + // - for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) { + if ( geometry.boundingSphere !== null ) { - _vector$4.fromBufferAttribute( morphAttribute, j ); + this.boundingSphere = geometry.boundingSphere.clone(); - if ( morphTargetsRelative ) { + } - _offset.fromBufferAttribute( position, j ); - _vector$4.add( _offset ); + if ( geometry.boundingBox !== null ) { - } + this.boundingBox = geometry.boundingBox.clone(); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); + } - } + return this; - } + }, - } + computeBoundingBox: function () { - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + if ( this.boundingBox === null ) { - if ( isNaN( this.boundingSphere.radius ) ) { + this.boundingBox = new Box3(); - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + } - } + var position = this.attributes.position; + var morphAttributesPosition = this.morphAttributes.position; - } + if ( position !== undefined ) { - }, + this.boundingBox.setFromBufferAttribute( position ); - computeFaceNormals: function () { + // process morph attributes if present - // backwards compatibility + if ( morphAttributesPosition ) { - }, + for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { - computeVertexNormals: function () { + var morphAttribute = morphAttributesPosition[ i ]; + _box$2.setFromBufferAttribute( morphAttribute ); - var index = this.index; - var attributes = this.attributes; + if ( this.morphTargetsRelative ) { - if ( attributes.position ) { + _vector$4.addVectors( this.boundingBox.min, _box$2.min ); + this.boundingBox.expandByPoint( _vector$4 ); - var positions = attributes.position.array; + _vector$4.addVectors( this.boundingBox.max, _box$2.max ); + this.boundingBox.expandByPoint( _vector$4 ); - if ( attributes.normal === undefined ) { + } else { - this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); + this.boundingBox.expandByPoint( _box$2.min ); + this.boundingBox.expandByPoint( _box$2.max ); - } else { + } - // reset existing normals to zero + } - var array = attributes.normal.array; + } - for ( var i = 0, il = array.length; i < il; i ++ ) { + } else { - array[ i ] = 0; + this.boundingBox.makeEmpty(); - } + } - } + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - var normals = attributes.normal.array; + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - var vA, vB, vC; - var pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); - var cb = new Vector3(), ab = new Vector3(); + } - // indexed elements + }, - if ( index ) { + computeBoundingSphere: function () { - var indices = index.array; + if ( this.boundingSphere === null ) { - for ( var i = 0, il = index.count; i < il; i += 3 ) { + this.boundingSphere = new Sphere(); - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + } - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + var position = this.attributes.position; + var morphAttributesPosition = this.morphAttributes.position; - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + if ( position ) { - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + // first, find the center of the bounding sphere - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + var center = this.boundingSphere.center; - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + _box$2.setFromBufferAttribute( position ); - } + // process morph attributes if present - } else { + if ( morphAttributesPosition ) { - // non-indexed elements (unconnected triangle soup) + for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + var morphAttribute = morphAttributesPosition[ i ]; + _boxMorphTargets.setFromBufferAttribute( morphAttribute ); - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + if ( this.morphTargetsRelative ) { - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + _vector$4.addVectors( _box$2.min, _boxMorphTargets.min ); + _box$2.expandByPoint( _vector$4 ); - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + _vector$4.addVectors( _box$2.max, _boxMorphTargets.max ); + _box$2.expandByPoint( _vector$4 ); - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + } else { - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + _box$2.expandByPoint( _boxMorphTargets.min ); + _box$2.expandByPoint( _boxMorphTargets.max ); } } - this.normalizeNormals(); + } - attributes.normal.needsUpdate = true; + _box$2.getCenter( center ); - } + // second, try to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - }, + var maxRadiusSq = 0; - merge: function ( geometry, offset ) { + for ( var i = 0, il = position.count; i < il; i ++ ) { - if ( ! ( geometry && geometry.isBufferGeometry ) ) { + _vector$4.fromBufferAttribute( position, i ); - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); } - if ( offset === undefined ) { - - offset = 0; + // process morph attributes if present - console.warn( - 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' - + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' - ); + if ( morphAttributesPosition ) { - } + for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { - var attributes = this.attributes; + var morphAttribute = morphAttributesPosition[ i ]; + var morphTargetsRelative = this.morphTargetsRelative; - for ( var key in attributes ) { + for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) { - if ( geometry.attributes[ key ] === undefined ) { continue; } + _vector$4.fromBufferAttribute( morphAttribute, j ); - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + if ( morphTargetsRelative ) { - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + _offset.fromBufferAttribute( position, j ); + _vector$4.add( _offset ); - var attributeOffset = attribute2.itemSize * offset; - var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset ); + } - for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) { + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); - attributeArray1[ j ] = attributeArray2[ i ]; + } } } - return this; + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - }, + if ( isNaN( this.boundingSphere.radius ) ) { - normalizeNormals: function () { + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); - var normals = this.attributes.normal; + } - for ( var i = 0, il = normals.count; i < il; i ++ ) { + } - _vector$4.x = normals.getX( i ); - _vector$4.y = normals.getY( i ); - _vector$4.z = normals.getZ( i ); + }, - _vector$4.normalize(); + computeFaceNormals: function () { - normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); + // backwards compatibility - } + }, - }, + computeVertexNormals: function () { - toNonIndexed: function () { + var index = this.index; + var attributes = this.attributes; - function convertBufferAttribute( attribute, indices ) { + if ( attributes.position ) { - var array = attribute.array; - var itemSize = attribute.itemSize; + var positions = attributes.position.array; - var array2 = new array.constructor( indices.length * itemSize ); + if ( attributes.normal === undefined ) { - var index = 0, index2 = 0; + this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - for ( var i = 0, l = indices.length; i < l; i ++ ) { + } else { - index = indices[ i ] * itemSize; + // reset existing normals to zero - for ( var j = 0; j < itemSize; j ++ ) { + var array = attributes.normal.array; - array2[ index2 ++ ] = array[ index ++ ]; + for ( var i = 0, il = array.length; i < il; i ++ ) { - } + array[ i ] = 0; } - return new BufferAttribute( array2, itemSize ); - } - // + var normals = attributes.normal.array; - if ( this.index === null ) { + var vA, vB, vC; + var pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + var cb = new Vector3(), ab = new Vector3(); - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + // indexed elements - } + if ( index ) { - var geometry2 = new BufferGeometry(); + var indices = index.array; - var indices = this.index.array; - var attributes = this.attributes; + for ( var i = 0, il = index.count; i < il; i += 3 ) { - // attributes + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - for ( var name in attributes ) { + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - var attribute = attributes[ name ]; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - var newAttribute = convertBufferAttribute( attribute, indices ); + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - geometry2.setAttribute( name, newAttribute ); + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - } + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - // morph attributes + } - var morphAttributes = this.morphAttributes; + } else { - for ( name in morphAttributes ) { + // non-indexed elements (unconnected triangle soup) - var morphArray = []; - var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) { + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - var attribute = morphAttribute[ i ]; + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - var newAttribute = convertBufferAttribute( attribute, indices ); + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - morphArray.push( newAttribute ); + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - } + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - geometry2.morphAttributes[ name ] = morphArray; + } } - geometry2.morphTargetsRelative = this.morphTargetsRelative; - - // groups - - var groups = this.groups; - - for ( var i = 0, l = groups.length; i < l; i ++ ) { + this.normalizeNormals(); - var group = groups[ i ]; - geometry2.addGroup( group.start, group.count, group.materialIndex ); + attributes.normal.needsUpdate = true; - } + } - return geometry2; + }, - }, + merge: function ( geometry, offset ) { - toJSON: function () { + if ( ! ( geometry && geometry.isBufferGeometry ) ) { - var data = { - metadata: { - version: 4.5, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - // standard BufferGeometry serialization + } - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) { data.name = this.name; } - if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; } + if ( offset === undefined ) { - if ( this.parameters !== undefined ) { + offset = 0; - var parameters = this.parameters; + console.warn( + 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' + ); - for ( var key in parameters ) { + } - if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; } + var attributes = this.attributes; - } + for ( var key in attributes ) { - return data; + if ( geometry.attributes[ key ] === undefined ) continue; - } + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - data.data = { attributes: {} }; + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - var index = this.index; + var attributeOffset = attribute2.itemSize * offset; + var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset ); - if ( index !== null ) { + for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) { - data.data.index = { - type: index.array.constructor.name, - array: Array.prototype.slice.call( index.array ) - }; + attributeArray1[ j ] = attributeArray2[ i ]; } - var attributes = this.attributes; + } - for ( var key in attributes ) { + return this; - var attribute = attributes[ key ]; + }, - var attributeData = attribute.toJSON(); + normalizeNormals: function () { - if ( attribute.name !== '' ) { attributeData.name = attribute.name; } + var normals = this.attributes.normal; - data.data.attributes[ key ] = attributeData; + for ( var i = 0, il = normals.count; i < il; i ++ ) { - } + _vector$4.x = normals.getX( i ); + _vector$4.y = normals.getY( i ); + _vector$4.z = normals.getZ( i ); - var morphAttributes = {}; - var hasMorphAttributes = false; + _vector$4.normalize(); - for ( var key in this.morphAttributes ) { + normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); - var attributeArray = this.morphAttributes[ key ]; + } - var array = []; + }, - for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { + toNonIndexed: function () { - var attribute = attributeArray[ i ]; + function convertBufferAttribute( attribute, indices ) { - var attributeData = attribute.toJSON(); + var array = attribute.array; + var itemSize = attribute.itemSize; + var normalized = attribute.normalized; - if ( attribute.name !== '' ) { attributeData.name = attribute.name; } + var array2 = new array.constructor( indices.length * itemSize ); - array.push( attributeData ); + var index = 0, index2 = 0; - } + for ( var i = 0, l = indices.length; i < l; i ++ ) { - if ( array.length > 0 ) { + index = indices[ i ] * itemSize; - morphAttributes[ key ] = array; + for ( var j = 0; j < itemSize; j ++ ) { - hasMorphAttributes = true; + array2[ index2 ++ ] = array[ index ++ ]; } } - if ( hasMorphAttributes ) { + return new BufferAttribute( array2, itemSize, normalized ); - data.data.morphAttributes = morphAttributes; - data.data.morphTargetsRelative = this.morphTargetsRelative; + } - } + // - var groups = this.groups; + if ( this.index === null ) { - if ( groups.length > 0 ) { + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + } - } + var geometry2 = new BufferGeometry(); - var boundingSphere = this.boundingSphere; + var indices = this.index.array; + var attributes = this.attributes; - if ( boundingSphere !== null ) { + // attributes - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + for ( var name in attributes ) { - } + var attribute = attributes[ name ]; - return data; + var newAttribute = convertBufferAttribute( attribute, indices ); - }, + geometry2.setAttribute( name, newAttribute ); - clone: function () { + } - /* - // Handle primitives + // morph attributes - var parameters = this.parameters; + var morphAttributes = this.morphAttributes; - if ( parameters !== undefined ) { + for ( name in morphAttributes ) { - var values = []; + var morphArray = []; + var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes - for ( var key in parameters ) { + for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) { - values.push( parameters[ key ] ); + var attribute = morphAttribute[ i ]; - } + var newAttribute = convertBufferAttribute( attribute, indices ); - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + morphArray.push( newAttribute ); - } + } - return new this.constructor().copy( this ); - */ + geometry2.morphAttributes[ name ] = morphArray; - return new BufferGeometry().copy( this ); + } - }, + geometry2.morphTargetsRelative = this.morphTargetsRelative; - copy: function ( source ) { + // groups - var name, i, l; + var groups = this.groups; - // reset + for ( var i = 0, l = groups.length; i < l; i ++ ) { - this.index = null; - this.attributes = {}; - this.morphAttributes = {}; - this.groups = []; - this.boundingBox = null; - this.boundingSphere = null; + var group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); - // name + } - this.name = source.name; + return geometry2; - // index + }, - var index = source.index; + toJSON: function () { - if ( index !== null ) { + var data = { + metadata: { + version: 4.5, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - this.setIndex( index.clone() ); + // standard BufferGeometry serialization - } + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; + if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData; - // attributes + if ( this.parameters !== undefined ) { - var attributes = source.attributes; + var parameters = this.parameters; - for ( name in attributes ) { + for ( var key in parameters ) { - var attribute = attributes[ name ]; - this.setAttribute( name, attribute.clone() ); + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; } - // morph attributes - - var morphAttributes = source.morphAttributes; + return data; - for ( name in morphAttributes ) { + } - var array = []; - var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + data.data = { attributes: {} }; - for ( i = 0, l = morphAttribute.length; i < l; i ++ ) { + var index = this.index; - array.push( morphAttribute[ i ].clone() ); + if ( index !== null ) { - } + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call( index.array ) + }; - this.morphAttributes[ name ] = array; + } - } + var attributes = this.attributes; - this.morphTargetsRelative = source.morphTargetsRelative; + for ( var key in attributes ) { - // groups + var attribute = attributes[ key ]; - var groups = source.groups; + var attributeData = attribute.toJSON(); - for ( i = 0, l = groups.length; i < l; i ++ ) { + if ( attribute.name !== '' ) attributeData.name = attribute.name; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + data.data.attributes[ key ] = attributeData; - } + } - // bounding box + var morphAttributes = {}; + var hasMorphAttributes = false; - var boundingBox = source.boundingBox; + for ( var key in this.morphAttributes ) { - if ( boundingBox !== null ) { + var attributeArray = this.morphAttributes[ key ]; - this.boundingBox = boundingBox.clone(); + var array = []; - } + for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { - // bounding sphere + var attribute = attributeArray[ i ]; - var boundingSphere = source.boundingSphere; + var attributeData = attribute.toJSON(); - if ( boundingSphere !== null ) { + if ( attribute.name !== '' ) attributeData.name = attribute.name; - this.boundingSphere = boundingSphere.clone(); + array.push( attributeData ); } - // draw range - - this.drawRange.start = source.drawRange.start; - this.drawRange.count = source.drawRange.count; + if ( array.length > 0 ) { - // user data + morphAttributes[ key ] = array; - this.userData = source.userData; + hasMorphAttributes = true; - return this; + } - }, + } - dispose: function () { + if ( hasMorphAttributes ) { - this.dispatchEvent( { type: 'dispose' } ); + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; } - } ); + var groups = this.groups; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ - */ + if ( groups.length > 0 ) { - var _inverseMatrix = new Matrix4(); - var _ray = new Ray(); - var _sphere = new Sphere(); + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - var _vA = new Vector3(); - var _vB = new Vector3(); - var _vC = new Vector3(); + } - var _tempA = new Vector3(); - var _tempB = new Vector3(); - var _tempC = new Vector3(); + var boundingSphere = this.boundingSphere; - var _morphA = new Vector3(); - var _morphB = new Vector3(); - var _morphC = new Vector3(); + if ( boundingSphere !== null ) { - var _uvA = new Vector2(); - var _uvB = new Vector2(); - var _uvC = new Vector2(); + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; - var _intersectionPoint = new Vector3(); - var _intersectionPointWorld = new Vector3(); + } - function Mesh( geometry, material ) { + return data; - Object3D.call( this ); + }, - this.type = 'Mesh'; + clone: function () { - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + /* + // Handle primitives - this.drawMode = TrianglesDrawMode; + var parameters = this.parameters; - this.updateMorphTargets(); + if ( parameters !== undefined ) { - } + var values = []; - Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + for ( var key in parameters ) { - constructor: Mesh, + values.push( parameters[ key ] ); - isMesh: true, + } - setDrawMode: function ( value ) { + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - this.drawMode = value; + } - }, + return new this.constructor().copy( this ); + */ - copy: function ( source ) { + return new BufferGeometry().copy( this ); - Object3D.prototype.copy.call( this, source ); + }, - this.drawMode = source.drawMode; + copy: function ( source ) { - if ( source.morphTargetInfluences !== undefined ) { + var name, i, l; - this.morphTargetInfluences = source.morphTargetInfluences.slice(); + // reset - } + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; - if ( source.morphTargetDictionary !== undefined ) { + // name - this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); + this.name = source.name; - } + // index - return this; + var index = source.index; - }, + if ( index !== null ) { - updateMorphTargets: function () { + this.setIndex( index.clone() ); - var geometry = this.geometry; - var m, ml, name; + } - if ( geometry.isBufferGeometry ) { + // attributes - var morphAttributes = geometry.morphAttributes; - var keys = Object.keys( morphAttributes ); + var attributes = source.attributes; - if ( keys.length > 0 ) { + for ( name in attributes ) { - var morphAttribute = morphAttributes[ keys[ 0 ] ]; + var attribute = attributes[ name ]; + this.setAttribute( name, attribute.clone() ); - if ( morphAttribute !== undefined ) { + } - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + // morph attributes - for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + var morphAttributes = source.morphAttributes; - name = morphAttribute[ m ].name || String( m ); + for ( name in morphAttributes ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + var array = []; + var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes - } + for ( i = 0, l = morphAttribute.length; i < l; i ++ ) { - } + array.push( morphAttribute[ i ].clone() ); - } + } - } else { + this.morphAttributes[ name ] = array; - var morphTargets = geometry.morphTargets; + } - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + this.morphTargetsRelative = source.morphTargetsRelative; - console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + // groups - } + var groups = source.groups; - } + for ( i = 0, l = groups.length; i < l; i ++ ) { - }, + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); - raycast: function ( raycaster, intersects ) { + } - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + // bounding box - if ( material === undefined ) { return; } + var boundingBox = source.boundingBox; - // Checking boundingSphere distance to ray + if ( boundingBox !== null ) { - if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } + this.boundingBox = boundingBox.clone(); - _sphere.copy( geometry.boundingSphere ); - _sphere.applyMatrix4( matrixWorld ); + } - if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; } + // bounding sphere - // + var boundingSphere = source.boundingSphere; - _inverseMatrix.getInverse( matrixWorld ); - _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); + if ( boundingSphere !== null ) { - // Check boundingBox before continuing + this.boundingSphere = boundingSphere.clone(); - if ( geometry.boundingBox !== null ) { + } - if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; } + // draw range - } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; - // check unsupported draw modes + // user data - if ( this.drawMode !== TrianglesDrawMode ) { + this.userData = source.userData; - console.warn( 'THREE.Mesh: TriangleStripDrawMode and TriangleFanDrawMode are not supported by .raycast().' ); - return; + return this; - } + }, - var intersection; + dispose: function () { - if ( geometry.isBufferGeometry ) { + this.dispatchEvent( { type: 'dispose' } ); - var a, b, c; - var index = geometry.index; - var position = geometry.attributes.position; - var morphPosition = geometry.morphAttributes.position; - var morphTargetsRelative = geometry.morphTargetsRelative; - var uv = geometry.attributes.uv; - var uv2 = geometry.attributes.uv2; - var groups = geometry.groups; - var drawRange = geometry.drawRange; - var i, j, il, jl; - var group, groupMaterial; - var start, end; + } - if ( index !== null ) { +} ); - // indexed buffer geometry +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - if ( Array.isArray( material ) ) { +var _inverseMatrix = new Matrix4(); +var _ray = new Ray(); +var _sphere = new Sphere(); - for ( i = 0, il = groups.length; i < il; i ++ ) { +var _vA = new Vector3(); +var _vB = new Vector3(); +var _vC = new Vector3(); - group = groups[ i ]; - groupMaterial = material[ group.materialIndex ]; +var _tempA = new Vector3(); +var _tempB = new Vector3(); +var _tempC = new Vector3(); - start = Math.max( group.start, drawRange.start ); - end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); +var _morphA = new Vector3(); +var _morphB = new Vector3(); +var _morphC = new Vector3(); - for ( j = start, jl = end; j < jl; j += 3 ) { +var _uvA = new Vector2(); +var _uvB = new Vector2(); +var _uvC = new Vector2(); - a = index.getX( j ); - b = index.getX( j + 1 ); - c = index.getX( j + 2 ); +var _intersectionPoint = new Vector3(); +var _intersectionPointWorld = new Vector3(); - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); +function Mesh( geometry, material ) { - if ( intersection ) { + Object3D.call( this ); - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + this.type = 'Mesh'; - } + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial(); - } + this.updateMorphTargets(); - } +} - } else { +Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - start = Math.max( 0, drawRange.start ); - end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + constructor: Mesh, - for ( i = start, il = end; i < il; i += 3 ) { + isMesh: true, - a = index.getX( i ); - b = index.getX( i + 1 ); - c = index.getX( i + 2 ); + copy: function ( source ) { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + Object3D.prototype.copy.call( this, source ); - if ( intersection ) { + if ( source.morphTargetInfluences !== undefined ) { - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics - intersects.push( intersection ); + this.morphTargetInfluences = source.morphTargetInfluences.slice(); - } + } - } + if ( source.morphTargetDictionary !== undefined ) { - } + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); - } else if ( position !== undefined ) { + } - // non-indexed buffer geometry + return this; - if ( Array.isArray( material ) ) { + }, - for ( i = 0, il = groups.length; i < il; i ++ ) { + updateMorphTargets: function () { - group = groups[ i ]; - groupMaterial = material[ group.materialIndex ]; + var geometry = this.geometry; + var m, ml, name; - start = Math.max( group.start, drawRange.start ); - end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + if ( geometry.isBufferGeometry ) { - for ( j = start, jl = end; j < jl; j += 3 ) { + var morphAttributes = geometry.morphAttributes; + var keys = Object.keys( morphAttributes ); - a = j; - b = j + 1; - c = j + 2; + if ( keys.length > 0 ) { - intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + var morphAttribute = morphAttributes[ keys[ 0 ] ]; - if ( intersection ) { + if ( morphAttribute !== undefined ) { - intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics - intersection.face.materialIndex = group.materialIndex; - intersects.push( intersection ); + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - } + for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - } + name = morphAttribute[ m ].name || String( m ); - } + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; - } else { + } - start = Math.max( 0, drawRange.start ); - end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); + } - for ( i = start, il = end; i < il; i += 3 ) { + } - a = i; - b = i + 1; - c = i + 2; + } else { - intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); + var morphTargets = geometry.morphTargets; - if ( intersection ) { + if ( morphTargets !== undefined && morphTargets.length > 0 ) { - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics - intersects.push( intersection ); + console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - } + } - } + } - } + }, - } + raycast: function ( raycaster, intersects ) { - } else if ( geometry.isGeometry ) { + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - var fvA, fvB, fvC; - var isMultiMaterial = Array.isArray( material ); + if ( material === undefined ) return; - var vertices = geometry.vertices; - var faces = geometry.faces; - var uvs; + // Checking boundingSphere distance to ray - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; } + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + _sphere.copy( geometry.boundingSphere ); + _sphere.applyMatrix4( matrixWorld ); - var face = faces[ f ]; - var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material; + if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return; - if ( faceMaterial === undefined ) { continue; } + // - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + _inverseMatrix.getInverse( matrixWorld ); + _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); - intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint ); + // Check boundingBox before continuing - if ( intersection ) { + if ( geometry.boundingBox !== null ) { - if ( uvs && uvs[ f ] ) { + if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return; - var uvs_f = uvs[ f ]; - _uvA.copy( uvs_f[ 0 ] ); - _uvB.copy( uvs_f[ 1 ] ); - _uvC.copy( uvs_f[ 2 ] ); + } - intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() ); + var intersection; - } + if ( geometry.isBufferGeometry ) { - intersection.face = face; - intersection.faceIndex = f; - intersects.push( intersection ); + var a, b, c; + var index = geometry.index; + var position = geometry.attributes.position; + var morphPosition = geometry.morphAttributes.position; + var morphTargetsRelative = geometry.morphTargetsRelative; + var uv = geometry.attributes.uv; + var uv2 = geometry.attributes.uv2; + var groups = geometry.groups; + var drawRange = geometry.drawRange; + var i, j, il, jl; + var group, groupMaterial; + var start, end; - } + if ( index !== null ) { - } + // indexed buffer geometry - } + if ( Array.isArray( material ) ) { - }, + for ( i = 0, il = groups.length; i < il; i ++ ) { - clone: function () { + group = groups[ i ]; + groupMaterial = material[ group.materialIndex ]; - return new this.constructor( this.geometry, this.material ).copy( this ); + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); - } + for ( j = start, jl = end; j < jl; j += 3 ) { - } ); + a = index.getX( j ); + b = index.getX( j + 1 ); + c = index.getX( j + 2 ); - function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - var intersect; + if ( intersection ) { - if ( material.side === BackSide ) { + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + } - } else { + } - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); + } - } + } else { - if ( intersect === null ) { return null; } + start = Math.max( 0, drawRange.start ); + end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); - _intersectionPointWorld.copy( point ); - _intersectionPointWorld.applyMatrix4( object.matrixWorld ); + for ( i = start, il = end; i < il; i += 3 ) { - var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); + a = index.getX( i ); + b = index.getX( i + 1 ); + c = index.getX( i + 2 ); - if ( distance < raycaster.near || distance > raycaster.far ) { return null; } + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - return { - distance: distance, - point: _intersectionPointWorld.clone(), - object: object - }; + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics + intersects.push( intersection ); + + } - function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) { + } - _vA.fromBufferAttribute( position, a ); - _vB.fromBufferAttribute( position, b ); - _vC.fromBufferAttribute( position, c ); + } - var morphInfluences = object.morphTargetInfluences; + } else if ( position !== undefined ) { - if ( material.morphTargets && morphPosition && morphInfluences ) { + // non-indexed buffer geometry - _morphA.set( 0, 0, 0 ); - _morphB.set( 0, 0, 0 ); - _morphC.set( 0, 0, 0 ); + if ( Array.isArray( material ) ) { - for ( var i = 0, il = morphPosition.length; i < il; i ++ ) { + for ( i = 0, il = groups.length; i < il; i ++ ) { - var influence = morphInfluences[ i ]; - var morphAttribute = morphPosition[ i ]; + group = groups[ i ]; + groupMaterial = material[ group.materialIndex ]; - if ( influence === 0 ) { continue; } + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); - _tempA.fromBufferAttribute( morphAttribute, a ); - _tempB.fromBufferAttribute( morphAttribute, b ); - _tempC.fromBufferAttribute( morphAttribute, c ); + for ( j = start, jl = end; j < jl; j += 3 ) { - if ( morphTargetsRelative ) { + a = j; + b = j + 1; + c = j + 2; - _morphA.addScaledVector( _tempA, influence ); - _morphB.addScaledVector( _tempB, influence ); - _morphC.addScaledVector( _tempC, influence ); + intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - } else { + if ( intersection ) { - _morphA.addScaledVector( _tempA.sub( _vA ), influence ); - _morphB.addScaledVector( _tempB.sub( _vB ), influence ); - _morphC.addScaledVector( _tempC.sub( _vC ), influence ); + intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics + intersection.face.materialIndex = group.materialIndex; + intersects.push( intersection ); - } + } - } + } - _vA.add( _morphA ); - _vB.add( _morphB ); - _vC.add( _morphC ); + } - } + } else { - var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); + start = Math.max( 0, drawRange.start ); + end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); - if ( intersection ) { + for ( i = start, il = end; i < il; i += 3 ) { - if ( uv ) { + a = i; + b = i + 1; + c = i + 2; - _uvA.fromBufferAttribute( uv, a ); - _uvB.fromBufferAttribute( uv, b ); - _uvC.fromBufferAttribute( uv, c ); + intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); - intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + if ( intersection ) { - } + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics + intersects.push( intersection ); - if ( uv2 ) { + } - _uvA.fromBufferAttribute( uv2, a ); - _uvB.fromBufferAttribute( uv2, b ); - _uvC.fromBufferAttribute( uv2, c ); + } - intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); + } } - var face = new Face3( a, b, c ); - Triangle.getNormal( _vA, _vB, _vC, face.normal ); + } else if ( geometry.isGeometry ) { - intersection.face = face; + var fvA, fvB, fvC; + var isMultiMaterial = Array.isArray( material ); - } + var vertices = geometry.vertices; + var faces = geometry.faces; + var uvs; - return intersection; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - } + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author bhouston / http://clara.io - */ + var face = faces[ f ]; + var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material; - var _geometryId = 0; // Geometry uses even numbers as Id - var _m1$3 = new Matrix4(); - var _obj$1 = new Object3D(); - var _offset$1 = new Vector3(); + if ( faceMaterial === undefined ) continue; - function Geometry() { + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - Object.defineProperty( this, 'id', { value: _geometryId += 2 } ); + intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint ); - this.uuid = _Math.generateUUID(); + if ( intersection ) { - this.name = ''; - this.type = 'Geometry'; + if ( uvs && uvs[ f ] ) { - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; + var uvs_f = uvs[ f ]; + _uvA.copy( uvs_f[ 0 ] ); + _uvB.copy( uvs_f[ 1 ] ); + _uvC.copy( uvs_f[ 2 ] ); - this.morphTargets = []; - this.morphNormals = []; + intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() ); - this.skinWeights = []; - this.skinIndices = []; + } - this.lineDistances = []; + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - this.boundingBox = null; - this.boundingSphere = null; + } - // update flags + } - this.elementsNeedUpdate = false; - this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; - this.groupsNeedUpdate = false; + } - } + }, - Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + clone: function () { - constructor: Geometry, + return new this.constructor( this.geometry, this.material ).copy( this ); - isGeometry: true, + } - applyMatrix: function ( matrix ) { +} ); - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); +function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + var intersect; - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + if ( material.side === BackSide ) { - } + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + } else { - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + } - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + if ( intersect === null ) return null; - } + _intersectionPointWorld.copy( point ); + _intersectionPointWorld.applyMatrix4( object.matrixWorld ); - } + var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); - if ( this.boundingBox !== null ) { + if ( distance < raycaster.near || distance > raycaster.far ) return null; - this.computeBoundingBox(); + return { + distance: distance, + point: _intersectionPointWorld.clone(), + object: object + }; - } +} - if ( this.boundingSphere !== null ) { +function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) { - this.computeBoundingSphere(); + _vA.fromBufferAttribute( position, a ); + _vB.fromBufferAttribute( position, b ); + _vC.fromBufferAttribute( position, c ); - } + var morphInfluences = object.morphTargetInfluences; - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; + if ( material.morphTargets && morphPosition && morphInfluences ) { - return this; + _morphA.set( 0, 0, 0 ); + _morphB.set( 0, 0, 0 ); + _morphC.set( 0, 0, 0 ); - }, + for ( var i = 0, il = morphPosition.length; i < il; i ++ ) { - rotateX: function ( angle ) { + var influence = morphInfluences[ i ]; + var morphAttribute = morphPosition[ i ]; - // rotate geometry around world x-axis + if ( influence === 0 ) continue; - _m1$3.makeRotationX( angle ); + _tempA.fromBufferAttribute( morphAttribute, a ); + _tempB.fromBufferAttribute( morphAttribute, b ); + _tempC.fromBufferAttribute( morphAttribute, c ); - this.applyMatrix( _m1$3 ); + if ( morphTargetsRelative ) { - return this; + _morphA.addScaledVector( _tempA, influence ); + _morphB.addScaledVector( _tempB, influence ); + _morphC.addScaledVector( _tempC, influence ); - }, + } else { - rotateY: function ( angle ) { + _morphA.addScaledVector( _tempA.sub( _vA ), influence ); + _morphB.addScaledVector( _tempB.sub( _vB ), influence ); + _morphC.addScaledVector( _tempC.sub( _vC ), influence ); - // rotate geometry around world y-axis + } - _m1$3.makeRotationY( angle ); + } - this.applyMatrix( _m1$3 ); + _vA.add( _morphA ); + _vB.add( _morphB ); + _vC.add( _morphC ); - return this; + } - }, + if ( object.isSkinnedMesh ) { - rotateZ: function ( angle ) { + object.boneTransform( a, _vA ); + object.boneTransform( b, _vB ); + object.boneTransform( c, _vC ); - // rotate geometry around world z-axis + } - _m1$3.makeRotationZ( angle ); + var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); - this.applyMatrix( _m1$3 ); + if ( intersection ) { - return this; + if ( uv ) { - }, + _uvA.fromBufferAttribute( uv, a ); + _uvB.fromBufferAttribute( uv, b ); + _uvC.fromBufferAttribute( uv, c ); - translate: function ( x, y, z ) { + intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); - // translate geometry + } - _m1$3.makeTranslation( x, y, z ); + if ( uv2 ) { - this.applyMatrix( _m1$3 ); + _uvA.fromBufferAttribute( uv2, a ); + _uvB.fromBufferAttribute( uv2, b ); + _uvC.fromBufferAttribute( uv2, c ); - return this; + intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); - }, + } - scale: function ( x, y, z ) { + var face = new Face3( a, b, c ); + Triangle.getNormal( _vA, _vB, _vC, face.normal ); - // scale geometry + intersection.face = face; - _m1$3.makeScale( x, y, z ); + } - this.applyMatrix( _m1$3 ); + return intersection; - return this; +} - }, +/** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author bhouston / http://clara.io + */ - lookAt: function ( vector ) { +var _geometryId = 0; // Geometry uses even numbers as Id +var _m1$3 = new Matrix4(); +var _obj$1 = new Object3D(); +var _offset$1 = new Vector3(); - _obj$1.lookAt( vector ); +function Geometry() { - _obj$1.updateMatrix(); + Object.defineProperty( this, 'id', { value: _geometryId += 2 } ); - this.applyMatrix( _obj$1.matrix ); + this.uuid = MathUtils.generateUUID(); - return this; + this.name = ''; + this.type = 'Geometry'; - }, + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [[]]; - fromBufferGeometry: function ( geometry ) { + this.morphTargets = []; + this.morphNormals = []; - var scope = this; + this.skinWeights = []; + this.skinIndices = []; - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + this.lineDistances = []; - if ( attributes.position === undefined ) { + this.boundingBox = null; + this.boundingSphere = null; - console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' ); - return this; + // update flags - } + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - var positions = attributes.position.array; - var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; - var colors = attributes.color !== undefined ? attributes.color.array : undefined; - var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; - var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; +} - if ( uvs2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; } +Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - for ( var i = 0; i < positions.length; i += 3 ) { + constructor: Geometry, - scope.vertices.push( new Vector3().fromArray( positions, i ) ); + isGeometry: true, - if ( colors !== undefined ) { + applyMatrix4: function ( matrix ) { - scope.colors.push( new Color().fromArray( colors, i ) ); + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - } + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { - } + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); - function addFace( a, b, c, materialIndex ) { + } - var vertexColors = ( colors === undefined ) ? [] : [ - scope.colors[ a ].clone(), - scope.colors[ b ].clone(), - scope.colors[ c ].clone() ]; + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - var vertexNormals = ( normals === undefined ) ? [] : [ - new Vector3().fromArray( normals, a * 3 ), - new Vector3().fromArray( normals, b * 3 ), - new Vector3().fromArray( normals, c * 3 ) - ]; + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - scope.faces.push( face ); + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - if ( uvs !== undefined ) { + } - scope.faceVertexUvs[ 0 ].push( [ - new Vector2().fromArray( uvs, a * 2 ), - new Vector2().fromArray( uvs, b * 2 ), - new Vector2().fromArray( uvs, c * 2 ) - ] ); + } - } + if ( this.boundingBox !== null ) { - if ( uvs2 !== undefined ) { + this.computeBoundingBox(); - scope.faceVertexUvs[ 1 ].push( [ - new Vector2().fromArray( uvs2, a * 2 ), - new Vector2().fromArray( uvs2, b * 2 ), - new Vector2().fromArray( uvs2, c * 2 ) - ] ); + } - } + if ( this.boundingSphere !== null ) { - } + this.computeBoundingSphere(); - var groups = geometry.groups; + } - if ( groups.length > 0 ) { + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - for ( var i = 0; i < groups.length; i ++ ) { + return this; - var group = groups[ i ]; + }, - var start = group.start; - var count = group.count; + rotateX: function ( angle ) { - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + // rotate geometry around world x-axis - if ( indices !== undefined ) { + _m1$3.makeRotationX( angle ); - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + this.applyMatrix4( _m1$3 ); - } else { + return this; - addFace( j, j + 1, j + 2, group.materialIndex ); + }, - } + rotateY: function ( angle ) { - } + // rotate geometry around world y-axis - } + _m1$3.makeRotationY( angle ); - } else { + this.applyMatrix4( _m1$3 ); - if ( indices !== undefined ) { + return this; - for ( var i = 0; i < indices.length; i += 3 ) { + }, - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + rotateZ: function ( angle ) { - } + // rotate geometry around world z-axis - } else { + _m1$3.makeRotationZ( angle ); - for ( var i = 0; i < positions.length / 3; i += 3 ) { + this.applyMatrix4( _m1$3 ); - addFace( i, i + 1, i + 2 ); + return this; - } + }, - } + translate: function ( x, y, z ) { - } + // translate geometry - this.computeFaceNormals(); + _m1$3.makeTranslation( x, y, z ); - if ( geometry.boundingBox !== null ) { + this.applyMatrix4( _m1$3 ); - this.boundingBox = geometry.boundingBox.clone(); + return this; - } + }, - if ( geometry.boundingSphere !== null ) { + scale: function ( x, y, z ) { - this.boundingSphere = geometry.boundingSphere.clone(); + // scale geometry - } + _m1$3.makeScale( x, y, z ); - return this; + this.applyMatrix4( _m1$3 ); - }, + return this; - center: function () { + }, - this.computeBoundingBox(); + lookAt: function ( vector ) { - this.boundingBox.getCenter( _offset$1 ).negate(); + _obj$1.lookAt( vector ); - this.translate( _offset$1.x, _offset$1.y, _offset$1.z ); + _obj$1.updateMatrix(); - return this; + this.applyMatrix4( _obj$1.matrix ); - }, + return this; - normalize: function () { + }, - this.computeBoundingSphere(); + fromBufferGeometry: function ( geometry ) { - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; - - var s = radius === 0 ? 1 : 1.0 / radius; + var scope = this; - var matrix = new Matrix4(); - matrix.set( - s, 0, 0, - s * center.x, - 0, s, 0, - s * center.y, - 0, 0, s, - s * center.z, - 0, 0, 0, 1 - ); + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - this.applyMatrix( matrix ); + if ( attributes.position === undefined ) { + console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' ); return this; - }, - - computeFaceNormals: function () { - - var cb = new Vector3(), ab = new Vector3(); + } - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + var positions = attributes.position.array; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - var face = this.faces[ f ]; + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + for ( var i = 0; i < positions.length; i += 3 ) { - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + scope.vertices.push( new Vector3().fromArray( positions, i ) ); - cb.normalize(); + if ( colors !== undefined ) { - face.normal.copy( cb ); + scope.colors.push( new Color().fromArray( colors, i ) ); } - }, + } - computeVertexNormals: function ( areaWeighted ) { + function addFace( a, b, c, materialIndex ) { - if ( areaWeighted === undefined ) { areaWeighted = true; } + var vertexColors = ( colors === undefined ) ? [] : [ + scope.colors[ a ].clone(), + scope.colors[ b ].clone(), + scope.colors[ c ].clone() ]; + + var vertexNormals = ( normals === undefined ) ? [] : [ + new Vector3().fromArray( normals, a * 3 ), + new Vector3().fromArray( normals, b * 3 ), + new Vector3().fromArray( normals, c * 3 ) + ]; - var v, vl, f, fl, face, vertices; + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - vertices = new Array( this.vertices.length ); + scope.faces.push( face ); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + if ( uvs !== undefined ) { - vertices[ v ] = new Vector3(); + scope.faceVertexUvs[ 0 ].push( [ + new Vector2().fromArray( uvs, a * 2 ), + new Vector2().fromArray( uvs, b * 2 ), + new Vector2().fromArray( uvs, c * 2 ) + ] ); } - if ( areaWeighted ) { + if ( uvs2 !== undefined ) { - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + scope.faceVertexUvs[ 1 ].push( [ + new Vector2().fromArray( uvs2, a * 2 ), + new Vector2().fromArray( uvs2, b * 2 ), + new Vector2().fromArray( uvs2, c * 2 ) + ] ); - var vA, vB, vC; - var cb = new Vector3(), ab = new Vector3(); + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + var groups = geometry.groups; - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + if ( groups.length > 0 ) { - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + for ( var i = 0; i < groups.length; i ++ ) { - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + var group = groups[ i ]; - } + var start = group.start; + var count = group.count; - } else { + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - this.computeFaceNormals(); + if ( indices !== undefined ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - face = this.faces[ f ]; + } else { + + addFace( j, j + 1, j + 2, group.materialIndex ); - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + } } } - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - - vertices[ v ].normalize(); - - } + } else { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( indices !== undefined ) { - face = this.faces[ f ]; + for ( var i = 0; i < indices.length; i += 3 ) { - var vertexNormals = face.vertexNormals; + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - if ( vertexNormals.length === 3 ) { + } - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + } else { - } else { + for ( var i = 0; i < positions.length / 3; i += 3 ) { - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + addFace( i, i + 1, i + 2 ); } } - if ( this.faces.length > 0 ) { - - this.normalsNeedUpdate = true; - - } - - }, + } - computeFlatVertexNormals: function () { + this.computeFaceNormals(); - var f, fl, face; + if ( geometry.boundingBox !== null ) { - this.computeFaceNormals(); + this.boundingBox = geometry.boundingBox.clone(); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + if ( geometry.boundingSphere !== null ) { - var vertexNormals = face.vertexNormals; + this.boundingSphere = geometry.boundingSphere.clone(); - if ( vertexNormals.length === 3 ) { + } - vertexNormals[ 0 ].copy( face.normal ); - vertexNormals[ 1 ].copy( face.normal ); - vertexNormals[ 2 ].copy( face.normal ); + return this; - } else { + }, - vertexNormals[ 0 ] = face.normal.clone(); - vertexNormals[ 1 ] = face.normal.clone(); - vertexNormals[ 2 ] = face.normal.clone(); + center: function () { - } + this.computeBoundingBox(); - } + this.boundingBox.getCenter( _offset$1 ).negate(); - if ( this.faces.length > 0 ) { + this.translate( _offset$1.x, _offset$1.y, _offset$1.z ); - this.normalsNeedUpdate = true; + return this; - } + }, - }, + normalize: function () { - computeMorphNormals: function () { + this.computeBoundingSphere(); - var i, il, f, fl, face; + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + var s = radius === 0 ? 1 : 1.0 / radius; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - face = this.faces[ f ]; + this.applyMatrix4( matrix ); - if ( ! face.__originalFaceNormal ) { + return this; - face.__originalFaceNormal = face.normal.clone(); + }, - } else { + computeFaceNormals: function () { - face.__originalFaceNormal.copy( face.normal ); + var cb = new Vector3(), ab = new Vector3(); - } + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; } + var face = this.faces[ f ]; - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - if ( ! face.__originalVertexNormals[ i ] ) { + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + cb.normalize(); - } else { + face.normal.copy( cb ); - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + } - } + }, - } + computeVertexNormals: function ( areaWeighted ) { - } + if ( areaWeighted === undefined ) areaWeighted = true; - // use temp geometry to compute face and vertex normals for each morph + var v, vl, f, fl, face, vertices; - var tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; + vertices = new Array( this.vertices.length ); - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - // create on first access + vertices[ v ] = new Vector3(); - if ( ! this.morphNormals[ i ] ) { + } - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + if ( areaWeighted ) { - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - var faceNormal, vertexNormals; + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - faceNormal = new Vector3(); - vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; + face = this.faces[ f ]; - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - } + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - } + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - var morphNormals = this.morphNormals[ i ]; + } - // set vertices to morph target + } else { - tmpGeo.vertices = this.morphTargets[ i ].vertices; + this.computeFaceNormals(); - // compute morph normals + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + face = this.faces[ f ]; - // store morph normals + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - var faceNormal, vertexNormals; + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + } - face = this.faces[ f ]; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + vertices[ v ].normalize(); - faceNormal.copy( face.normal ); + } - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - } + var vertexNormals = face.vertexNormals; - // restore original normals + if ( vertexNormals.length === 3 ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - face = this.faces[ f ]; + } else { - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); } - }, - - computeBoundingBox: function () { + } - if ( this.boundingBox === null ) { + if ( this.faces.length > 0 ) { - this.boundingBox = new Box3(); + this.normalsNeedUpdate = true; - } + } - this.boundingBox.setFromPoints( this.vertices ); + }, - }, + computeFlatVertexNormals: function () { - computeBoundingSphere: function () { + var f, fl, face; - if ( this.boundingSphere === null ) { + this.computeFaceNormals(); - this.boundingSphere = new Sphere(); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - this.boundingSphere.setFromPoints( this.vertices ); + var vertexNormals = face.vertexNormals; - }, + if ( vertexNormals.length === 3 ) { - merge: function ( geometry, matrix, materialIndexOffset ) { + vertexNormals[ 0 ].copy( face.normal ); + vertexNormals[ 1 ].copy( face.normal ); + vertexNormals[ 2 ].copy( face.normal ); - if ( ! ( geometry && geometry.isGeometry ) ) { + } else { - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + vertexNormals[ 0 ] = face.normal.clone(); + vertexNormals[ 1 ] = face.normal.clone(); + vertexNormals[ 2 ] = face.normal.clone(); } - var normalMatrix, - vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - colors1 = this.colors, - colors2 = geometry.colors; - - if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; } + } - if ( matrix !== undefined ) { + if ( this.faces.length > 0 ) { - normalMatrix = new Matrix3().getNormalMatrix( matrix ); + this.normalsNeedUpdate = true; - } + } - // vertices + }, - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + computeMorphNormals: function () { - var vertex = vertices2[ i ]; + var i, il, f, fl, face; - var vertexCopy = vertex.clone(); + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - vertices1.push( vertexCopy ); + face = this.faces[ f ]; - } + if ( ! face.__originalFaceNormal ) { - // colors + face.__originalFaceNormal = face.normal.clone(); - for ( var i = 0, il = colors2.length; i < il; i ++ ) { + } else { - colors1.push( colors2[ i ].clone() ); + face.__originalFaceNormal.copy( face.normal ); } - // faces + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - for ( i = 0, il = faces2.length; i < il; i ++ ) { + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; + if ( ! face.__originalVertexNormals[ i ] ) { - faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - if ( normalMatrix !== undefined ) { + } else { - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); } - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + } - normal = faceVertexNormals[ j ].clone(); + } - if ( normalMatrix !== undefined ) { + // use temp geometry to compute face and vertex normals for each morph - normal.applyMatrix3( normalMatrix ).normalize(); + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - } + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - faceCopy.vertexNormals.push( normal ); + // create on first access - } + if ( ! this.morphNormals[ i ] ) { - faceCopy.color.copy( face.color ); + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + var faceNormal, vertexNormals; - } + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - faces1.push( faceCopy ); + } } - // uvs + var morphNormals = this.morphNormals[ i ]; - for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) { + // set vertices to morph target - var faceVertexUvs2 = geometry.faceVertexUvs[ i ]; + tmpGeo.vertices = this.morphTargets[ i ].vertices; - if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; } + // compute morph normals - for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) { + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - var uvs2 = faceVertexUvs2[ j ], uvsCopy = []; + // store morph normals - for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) { + var faceNormal, vertexNormals; - uvsCopy.push( uvs2[ k ].clone() ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - this.faceVertexUvs[ i ].push( uvsCopy ); + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - } + faceNormal.copy( face.normal ); - } + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - }, + } - mergeMesh: function ( mesh ) { + } - if ( ! ( mesh && mesh.isMesh ) ) { + // restore original normals - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); } + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - this.merge( mesh.geometry, mesh.matrix ); + } - }, + }, - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + computeBoundingBox: function () { - mergeVertices: function () { + if ( this.boundingBox === null ) { - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + this.boundingBox = new Box3(); - var v, key; - var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; + } - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + this.boundingBox.setFromPoints( this.vertices ); - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + }, - if ( verticesMap[ key ] === undefined ) { + computeBoundingSphere: function () { - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + if ( this.boundingSphere === null ) { - } else { + this.boundingSphere = new Sphere(); - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + } - } + this.boundingSphere.setFromPoints( this.vertices ); - } + }, + merge: function ( geometry, matrix, materialIndexOffset ) { - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + if ( ! ( geometry && geometry.isGeometry ) ) { - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - face = this.faces[ i ]; + } - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + var normalMatrix, + vertexOffset = this.vertices.length, + vertices1 = this.vertices, + vertices2 = geometry.vertices, + faces1 = this.faces, + faces2 = geometry.faces, + colors1 = this.colors, + colors2 = geometry.colors; - indices = [ face.a, face.b, face.c ]; + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { + if ( matrix !== undefined ) { - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - faceIndicesToRemove.push( i ); - break; + } - } + // vertices - } + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - } + var vertex = vertices2[ i ]; - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { + var vertexCopy = vertex.clone(); - var idx = faceIndicesToRemove[ i ]; + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - this.faces.splice( idx, 1 ); + vertices1.push( vertexCopy ); - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + } - this.faceVertexUvs[ j ].splice( idx, 1 ); + // colors - } + for ( var i = 0, il = colors2.length; i < il; i ++ ) { - } + colors1.push( colors2[ i ].clone() ); - // Use unique set of vertices + } - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + // faces - }, + for ( i = 0, il = faces2.length; i < il; i ++ ) { - setFromPoints: function ( points ) { + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - this.vertices = []; + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - for ( var i = 0, l = points.length; i < l; i ++ ) { + if ( normalMatrix !== undefined ) { - var point = points[ i ]; - this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); } - return this; - - }, + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - sortFacesByMaterialIndex: function () { + normal = faceVertexNormals[ j ].clone(); - var faces = this.faces; - var length = faces.length; + if ( normalMatrix !== undefined ) { - // tag faces + normal.applyMatrix3( normalMatrix ).normalize(); - for ( var i = 0; i < length; i ++ ) { + } - faces[ i ]._id = i; + faceCopy.vertexNormals.push( normal ); } - // sort faces + faceCopy.color.copy( face.color ); - function materialIndexSort( a, b ) { + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - return a.materialIndex - b.materialIndex; + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); } - faces.sort( materialIndexSort ); - - // sort uvs + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + faces1.push( faceCopy ); - var newUvs1, newUvs2; + } - if ( uvs1 && uvs1.length === length ) { newUvs1 = []; } - if ( uvs2 && uvs2.length === length ) { newUvs2 = []; } + // uvs - for ( var i = 0; i < length; i ++ ) { + for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) { - var id = faces[ i ]._id; + var faceVertexUvs2 = geometry.faceVertexUvs[ i ]; - if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); } - if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); } + if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = []; - } + for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) { - if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; } - if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; } + var uvs2 = faceVertexUvs2[ j ], uvsCopy = []; - }, + for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) { - toJSON: function () { + uvsCopy.push( uvs2[ k ].clone() ); - var data = { - metadata: { - version: 4.5, - type: 'Geometry', - generator: 'Geometry.toJSON' } - }; - - // standard Geometry serialization - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) { data.name = this.name; } + this.faceVertexUvs[ i ].push( uvsCopy ); - if ( this.parameters !== undefined ) { + } - var parameters = this.parameters; + } - for ( var key in parameters ) { + }, - if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; } + mergeMesh: function ( mesh ) { - } + if ( ! ( mesh && mesh.isMesh ) ) { - return data; + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - } + } - var vertices = []; + if ( mesh.matrixAutoUpdate ) mesh.updateMatrix(); - for ( var i = 0; i < this.vertices.length; i ++ ) { + this.merge( mesh.geometry, mesh.matrix ); - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + }, - } + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + mergeVertices: function () { - for ( var i = 0; i < this.faces.length; i ++ ) { + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; - var face = this.faces[ i ]; + var v, key; + var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; - var hasMaterial = true; - var hasFaceUv = false; // deprecated - var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; - var hasFaceNormal = face.normal.length() > 0; - var hasFaceVertexNormal = face.vertexNormals.length > 0; - var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - var hasFaceVertexColor = face.vertexColors.length > 0; + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - var faceType = 0; + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - faceType = setBit( faceType, 0, 0 ); // isQuad - faceType = setBit( faceType, 1, hasMaterial ); - faceType = setBit( faceType, 2, hasFaceUv ); - faceType = setBit( faceType, 3, hasFaceVertexUv ); - faceType = setBit( faceType, 4, hasFaceNormal ); - faceType = setBit( faceType, 5, hasFaceVertexNormal ); - faceType = setBit( faceType, 6, hasFaceColor ); - faceType = setBit( faceType, 7, hasFaceVertexColor ); + if ( verticesMap[ key ] === undefined ) { - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - if ( hasFaceVertexUv ) { + } else { - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + } - } + } - if ( hasFaceNormal ) { - faces.push( getNormalIndex( face.normal ) ); + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - } + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - if ( hasFaceVertexNormal ) { + face = this.faces[ i ]; - var vertexNormals = face.vertexNormals; + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + indices = [ face.a, face.b, face.c ]; - } + // if any duplicate vertices are found in a Face3 + // we have to remove the face as nothing can be saved + for ( var n = 0; n < 3; n ++ ) { - if ( hasFaceColor ) { + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - faces.push( getColorIndex( face.color ) ); + faceIndicesToRemove.push( i ); + break; } - if ( hasFaceVertexColor ) { + } - var vertexColors = face.vertexColors; + } - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - } + var idx = faceIndicesToRemove[ i ]; - } + this.faces.splice( idx, 1 ); - function setBit( value, position, enabled ) { + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + this.faceVertexUvs[ j ].splice( idx, 1 ); } - function getNormalIndex( normal ) { - - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + } - if ( normalsHash[ hash ] !== undefined ) { + // Use unique set of vertices - return normalsHash[ hash ]; + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - } + }, - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + setFromPoints: function ( points ) { - return normalsHash[ hash ]; + this.vertices = []; - } + for ( var i = 0, l = points.length; i < l; i ++ ) { - function getColorIndex( color ) { + var point = points[ i ]; + this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + } - if ( colorsHash[ hash ] !== undefined ) { + return this; - return colorsHash[ hash ]; + }, - } + sortFacesByMaterialIndex: function () { - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + var faces = this.faces; + var length = faces.length; - return colorsHash[ hash ]; + // tag faces - } + for ( var i = 0; i < length; i ++ ) { - function getUvIndex( uv ) { + faces[ i ]._id = i; - var hash = uv.x.toString() + uv.y.toString(); + } - if ( uvsHash[ hash ] !== undefined ) { + // sort faces - return uvsHash[ hash ]; + function materialIndexSort( a, b ) { - } + return a.materialIndex - b.materialIndex; - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + } - return uvsHash[ hash ]; + faces.sort( materialIndexSort ); - } + // sort uvs - data.data = {}; + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - data.data.vertices = vertices; - data.data.normals = normals; - if ( colors.length > 0 ) { data.data.colors = colors; } - if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility - data.data.faces = faces; + var newUvs1, newUvs2; - return data; + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - }, + for ( var i = 0; i < length; i ++ ) { - clone: function () { + var id = faces[ i ]._id; - /* - // Handle primitives + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); - var parameters = this.parameters; + } - if ( parameters !== undefined ) { + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; - var values = []; + }, - for ( var key in parameters ) { + toJSON: function () { - values.push( parameters[ key ] ); + var data = { + metadata: { + version: 4.5, + type: 'Geometry', + generator: 'Geometry.toJSON' + } + }; - } + // standard Geometry serialization - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - } + if ( this.parameters !== undefined ) { - return new this.constructor().copy( this ); - */ + var parameters = this.parameters; - return new Geometry().copy( this ); + for ( var key in parameters ) { - }, + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - copy: function ( source ) { + } - var i, il, j, jl, k, kl; + return data; - // reset + } - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; + var vertices = []; - // name + for ( var i = 0; i < this.vertices.length; i ++ ) { - this.name = source.name; + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - // vertices + } - var vertices = source.vertices; + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - for ( i = 0, il = vertices.length; i < il; i ++ ) { + for ( var i = 0; i < this.faces.length; i ++ ) { - this.vertices.push( vertices[ i ].clone() ); + var face = this.faces[ i ]; - } + var hasMaterial = true; + var hasFaceUv = false; // deprecated + var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; + var hasFaceNormal = face.normal.length() > 0; + var hasFaceVertexNormal = face.vertexNormals.length > 0; + var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; + var hasFaceVertexColor = face.vertexColors.length > 0; - // colors + var faceType = 0; - var colors = source.colors; + faceType = setBit( faceType, 0, 0 ); // isQuad + faceType = setBit( faceType, 1, hasMaterial ); + faceType = setBit( faceType, 2, hasFaceUv ); + faceType = setBit( faceType, 3, hasFaceVertexUv ); + faceType = setBit( faceType, 4, hasFaceNormal ); + faceType = setBit( faceType, 5, hasFaceVertexNormal ); + faceType = setBit( faceType, 6, hasFaceColor ); + faceType = setBit( faceType, 7, hasFaceVertexColor ); - for ( i = 0, il = colors.length; i < il; i ++ ) { + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - this.colors.push( colors[ i ].clone() ); + if ( hasFaceVertexUv ) { - } + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; - // faces + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); - var faces = source.faces; + } - for ( i = 0, il = faces.length; i < il; i ++ ) { + if ( hasFaceNormal ) { - this.faces.push( faces[ i ].clone() ); + faces.push( getNormalIndex( face.normal ) ); } - // face vertex uvs + if ( hasFaceVertexNormal ) { - for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + var vertexNormals = face.vertexNormals; - var faceVertexUvs = source.faceVertexUvs[ i ]; + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - if ( this.faceVertexUvs[ i ] === undefined ) { + } - this.faceVertexUvs[ i ] = []; + if ( hasFaceColor ) { - } + faces.push( getColorIndex( face.color ) ); - for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + } - var uvs = faceVertexUvs[ j ], uvsCopy = []; + if ( hasFaceVertexColor ) { - for ( k = 0, kl = uvs.length; k < kl; k ++ ) { + var vertexColors = face.vertexColors; - var uv = uvs[ k ]; + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - uvsCopy.push( uv.clone() ); + } - } + } - this.faceVertexUvs[ i ].push( uvsCopy ); + function setBit( value, position, enabled ) { - } + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - } + } - // morph targets + function getNormalIndex( normal ) { - var morphTargets = source.morphTargets; + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - for ( i = 0, il = morphTargets.length; i < il; i ++ ) { + if ( normalsHash[ hash ] !== undefined ) { - var morphTarget = {}; - morphTarget.name = morphTargets[ i ].name; + return normalsHash[ hash ]; - // vertices + } - if ( morphTargets[ i ].vertices !== undefined ) { + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - morphTarget.vertices = []; + return normalsHash[ hash ]; - for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) { + } - morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() ); + function getColorIndex( color ) { - } + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - } + if ( colorsHash[ hash ] !== undefined ) { + + return colorsHash[ hash ]; - // normals + } - if ( morphTargets[ i ].normals !== undefined ) { + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - morphTarget.normals = []; + return colorsHash[ hash ]; - for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) { + } - morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() ); + function getUvIndex( uv ) { - } + var hash = uv.x.toString() + uv.y.toString(); - } + if ( uvsHash[ hash ] !== undefined ) { - this.morphTargets.push( morphTarget ); + return uvsHash[ hash ]; } - // morph normals + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - var morphNormals = source.morphNormals; + return uvsHash[ hash ]; - for ( i = 0, il = morphNormals.length; i < il; i ++ ) { + } - var morphNormal = {}; + data.data = {}; - // vertex normals + data.data.vertices = vertices; + data.data.normals = normals; + if ( colors.length > 0 ) data.data.colors = colors; + if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility + data.data.faces = faces; - if ( morphNormals[ i ].vertexNormals !== undefined ) { + return data; - morphNormal.vertexNormals = []; + }, - for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) { + clone: function () { - var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ]; - var destVertexNormal = {}; + /* + // Handle primitives - destVertexNormal.a = srcVertexNormal.a.clone(); - destVertexNormal.b = srcVertexNormal.b.clone(); - destVertexNormal.c = srcVertexNormal.c.clone(); + var parameters = this.parameters; - morphNormal.vertexNormals.push( destVertexNormal ); + if ( parameters !== undefined ) { - } + var values = []; - } + for ( var key in parameters ) { - // face normals + values.push( parameters[ key ] ); - if ( morphNormals[ i ].faceNormals !== undefined ) { + } - morphNormal.faceNormals = []; + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) { + } - morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() ); + return new this.constructor().copy( this ); + */ - } + return new Geometry().copy( this ); - } + }, - this.morphNormals.push( morphNormal ); + copy: function ( source ) { - } + var i, il, j, jl, k, kl; - // skin weights + // reset - var skinWeights = source.skinWeights; + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [[]]; + this.morphTargets = []; + this.morphNormals = []; + this.skinWeights = []; + this.skinIndices = []; + this.lineDistances = []; + this.boundingBox = null; + this.boundingSphere = null; - for ( i = 0, il = skinWeights.length; i < il; i ++ ) { + // name - this.skinWeights.push( skinWeights[ i ].clone() ); + this.name = source.name; - } + // vertices - // skin indices + var vertices = source.vertices; - var skinIndices = source.skinIndices; + for ( i = 0, il = vertices.length; i < il; i ++ ) { - for ( i = 0, il = skinIndices.length; i < il; i ++ ) { + this.vertices.push( vertices[ i ].clone() ); - this.skinIndices.push( skinIndices[ i ].clone() ); + } - } + // colors - // line distances + var colors = source.colors; - var lineDistances = source.lineDistances; + for ( i = 0, il = colors.length; i < il; i ++ ) { - for ( i = 0, il = lineDistances.length; i < il; i ++ ) { + this.colors.push( colors[ i ].clone() ); - this.lineDistances.push( lineDistances[ i ] ); + } - } + // faces - // bounding box + var faces = source.faces; - var boundingBox = source.boundingBox; + for ( i = 0, il = faces.length; i < il; i ++ ) { - if ( boundingBox !== null ) { + this.faces.push( faces[ i ].clone() ); - this.boundingBox = boundingBox.clone(); + } - } + // face vertex uvs - // bounding sphere + for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { - var boundingSphere = source.boundingSphere; + var faceVertexUvs = source.faceVertexUvs[ i ]; - if ( boundingSphere !== null ) { + if ( this.faceVertexUvs[ i ] === undefined ) { - this.boundingSphere = boundingSphere.clone(); + this.faceVertexUvs[ i ] = []; } - // update flags + for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - this.elementsNeedUpdate = source.elementsNeedUpdate; - this.verticesNeedUpdate = source.verticesNeedUpdate; - this.uvsNeedUpdate = source.uvsNeedUpdate; - this.normalsNeedUpdate = source.normalsNeedUpdate; - this.colorsNeedUpdate = source.colorsNeedUpdate; - this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; - this.groupsNeedUpdate = source.groupsNeedUpdate; + var uvs = faceVertexUvs[ j ], uvsCopy = []; - return this; + for ( k = 0, kl = uvs.length; k < kl; k ++ ) { - }, + var uv = uvs[ k ]; - dispose: function () { + uvsCopy.push( uv.clone() ); - this.dispatchEvent( { type: 'dispose' } ); + } - } + this.faceVertexUvs[ i ].push( uvsCopy ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + } - // BoxGeometry + // morph targets - var BoxGeometry = /*@__PURE__*/(function (Geometry) { - function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + var morphTargets = source.morphTargets; - Geometry.call(this); + for ( i = 0, il = morphTargets.length; i < il; i ++ ) { - this.type = 'BoxGeometry'; + var morphTarget = {}; + morphTarget.name = morphTargets[ i ].name; - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + // vertices - this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + if ( morphTargets[ i ].vertices !== undefined ) { - } + morphTarget.vertices = []; - if ( Geometry ) BoxGeometry.__proto__ = Geometry; - BoxGeometry.prototype = Object.create( Geometry && Geometry.prototype ); - BoxGeometry.prototype.constructor = BoxGeometry; + for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) { - return BoxGeometry; - }(Geometry)); + morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() ); - // BoxBufferGeometry + } - var BoxBufferGeometry = /*@__PURE__*/(function (BufferGeometry) { - function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } - BufferGeometry.call(this); + // normals - this.type = 'BoxBufferGeometry'; + if ( morphTargets[ i ].normals !== undefined ) { - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + morphTarget.normals = []; - var scope = this; + for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) { - width = width || 1; - height = height || 1; - depth = depth || 1; + morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() ); - // segments + } - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + } - // buffers + this.morphTargets.push( morphTarget ); - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + } - // helper variables + // morph normals - var numberOfVertices = 0; - var groupStart = 0; + var morphNormals = source.morphNormals; - // build each side of the box geometry + for ( i = 0, il = morphNormals.length; i < il; i ++ ) { - buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px - buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx - buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py - buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny - buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz - buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + var morphNormal = {}; - // build geometry + // vertex normals - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + if ( morphNormals[ i ].vertexNormals !== undefined ) { - function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + morphNormal.vertexNormals = []; - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) { - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ]; + var destVertexNormal = {}; - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + destVertexNormal.a = srcVertexNormal.a.clone(); + destVertexNormal.b = srcVertexNormal.b.clone(); + destVertexNormal.c = srcVertexNormal.c.clone(); - var vertexCounter = 0; - var groupCount = 0; + morphNormal.vertexNormals.push( destVertexNormal ); - var ix, iy; + } - var vector = new Vector3(); + } - // generate vertices, normals and uvs + // face normals - for ( iy = 0; iy < gridY1; iy ++ ) { + if ( morphNormals[ i ].faceNormals !== undefined ) { - var y = iy * segmentHeight - heightHalf; + morphNormal.faceNormals = []; - for ( ix = 0; ix < gridX1; ix ++ ) { + for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) { - var x = ix * segmentWidth - widthHalf; + morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() ); - // set values to correct vector component + } - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + } - // now apply vector to vertex buffer + this.morphNormals.push( morphNormal ); - vertices.push( vector.x, vector.y, vector.z ); + } - // set values to correct vector component + // skin weights - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + var skinWeights = source.skinWeights; - // now apply vector to normal buffer + for ( i = 0, il = skinWeights.length; i < il; i ++ ) { - normals.push( vector.x, vector.y, vector.z ); + this.skinWeights.push( skinWeights[ i ].clone() ); - // uvs + } - uvs.push( ix / gridX ); - uvs.push( 1 - ( iy / gridY ) ); + // skin indices - // counters + var skinIndices = source.skinIndices; - vertexCounter += 1; + for ( i = 0, il = skinIndices.length; i < il; i ++ ) { - } + this.skinIndices.push( skinIndices[ i ].clone() ); - } + } - // indices + // line distances - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + var lineDistances = source.lineDistances; - for ( iy = 0; iy < gridY; iy ++ ) { + for ( i = 0, il = lineDistances.length; i < il; i ++ ) { - for ( ix = 0; ix < gridX; ix ++ ) { + this.lineDistances.push( lineDistances[ i ] ); - var a = numberOfVertices + ix + gridX1 * iy; - var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); - var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + } - // faces + // bounding box - indices.push( a, b, d ); - indices.push( b, c, d ); + var boundingBox = source.boundingBox; - // increase counter + if ( boundingBox !== null ) { - groupCount += 6; + this.boundingBox = boundingBox.clone(); - } + } - } + // bounding sphere - // add a group to the geometry. this will ensure multi material support + var boundingSphere = source.boundingSphere; - scope.addGroup( groupStart, groupCount, materialIndex ); + if ( boundingSphere !== null ) { - // calculate new start value for groups + this.boundingSphere = boundingSphere.clone(); - groupStart += groupCount; + } - // update total number of vertices + // update flags - numberOfVertices += vertexCounter; + this.elementsNeedUpdate = source.elementsNeedUpdate; + this.verticesNeedUpdate = source.verticesNeedUpdate; + this.uvsNeedUpdate = source.uvsNeedUpdate; + this.normalsNeedUpdate = source.normalsNeedUpdate; + this.colorsNeedUpdate = source.colorsNeedUpdate; + this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; + this.groupsNeedUpdate = source.groupsNeedUpdate; - } + return this; - } + }, - if ( BufferGeometry ) BoxBufferGeometry.__proto__ = BufferGeometry; - BoxBufferGeometry.prototype = Object.create( BufferGeometry && BufferGeometry.prototype ); - BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + dispose: function () { - return BoxBufferGeometry; - }(BufferGeometry)); + this.dispatchEvent( { type: 'dispose' } ); - /** - * Uniform Utilities - */ + } - function cloneUniforms( src ) { +} ); - var dst = {}; +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - for ( var u in src ) { +// BoxGeometry - dst[ u ] = {}; +class BoxGeometry extends Geometry { - for ( var p in src[ u ] ) { + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { - var property = src[ u ][ p ]; + super(); - if ( property && ( property.isColor || - property.isMatrix3 || property.isMatrix4 || - property.isVector2 || property.isVector3 || property.isVector4 || - property.isTexture ) ) { + this.type = 'BoxGeometry'; - dst[ u ][ p ] = property.clone(); + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - } else if ( Array.isArray( property ) ) { + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); - dst[ u ][ p ] = property.slice(); + } - } else { +} - dst[ u ][ p ] = property; +// BoxBufferGeometry - } +class BoxBufferGeometry extends BufferGeometry { - } + constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) { - } + super(); - return dst; + this.type = 'BoxBufferGeometry'; - } + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - function mergeUniforms( uniforms ) { + const scope = this; - var merged = {}; + width = width || 1; + height = height || 1; + depth = depth || 1; - for ( var u = 0; u < uniforms.length; u ++ ) { + // segments - var tmp = cloneUniforms( uniforms[ u ] ); + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - for ( var p in tmp ) { + // buffers - merged[ p ] = tmp[ p ]; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; - } + // helper variables - } + let numberOfVertices = 0; + let groupStart = 0; - return merged; + // build each side of the box geometry - } + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz - // Legacy + // build geometry - var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + const segmentWidth = width / gridX; + const segmentHeight = height / gridY; - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + const widthHalf = width / 2; + const heightHalf = height / 2; + const depthHalf = depth / 2; - function ShaderMaterial( parameters ) { + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; - Material.call( this ); + let vertexCounter = 0; + let groupCount = 0; - this.type = 'ShaderMaterial'; + const vector = new Vector3(); - this.defines = {}; - this.uniforms = {}; + // generate vertices, normals and uvs - this.vertexShader = default_vertex; - this.fragmentShader = default_fragment; + for ( let iy = 0; iy < gridY1; iy ++ ) { - this.linewidth = 1; + const y = iy * segmentHeight - heightHalf; - this.wireframe = false; - this.wireframeLinewidth = 1; + for ( let ix = 0; ix < gridX1; ix ++ ) { - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + const x = ix * segmentWidth - widthHalf; - this.skinning = false; // set to use skinning attribute streams - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + // set values to correct vector component - this.extensions = { - derivatives: false, // set to use derivatives - fragDepth: false, // set to use fragment depth values - drawBuffers: false, // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + // now apply vector to vertex buffer - this.index0AttributeName = undefined; - this.uniformsNeedUpdate = false; + vertices.push( vector.x, vector.y, vector.z ); - if ( parameters !== undefined ) { + // set values to correct vector component - if ( parameters.attributes !== undefined ) { + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + // now apply vector to normal buffer - } + normals.push( vector.x, vector.y, vector.z ); - this.setValues( parameters ); + // uvs - } + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); - } + // counters + + vertexCounter += 1; - ShaderMaterial.prototype = Object.create( Material.prototype ); - ShaderMaterial.prototype.constructor = ShaderMaterial; + } - ShaderMaterial.prototype.isShaderMaterial = true; + } - ShaderMaterial.prototype.copy = function ( source ) { + // indices - Material.prototype.copy.call( this, source ); + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + for ( let iy = 0; iy < gridY; iy ++ ) { - this.uniforms = cloneUniforms( source.uniforms ); + for ( let ix = 0; ix < gridX; ix ++ ) { - this.defines = Object.assign( {}, source.defines ); + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + // faces - this.lights = source.lights; - this.clipping = source.clipping; + indices.push( a, b, d ); + indices.push( b, c, d ); - this.skinning = source.skinning; + // increase counter - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + groupCount += 6; - this.extensions = source.extensions; + } - return this; + } - }; + // add a group to the geometry. this will ensure multi material support - ShaderMaterial.prototype.toJSON = function ( meta ) { + scope.addGroup( groupStart, groupCount, materialIndex ); - var data = Material.prototype.toJSON.call( this, meta ); + // calculate new start value for groups - data.uniforms = {}; + groupStart += groupCount; - for ( var name in this.uniforms ) { + // update total number of vertices - var uniform = this.uniforms[ name ]; - var value = uniform.value; + numberOfVertices += vertexCounter; - if ( value && value.isTexture ) { + } - data.uniforms[ name ] = { - type: 't', - value: value.toJSON( meta ).uuid - }; + } - } else if ( value && value.isColor ) { +} - data.uniforms[ name ] = { - type: 'c', - value: value.getHex() - }; +/** + * Uniform Utilities + */ - } else if ( value && value.isVector2 ) { +function cloneUniforms( src ) { - data.uniforms[ name ] = { - type: 'v2', - value: value.toArray() - }; + var dst = {}; - } else if ( value && value.isVector3 ) { + for ( var u in src ) { - data.uniforms[ name ] = { - type: 'v3', - value: value.toArray() - }; + dst[ u ] = {}; - } else if ( value && value.isVector4 ) { + for ( var p in src[ u ] ) { - data.uniforms[ name ] = { - type: 'v4', - value: value.toArray() - }; + var property = src[ u ][ p ]; - } else if ( value && value.isMatrix3 ) { + if ( property && ( property.isColor || + property.isMatrix3 || property.isMatrix4 || + property.isVector2 || property.isVector3 || property.isVector4 || + property.isTexture ) ) { - data.uniforms[ name ] = { - type: 'm3', - value: value.toArray() - }; + dst[ u ][ p ] = property.clone(); - } else if ( value && value.isMatrix4 ) { + } else if ( Array.isArray( property ) ) { - data.uniforms[ name ] = { - type: 'm4', - value: value.toArray() - }; + dst[ u ][ p ] = property.slice(); } else { - data.uniforms[ name ] = { - value: value - }; - - // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far + dst[ u ][ p ] = property; } } - if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; } - - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; - - var extensions = {}; - - for ( var key in this.extensions ) { - - if ( this.extensions[ key ] === true ) { extensions[ key ] = true; } - - } + } - if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; } + return dst; - return data; +} - }; +function mergeUniforms( uniforms ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley - */ + var merged = {}; - function Camera() { + for ( var u = 0; u < uniforms.length; u ++ ) { - Object3D.call( this ); + var tmp = cloneUniforms( uniforms[ u ] ); - this.type = 'Camera'; + for ( var p in tmp ) { - this.matrixWorldInverse = new Matrix4(); + merged[ p ] = tmp[ p ]; - this.projectionMatrix = new Matrix4(); - this.projectionMatrixInverse = new Matrix4(); + } } - Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { + return merged; - constructor: Camera, +} - isCamera: true, +// Legacy - copy: function ( source, recursive ) { +var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; - Object3D.prototype.copy.call( this, source, recursive ); +var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; - this.matrixWorldInverse.copy( source.matrixWorldInverse ); +var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; - this.projectionMatrix.copy( source.projectionMatrix ); - this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, + * + * fragmentShader: , + * vertexShader: , + * + * wireframe: , + * wireframeLinewidth: , + * + * lights: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - return this; - - }, +function ShaderMaterial( parameters ) { - getWorldDirection: function ( target ) { + Material.call( this ); - if ( target === undefined ) { + this.type = 'ShaderMaterial'; - console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); - target = new Vector3(); + this.defines = {}; + this.uniforms = {}; - } + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; - this.updateMatrixWorld( true ); + this.linewidth = 1; - var e = this.matrixWorld.elements; + this.wireframe = false; + this.wireframeLinewidth = 1; - return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes - }, + this.skinning = false; // set to use skinning attribute streams + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - updateMatrixWorld: function ( force ) { + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; - Object3D.prototype.updateMatrixWorld.call( this, force ); + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] + }; - this.matrixWorldInverse.getInverse( this.matrixWorld ); + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; - }, + if ( parameters !== undefined ) { - clone: function () { + if ( parameters.attributes !== undefined ) { - return new this.constructor().copy( this ); + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); } - } ); + this.setValues( parameters ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ + } - function PerspectiveCamera( fov, aspect, near, far ) { +} - Camera.call( this ); +ShaderMaterial.prototype = Object.create( Material.prototype ); +ShaderMaterial.prototype.constructor = ShaderMaterial; - this.type = 'PerspectiveCamera'; +ShaderMaterial.prototype.isShaderMaterial = true; - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; +ShaderMaterial.prototype.copy = function ( source ) { - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + Material.prototype.copy.call( this, source ); - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + this.uniforms = cloneUniforms( source.uniforms ); - this.updateProjectionMatrix(); + this.defines = Object.assign( {}, source.defines ); - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + this.lights = source.lights; + this.clipping = source.clipping; - constructor: PerspectiveCamera, + this.skinning = source.skinning; - isPerspectiveCamera: true, + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - copy: function ( source, recursive ) { + this.extensions = Object.assign( {}, source.extensions ); - Camera.prototype.copy.call( this, source, recursive ); + return this; - this.fov = source.fov; - this.zoom = source.zoom; +}; - this.near = source.near; - this.far = source.far; - this.focus = source.focus; +ShaderMaterial.prototype.toJSON = function ( meta ) { - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + var data = Material.prototype.toJSON.call( this, meta ); - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + data.uniforms = {}; - return this; + for ( var name in this.uniforms ) { - }, + var uniform = this.uniforms[ name ]; + var value = uniform.value; - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength: function ( focalLength ) { + if ( value && value.isTexture ) { - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + data.uniforms[ name ] = { + type: 't', + value: value.toJSON( meta ).uuid + }; - this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + } else if ( value && value.isColor ) { - }, + data.uniforms[ name ] = { + type: 'c', + value: value.getHex() + }; - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + } else if ( value && value.isVector2 ) { - var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov ); + data.uniforms[ name ] = { + type: 'v2', + value: value.toArray() + }; - return 0.5 * this.getFilmHeight() / vExtentSlope; + } else if ( value && value.isVector3 ) { - }, + data.uniforms[ name ] = { + type: 'v3', + value: value.toArray() + }; - getEffectiveFOV: function () { + } else if ( value && value.isVector4 ) { - return _Math.RAD2DEG * 2 * Math.atan( - Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + data.uniforms[ name ] = { + type: 'v4', + value: value.toArray() + }; - }, + } else if ( value && value.isMatrix3 ) { - getFilmWidth: function () { + data.uniforms[ name ] = { + type: 'm3', + value: value.toArray() + }; - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + } else if ( value && value.isMatrix4 ) { - }, + data.uniforms[ name ] = { + type: 'm4', + value: value.toArray() + }; - getFilmHeight: function () { + } else { - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + data.uniforms[ name ] = { + value: value + }; - }, + // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far - /** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + } - this.aspect = fullWidth / fullHeight; + } - if ( this.view === null ) { + if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines; - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - } + var extensions = {}; - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; + for ( var key in this.extensions ) { - this.updateProjectionMatrix(); + if ( this.extensions[ key ] === true ) extensions[ key ] = true; - }, + } - clearViewOffset: function () { + if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions; - if ( this.view !== null ) { + return data; - this.view.enabled = false; +}; - } +/** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley +*/ - this.updateProjectionMatrix(); +function Camera() { - }, + Object3D.call( this ); - updateProjectionMatrix: function () { + this.type = 'Camera'; - var near = this.near, - top = near * Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, - height = 2 * top, - width = this.aspect * height, - left = - 0.5 * width, - view = this.view; + this.matrixWorldInverse = new Matrix4(); - if ( this.view !== null && this.view.enabled ) { + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; +} - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; +Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Camera, - var skew = this.filmOffset; - if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); } + isCamera: true, - this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); + copy: function ( source, recursive ) { - this.projectionMatrixInverse.getInverse( this.projectionMatrix ); + Object3D.prototype.copy.call( this, source, recursive ); - }, + this.matrixWorldInverse.copy( source.matrixWorldInverse ); - toJSON: function ( meta ) { + this.projectionMatrix.copy( source.projectionMatrix ); + this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); - var data = Object3D.prototype.toJSON.call( this, meta ); + return this; - data.object.fov = this.fov; - data.object.zoom = this.zoom; + }, - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + getWorldDirection: function ( target ) { - data.object.aspect = this.aspect; + if ( target === undefined ) { - if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); } + console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); + target = new Vector3(); - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + } - return data; + this.updateMatrixWorld( true ); - } + var e = this.matrixWorld.elements; - } ); + return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); - /** - * Camera for rendering cube maps - * - renders scene into axis-aligned cube - * - * @author alteredq / http://alteredqualia.com/ - */ + }, - var fov = 90, aspect = 1; + updateMatrixWorld: function ( force ) { - function CubeCamera( near, far, cubeResolution, options ) { + Object3D.prototype.updateMatrixWorld.call( this, force ); - Object3D.call( this ); + this.matrixWorldInverse.getInverse( this.matrixWorld ); - this.type = 'CubeCamera'; + }, - var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); - cameraPX.up.set( 0, - 1, 0 ); - cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); - this.add( cameraPX ); + updateWorldMatrix: function ( updateParents, updateChildren ) { - var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); - cameraNX.up.set( 0, - 1, 0 ); - cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); - this.add( cameraNX ); + Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren ); - var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); - cameraPY.up.set( 0, 0, 1 ); - cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); - this.add( cameraPY ); + this.matrixWorldInverse.getInverse( this.matrixWorld ); - var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); - cameraNY.up.set( 0, 0, - 1 ); - cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); - this.add( cameraNY ); + }, - var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); - cameraPZ.up.set( 0, - 1, 0 ); - cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); - this.add( cameraPZ ); + clone: function () { - var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); - cameraNZ.up.set( 0, - 1, 0 ); - cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); - this.add( cameraNZ ); + return new this.constructor().copy( this ); - options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; + } - this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); - this.renderTarget.texture.name = "CubeCamera"; +} ); - this.update = function ( renderer, scene ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - if ( this.parent === null ) { this.updateMatrixWorld(); } +function PerspectiveCamera( fov, aspect, near, far ) { - var currentRenderTarget = renderer.getRenderTarget(); + Camera.call( this ); - var renderTarget = this.renderTarget; - var generateMipmaps = renderTarget.texture.generateMipmaps; + this.type = 'PerspectiveCamera'; - renderTarget.texture.generateMipmaps = false; + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - renderer.setRenderTarget( renderTarget, 0 ); - renderer.render( scene, cameraPX ); + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; - renderer.setRenderTarget( renderTarget, 1 ); - renderer.render( scene, cameraNX ); + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; - renderer.setRenderTarget( renderTarget, 2 ); - renderer.render( scene, cameraPY ); + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - renderer.setRenderTarget( renderTarget, 3 ); - renderer.render( scene, cameraNY ); + this.updateProjectionMatrix(); - renderer.setRenderTarget( renderTarget, 4 ); - renderer.render( scene, cameraPZ ); +} - renderTarget.texture.generateMipmaps = generateMipmaps; +PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - renderer.setRenderTarget( renderTarget, 5 ); - renderer.render( scene, cameraNZ ); + constructor: PerspectiveCamera, - renderer.setRenderTarget( currentRenderTarget ); + isPerspectiveCamera: true, - }; + copy: function ( source, recursive ) { - this.clear = function ( renderer, color, depth, stencil ) { + Camera.prototype.copy.call( this, source, recursive ); - var currentRenderTarget = renderer.getRenderTarget(); + this.fov = source.fov; + this.zoom = source.zoom; - var renderTarget = this.renderTarget; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - for ( var i = 0; i < 6; i ++ ) { + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - renderer.setRenderTarget( renderTarget, i ); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - renderer.clear( color, depth, stencil ); + return this; - } + }, - renderer.setRenderTarget( currentRenderTarget ); + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength: function ( focalLength ) { - }; + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - } + this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - CubeCamera.prototype = Object.create( Object3D.prototype ); - CubeCamera.prototype.constructor = CubeCamera; + }, /** - * @author alteredq / http://alteredqualia.com - * @author WestLangley / http://github.com/WestLangley + * Calculates the focal length from the current .fov and .filmGauge. */ + getFocalLength: function () { - function WebGLRenderTargetCube( width, height, options ) { + var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ); - WebGLRenderTarget.call( this, width, height, options ); + return 0.5 * this.getFilmHeight() / vExtentSlope; - } + }, - WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); - WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; + getEffectiveFOV: function () { - WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; + return MathUtils.RAD2DEG * 2 * Math.atan( + Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom ); - WebGLRenderTargetCube.prototype.fromEquirectangularTexture = function ( renderer, texture ) { + }, - this.texture.type = texture.type; - this.texture.format = texture.format; - this.texture.encoding = texture.encoding; + getFilmWidth: function () { - var scene = new Scene(); + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - var shader = { + }, - uniforms: { - tEquirect: { value: null }, - }, + getFilmHeight: function () { - vertexShader: [ + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - "varying vec3 vWorldDirection;", + }, - "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", + this.aspect = fullWidth / fullHeight; - "}", + if ( this.view === null ) { - "void main() {", + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; - " vWorldDirection = transformDirection( position, modelMatrix );", + } - " #include ", - " #include ", + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - "}" + this.updateProjectionMatrix(); - ].join( '\n' ), + }, - fragmentShader: [ + clearViewOffset: function () { - "uniform sampler2D tEquirect;", + if ( this.view !== null ) { - "varying vec3 vWorldDirection;", + this.view.enabled = false; - "#define RECIPROCAL_PI 0.31830988618", - "#define RECIPROCAL_PI2 0.15915494", + } - "void main() {", + this.updateProjectionMatrix(); - " vec3 direction = normalize( vWorldDirection );", + }, - " vec2 sampleUV;", + updateProjectionMatrix: function () { - " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", + var near = this.near, + top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", + if ( this.view !== null && this.view.enabled ) { - " gl_FragColor = texture2D( tEquirect, sampleUV );", + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - "}" + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - ].join( '\n' ), - }; + } - var material = new ShaderMaterial( { + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - type: 'CubemapFromEquirect', + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); - uniforms: cloneUniforms( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader, - side: BackSide, - blending: NoBlending + this.projectionMatrixInverse.getInverse( this.projectionMatrix ); - } ); + }, - material.uniforms.tEquirect.value = texture; + toJSON: function ( meta ) { - var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material ); + var data = Object3D.prototype.toJSON.call( this, meta ); - scene.add( mesh ); + data.object.fov = this.fov; + data.object.zoom = this.zoom; - var camera = new CubeCamera( 1, 10, 1 ); + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - camera.renderTarget = this; - camera.renderTarget.texture.name = 'CubeCameraTexture'; + data.object.aspect = this.aspect; - camera.update( renderer, scene ); + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - mesh.geometry.dispose(); - mesh.material.dispose(); + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - return this; + return data; - }; + } - /** - * @author alteredq / http://alteredqualia.com/ - */ +} ); - function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { +/** + * Camera for rendering cube maps + * - renders scene into axis-aligned cube + * + * @author alteredq / http://alteredqualia.com/ + */ - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); +var fov = 90, aspect = 1; - this.image = { data: data || null, width: width || 1, height: height || 1 }; +function CubeCamera( near, far, renderTarget ) { - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + Object3D.call( this ); - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; + this.type = 'CubeCamera'; - this.needsUpdate = true; + if ( renderTarget.isWebGLCubeRenderTarget !== true ) { + + console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' ); + return; } - DataTexture.prototype = Object.create( Texture.prototype ); - DataTexture.prototype.constructor = DataTexture; + this.renderTarget = renderTarget; - DataTexture.prototype.isDataTexture = true; + var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); + cameraPX.layers = this.layers; + cameraPX.up.set( 0, - 1, 0 ); + cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); + this.add( cameraPX ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); + cameraNX.layers = this.layers; + cameraNX.up.set( 0, - 1, 0 ); + cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); + this.add( cameraNX ); - var _sphere$1 = new Sphere(); - var _vector$5 = new Vector3(); + var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); + cameraPY.layers = this.layers; + cameraPY.up.set( 0, 0, 1 ); + cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); + this.add( cameraPY ); - function Frustum( p0, p1, p2, p3, p4, p5 ) { + var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); + cameraNY.layers = this.layers; + cameraNY.up.set( 0, 0, - 1 ); + cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); + this.add( cameraNY ); - this.planes = [ + var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraPZ.layers = this.layers; + cameraPZ.up.set( 0, - 1, 0 ); + cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); + this.add( cameraPZ ); - ( p0 !== undefined ) ? p0 : new Plane(), - ( p1 !== undefined ) ? p1 : new Plane(), - ( p2 !== undefined ) ? p2 : new Plane(), - ( p3 !== undefined ) ? p3 : new Plane(), - ( p4 !== undefined ) ? p4 : new Plane(), - ( p5 !== undefined ) ? p5 : new Plane() + var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); + cameraNZ.layers = this.layers; + cameraNZ.up.set( 0, - 1, 0 ); + cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); + this.add( cameraNZ ); - ]; + this.update = function ( renderer, scene ) { - } + if ( this.parent === null ) this.updateMatrixWorld(); - Object.assign( Frustum.prototype, { + var currentXrEnabled = renderer.xr.enabled; + var currentRenderTarget = renderer.getRenderTarget(); - set: function ( p0, p1, p2, p3, p4, p5 ) { + renderer.xr.enabled = false; - var planes = this.planes; + var generateMipmaps = renderTarget.texture.generateMipmaps; - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + renderTarget.texture.generateMipmaps = false; - return this; + renderer.setRenderTarget( renderTarget, 0 ); + renderer.render( scene, cameraPX ); - }, + renderer.setRenderTarget( renderTarget, 1 ); + renderer.render( scene, cameraNX ); - clone: function () { + renderer.setRenderTarget( renderTarget, 2 ); + renderer.render( scene, cameraPY ); - return new this.constructor().copy( this ); + renderer.setRenderTarget( renderTarget, 3 ); + renderer.render( scene, cameraNY ); - }, + renderer.setRenderTarget( renderTarget, 4 ); + renderer.render( scene, cameraPZ ); - copy: function ( frustum ) { + renderTarget.texture.generateMipmaps = generateMipmaps; - var planes = this.planes; + renderer.setRenderTarget( renderTarget, 5 ); + renderer.render( scene, cameraNZ ); - for ( var i = 0; i < 6; i ++ ) { + renderer.setRenderTarget( currentRenderTarget ); - planes[ i ].copy( frustum.planes[ i ] ); + renderer.xr.enabled = currentXrEnabled; - } + }; - return this; + this.clear = function ( renderer, color, depth, stencil ) { - }, + var currentRenderTarget = renderer.getRenderTarget(); - setFromMatrix: function ( m ) { + for ( var i = 0; i < 6; i ++ ) { - var planes = this.planes; - var me = m.elements; - var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + renderer.setRenderTarget( renderTarget, i ); - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); + renderer.clear( color, depth, stencil ); - return this; + } - }, + renderer.setRenderTarget( currentRenderTarget ); - intersectsObject: function ( object ) { + }; - var geometry = object.geometry; +} - if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } +CubeCamera.prototype = Object.create( Object3D.prototype ); +CubeCamera.prototype.constructor = CubeCamera; - _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); +/** + * @author alteredq / http://alteredqualia.com + * @author WestLangley / http://github.com/WestLangley + */ - return this.intersectsSphere( _sphere$1 ); +function WebGLCubeRenderTarget( size, options, dummy ) { - }, + if ( Number.isInteger( options ) ) { - intersectsSprite: function ( sprite ) { + console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' ); - _sphere$1.center.set( 0, 0, 0 ); - _sphere$1.radius = 0.7071067811865476; - _sphere$1.applyMatrix4( sprite.matrixWorld ); + options = dummy; - return this.intersectsSphere( _sphere$1 ); + } - }, + WebGLRenderTarget.call( this, size, size, options ); - intersectsSphere: function ( sphere ) { +} - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; +WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype ); +WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget; - for ( var i = 0; i < 6; i ++ ) { +WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; - var distance = planes[ i ].distanceToPoint( center ); +WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) { - if ( distance < negRadius ) { + this.texture.type = texture.type; + this.texture.format = texture.format; + this.texture.encoding = texture.encoding; - return false; + var scene = new Scene(); - } + var shader = { - } + uniforms: { + tEquirect: { value: null }, + }, - return true; + vertexShader: [ - }, + "varying vec3 vWorldDirection;", - intersectsBox: function ( box ) { + "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", - var planes = this.planes; + " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", - for ( var i = 0; i < 6; i ++ ) { + "}", - var plane = planes[ i ]; + "void main() {", - // corner at max distance + " vWorldDirection = transformDirection( position, modelMatrix );", - _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; - _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; - _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; + " #include ", + " #include ", - if ( plane.distanceToPoint( _vector$5 ) < 0 ) { + "}" - return false; + ].join( '\n' ), - } + fragmentShader: [ - } + "uniform sampler2D tEquirect;", - return true; + "varying vec3 vWorldDirection;", - }, + "#include ", - containsPoint: function ( point ) { + "void main() {", - var planes = this.planes; + " vec3 direction = normalize( vWorldDirection );", - for ( var i = 0; i < 6; i ++ ) { + " vec2 sampleUV = equirectUv( direction );", - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + " gl_FragColor = texture2D( tEquirect, sampleUV );", - return false; + "}" - } + ].join( '\n' ), + }; - } + var material = new ShaderMaterial( { - return true; + type: 'CubemapFromEquirect', - } + uniforms: cloneUniforms( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending } ); - var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; + material.uniforms.tEquirect.value = texture; - var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material ); - var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif"; + scene.add( mesh ); - var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif"; + var camera = new CubeCamera( 1, 10, this ); + camera.update( renderer, scene ); - var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + mesh.geometry.dispose(); + mesh.material.dispose(); - var begin_vertex = "vec3 transformed = vec3( position );"; + return this; - var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; +}; - var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif"; +/** + * @author alteredq / http://alteredqualia.com/ + */ - var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; +function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + this.image = { data: data || null, width: width || 1, height: height || 1 }; - var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif"; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif"; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; - var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; + this.needsUpdate = true; - var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; +} - var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; +DataTexture.prototype = Object.create( Texture.prototype ); +DataTexture.prototype.constructor = DataTexture; - var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; +DataTexture.prototype.isDataTexture = true; - var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}"; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / http://clara.io + */ - var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV( sampler2D envMap, vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif"; +var _sphere$1 = new Sphere(); +var _vector$5 = new Vector3(); - var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = normalMatrix * objectTangent;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; +function Frustum( p0, p1, p2, p3, p4, p5 ) { - var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; + this.planes = [ - var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; - - var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; + ]; - var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; +} - var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}"; +Object.assign( Frustum.prototype, { - var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; + set: function ( p0, p1, p2, p3, p4, p5 ) { - var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; + var planes = this.planes; - var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); - var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; + return this; - var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; + }, - var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif"; + clone: function () { - var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif"; + return new this.constructor().copy( this ); - var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + }, - var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; + copy: function ( frustum ) { - var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif"; + var planes = this.planes; - var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif"; + for ( var i = 0; i < 6; i ++ ) { - var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + planes[ i ].copy( frustum.planes[ i ] ); - var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif"; + } - var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif"; + return this; - var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif"; + }, - var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + setFromProjectionMatrix: function ( m ) { - var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; + var planes = this.planes; + var me = m.elements; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = clamp( clearcoatRoughness, 0.04, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif"; + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); - var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + return this; - var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + }, - var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif"; + intersectsObject: function ( object ) { - var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; + var geometry = object.geometry; - var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; + _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); - var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; + return this.intersectsSphere( _sphere$1 ); - var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; + }, - var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif"; + intersectsSprite: function ( sprite ) { - var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; + _sphere$1.center.set( 0, 0, 0 ); + _sphere$1.radius = 0.7071067811865476; + _sphere$1.applyMatrix4( sprite.matrixWorld ); - var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + return this.intersectsSphere( _sphere$1 ); - var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; + }, - var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; + intersectsSphere: function ( sphere ) { - var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif"; + for ( var i = 0; i < 6; i ++ ) { - var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; + var distance = planes[ i ].distanceToPoint( center ); - var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif"; + if ( distance < negRadius ) { - var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; + return false; - var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif"; + } - var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tbool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\t\t\tmapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\t\t#else\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif"; + } - var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; + return true; - var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif"; + }, - var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; + intersectsBox: function ( box ) { - var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpack2HalfToRGBA( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; + var planes = this.planes; - var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + for ( var i = 0; i < 6; i ++ ) { - var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + var plane = planes[ i ]; - var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + // corner at max distance - var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; + _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; - var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; + if ( plane.distanceToPoint( _vector$5 ) < 0 ) { - var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + return false; - var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpack2HalfToRGBA( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = ( floor( uv * size - 0.5 ) + 0.5 ) * texelSize;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; + } - var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; + } - var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif"; + return true; - var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}"; + }, - var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + containsPoint: function ( point ) { - var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; + var planes = this.planes; - var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + for ( var i = 0; i < 6; i ++ ) { - var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + return false; - var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + } - var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + } - var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}"; + return true; - var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; + } - var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; +} ); - var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; +/** + * Uniforms library for shared webgl shaders + */ - var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; +var UniformsLib = { - var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; + common: { - var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, - var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; + map: { value: null }, + uvTransform: { value: new Matrix3() }, + uv2Transform: { value: new Matrix3() }, - var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; + alphaMap: { value: null }, - var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + }, - var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; + specularmap: { - var cube_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; + specularMap: { value: null }, - var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}"; + }, - var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + envmap: { - var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, + refractionRatio: { value: 0.98 }, + maxMipLevel: { value: 0 } - var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; + }, - var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; + aomap: { - var equirect_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; + aoMap: { value: null }, + aoMapIntensity: { value: 1 } - var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + }, - var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + lightmap: { - var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + lightMap: { value: null }, + lightMapIntensity: { value: 1 } - var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + }, - var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + emissivemap: { - var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + emissiveMap: { value: null } - var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + }, - var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; + bumpmap: { - var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + bumpMap: { value: null }, + bumpScale: { value: 1 } - var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + }, - var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + normalmap: { - var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; + normalMap: { value: null }, + normalScale: { value: new Vector2( 1, 1 ) } - var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}"; + }, - var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; + displacementmap: { - var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } - var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; + }, - var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n}"; + roughnessmap: { - var shadow_vert = "#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; + roughnessMap: { value: null } - var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}"; + }, - var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; + metalnessmap: { - var ShaderChunk = { - alphamap_fragment: alphamap_fragment, - alphamap_pars_fragment: alphamap_pars_fragment, - alphatest_fragment: alphatest_fragment, - aomap_fragment: aomap_fragment, - aomap_pars_fragment: aomap_pars_fragment, - begin_vertex: begin_vertex, - beginnormal_vertex: beginnormal_vertex, - bsdfs: bsdfs, - bumpmap_pars_fragment: bumpmap_pars_fragment, - clipping_planes_fragment: clipping_planes_fragment, - clipping_planes_pars_fragment: clipping_planes_pars_fragment, - clipping_planes_pars_vertex: clipping_planes_pars_vertex, - clipping_planes_vertex: clipping_planes_vertex, - color_fragment: color_fragment, - color_pars_fragment: color_pars_fragment, - color_pars_vertex: color_pars_vertex, - color_vertex: color_vertex, - common: common, - cube_uv_reflection_fragment: cube_uv_reflection_fragment, - defaultnormal_vertex: defaultnormal_vertex, - displacementmap_pars_vertex: displacementmap_pars_vertex, - displacementmap_vertex: displacementmap_vertex, - emissivemap_fragment: emissivemap_fragment, - emissivemap_pars_fragment: emissivemap_pars_fragment, - encodings_fragment: encodings_fragment, - encodings_pars_fragment: encodings_pars_fragment, - envmap_fragment: envmap_fragment, - envmap_common_pars_fragment: envmap_common_pars_fragment, - envmap_pars_fragment: envmap_pars_fragment, - envmap_pars_vertex: envmap_pars_vertex, - envmap_physical_pars_fragment: envmap_physical_pars_fragment, - envmap_vertex: envmap_vertex, - fog_vertex: fog_vertex, - fog_pars_vertex: fog_pars_vertex, - fog_fragment: fog_fragment, - fog_pars_fragment: fog_pars_fragment, - gradientmap_pars_fragment: gradientmap_pars_fragment, - lightmap_fragment: lightmap_fragment, - lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_vertex: lights_lambert_vertex, - lights_pars_begin: lights_pars_begin, - lights_phong_fragment: lights_phong_fragment, - lights_phong_pars_fragment: lights_phong_pars_fragment, - lights_physical_fragment: lights_physical_fragment, - lights_physical_pars_fragment: lights_physical_pars_fragment, - lights_fragment_begin: lights_fragment_begin, - lights_fragment_maps: lights_fragment_maps, - lights_fragment_end: lights_fragment_end, - logdepthbuf_fragment: logdepthbuf_fragment, - logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, - logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, - logdepthbuf_vertex: logdepthbuf_vertex, - map_fragment: map_fragment, - map_pars_fragment: map_pars_fragment, - map_particle_fragment: map_particle_fragment, - map_particle_pars_fragment: map_particle_pars_fragment, - metalnessmap_fragment: metalnessmap_fragment, - metalnessmap_pars_fragment: metalnessmap_pars_fragment, - morphnormal_vertex: morphnormal_vertex, - morphtarget_pars_vertex: morphtarget_pars_vertex, - morphtarget_vertex: morphtarget_vertex, - normal_fragment_begin: normal_fragment_begin, - normal_fragment_maps: normal_fragment_maps, - normalmap_pars_fragment: normalmap_pars_fragment, - clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, - clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, - clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment, - packing: packing, - premultiplied_alpha_fragment: premultiplied_alpha_fragment, - project_vertex: project_vertex, - dithering_fragment: dithering_fragment, - dithering_pars_fragment: dithering_pars_fragment, - roughnessmap_fragment: roughnessmap_fragment, - roughnessmap_pars_fragment: roughnessmap_pars_fragment, - shadowmap_pars_fragment: shadowmap_pars_fragment, - shadowmap_pars_vertex: shadowmap_pars_vertex, - shadowmap_vertex: shadowmap_vertex, - shadowmask_pars_fragment: shadowmask_pars_fragment, - skinbase_vertex: skinbase_vertex, - skinning_pars_vertex: skinning_pars_vertex, - skinning_vertex: skinning_vertex, - skinnormal_vertex: skinnormal_vertex, - specularmap_fragment: specularmap_fragment, - specularmap_pars_fragment: specularmap_pars_fragment, - tonemapping_fragment: tonemapping_fragment, - tonemapping_pars_fragment: tonemapping_pars_fragment, - uv_pars_fragment: uv_pars_fragment, - uv_pars_vertex: uv_pars_vertex, - uv_vertex: uv_vertex, - uv2_pars_fragment: uv2_pars_fragment, - uv2_pars_vertex: uv2_pars_vertex, - uv2_vertex: uv2_vertex, - worldpos_vertex: worldpos_vertex, - - background_frag: background_frag, - background_vert: background_vert, - cube_frag: cube_frag, - cube_vert: cube_vert, - depth_frag: depth_frag, - depth_vert: depth_vert, - distanceRGBA_frag: distanceRGBA_frag, - distanceRGBA_vert: distanceRGBA_vert, - equirect_frag: equirect_frag, - equirect_vert: equirect_vert, - linedashed_frag: linedashed_frag, - linedashed_vert: linedashed_vert, - meshbasic_frag: meshbasic_frag, - meshbasic_vert: meshbasic_vert, - meshlambert_frag: meshlambert_frag, - meshlambert_vert: meshlambert_vert, - meshmatcap_frag: meshmatcap_frag, - meshmatcap_vert: meshmatcap_vert, - meshphong_frag: meshphong_frag, - meshphong_vert: meshphong_vert, - meshphysical_frag: meshphysical_frag, - meshphysical_vert: meshphysical_vert, - normal_frag: normal_frag, - normal_vert: normal_vert, - points_frag: points_frag, - points_vert: points_vert, - shadow_frag: shadow_frag, - shadow_vert: shadow_vert, - sprite_frag: sprite_frag, - sprite_vert: sprite_vert - }; + metalnessMap: { value: null } - /** - * Uniforms library for shared webgl shaders - */ + }, - var UniformsLib = { + gradientmap: { - common: { + gradientMap: { value: null } - diffuse: { value: new Color( 0xeeeeee ) }, - opacity: { value: 1.0 }, + }, - map: { value: null }, - uvTransform: { value: new Matrix3() }, + fog: { - alphaMap: { value: null }, + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: new Color( 0xffffff ) } - }, + }, - specularmap: { + lights: { - specularMap: { value: null }, + ambientLightColor: { value: [] }, - }, + lightProbe: { value: [] }, - envmap: { + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, - envMap: { value: null }, - flipEnvMap: { value: - 1 }, - reflectivity: { value: 1.0 }, - refractionRatio: { value: 0.98 }, - maxMipLevel: { value: 0 } + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, - aomap: { + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, - aoMap: { value: null }, - aoMapIntensity: { value: 1 } + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - }, + spotShadowMap: { value: [] }, + spotShadowMatrix: { value: [] }, - lightmap: { + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, - lightMap: { value: null }, - lightMapIntensity: { value: 1 } + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, - }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, - emissivemap: { + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, - emissiveMap: { value: null } + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } } - }, + }, - bumpmap: { + points: { - bumpMap: { value: null }, - bumpScale: { value: 1 } + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + alphaMap: { value: null }, + uvTransform: { value: new Matrix3() } - }, + }, - normalmap: { + sprite: { - normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, + center: { value: new Vector2( 0.5, 0.5 ) }, + rotation: { value: 0.0 }, + map: { value: null }, + alphaMap: { value: null }, + uvTransform: { value: new Matrix3() } - }, + } - displacementmap: { +}; - displacementMap: { value: null }, - displacementScale: { value: 1 }, - displacementBias: { value: 0 } +/** + * @author mrdoob / http://mrdoob.com/ + */ - }, +function WebGLAnimation() { - roughnessmap: { + var context = null; + var isAnimating = false; + var animationLoop = null; - roughnessMap: { value: null } + function onAnimationFrame( time, frame ) { - }, + if ( isAnimating === false ) return; - metalnessmap: { + animationLoop( time, frame ); - metalnessMap: { value: null } + context.requestAnimationFrame( onAnimationFrame ); - }, + } - gradientmap: { + return { - gradientMap: { value: null } + start: function () { - }, + if ( isAnimating === true ) return; + if ( animationLoop === null ) return; - fog: { + context.requestAnimationFrame( onAnimationFrame ); - fogDensity: { value: 0.00025 }, - fogNear: { value: 1 }, - fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + isAnimating = true; }, - lights: { - - ambientLightColor: { value: [] }, - - lightProbe: { value: [] }, - - directionalLights: { value: [], properties: { - direction: {}, - color: {}, - - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } }, - - directionalShadowMap: { value: [] }, - directionalShadowMatrix: { value: [] }, - - spotLights: { value: [], properties: { - color: {}, - position: {}, - direction: {}, - distance: {}, - coneCos: {}, - penumbraCos: {}, - decay: {}, - - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } }, - - spotShadowMap: { value: [] }, - spotShadowMatrix: { value: [] }, - - pointLights: { value: [], properties: { - color: {}, - position: {}, - decay: {}, - distance: {}, - - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {}, - shadowCameraNear: {}, - shadowCameraFar: {} - } }, - - pointShadowMap: { value: [] }, - pointShadowMatrix: { value: [] }, - - hemisphereLights: { value: [], properties: { - direction: {}, - skyColor: {}, - groundColor: {} - } }, - - // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src - rectAreaLights: { value: [], properties: { - color: {}, - position: {}, - width: {}, - height: {} - } } + stop: function () { + + isAnimating = false; }, - points: { + setAnimationLoop: function ( callback ) { - diffuse: { value: new Color( 0xeeeeee ) }, - opacity: { value: 1.0 }, - size: { value: 1.0 }, - scale: { value: 1.0 }, - map: { value: null }, - alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + animationLoop = callback; }, - sprite: { + setContext: function ( value ) { - diffuse: { value: new Color( 0xeeeeee ) }, - opacity: { value: 1.0 }, - center: { value: new Vector2( 0.5, 0.5 ) }, - rotation: { value: 0.0 }, - map: { value: null }, - alphaMap: { value: null }, - uvTransform: { value: new Matrix3() } + context = value; } }; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ - - var ShaderLib = { +} - basic: { +/** + * @author mrdoob / http://mrdoob.com/ + */ - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.specularmap, - UniformsLib.envmap, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.fog - ] ), +function WebGLAttributes( gl, capabilities ) { - vertexShader: ShaderChunk.meshbasic_vert, - fragmentShader: ShaderChunk.meshbasic_frag - - }, + var isWebGL2 = capabilities.isWebGL2; - lambert: { - - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.specularmap, - UniformsLib.envmap, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) } - } - ] ), + var buffers = new WeakMap(); - vertexShader: ShaderChunk.meshlambert_vert, - fragmentShader: ShaderChunk.meshlambert_frag + function createBuffer( attribute, bufferType ) { - }, + var array = attribute.array; + var usage = attribute.usage; - phong: { - - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.specularmap, - UniformsLib.envmap, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - UniformsLib.gradientmap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, - shininess: { value: 30 } - } - ] ), + var buffer = gl.createBuffer(); - vertexShader: ShaderChunk.meshphong_vert, - fragmentShader: ShaderChunk.meshphong_frag + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); - }, + attribute.onUploadCallback(); - standard: { - - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.envmap, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - UniformsLib.roughnessmap, - UniformsLib.metalnessmap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) }, - roughness: { value: 0.5 }, - metalness: { value: 0.5 }, - envMapIntensity: { value: 1 } // temporary - } - ] ), + var type = 5126; - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag + if ( array instanceof Float32Array ) { - }, + type = 5126; - matcap: { + } else if ( array instanceof Float64Array ) { - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - UniformsLib.fog, - { - matcap: { value: null } - } - ] ), + console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); - vertexShader: ShaderChunk.meshmatcap_vert, - fragmentShader: ShaderChunk.meshmatcap_frag + } else if ( array instanceof Uint16Array ) { - }, + type = 5123; - points: { + } else if ( array instanceof Int16Array ) { - uniforms: mergeUniforms( [ - UniformsLib.points, - UniformsLib.fog - ] ), + type = 5122; - vertexShader: ShaderChunk.points_vert, - fragmentShader: ShaderChunk.points_frag + } else if ( array instanceof Uint32Array ) { - }, + type = 5125; - dashed: { + } else if ( array instanceof Int32Array ) { - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.fog, - { - scale: { value: 1 }, - dashSize: { value: 1 }, - totalSize: { value: 2 } - } - ] ), + type = 5124; - vertexShader: ShaderChunk.linedashed_vert, - fragmentShader: ShaderChunk.linedashed_frag + } else if ( array instanceof Int8Array ) { - }, + type = 5120; - depth: { + } else if ( array instanceof Uint8Array ) { - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.displacementmap - ] ), + type = 5121; - vertexShader: ShaderChunk.depth_vert, - fragmentShader: ShaderChunk.depth_frag + } - }, + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; - normal: { + } - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - { - opacity: { value: 1.0 } - } - ] ), + function updateBuffer( buffer, attribute, bufferType ) { - vertexShader: ShaderChunk.normal_vert, - fragmentShader: ShaderChunk.normal_frag + var array = attribute.array; + var updateRange = attribute.updateRange; - }, + gl.bindBuffer( bufferType, buffer ); - sprite: { + if ( updateRange.count === - 1 ) { - uniforms: mergeUniforms( [ - UniformsLib.sprite, - UniformsLib.fog - ] ), + // Not using update ranges - vertexShader: ShaderChunk.sprite_vert, - fragmentShader: ShaderChunk.sprite_frag + gl.bufferSubData( bufferType, 0, array ); - }, + } else { - background: { + if ( isWebGL2 ) { - uniforms: { - uvTransform: { value: new Matrix3() }, - t2D: { value: null }, - }, + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array, updateRange.offset, updateRange.count ); - vertexShader: ShaderChunk.background_vert, - fragmentShader: ShaderChunk.background_frag + } else { - }, - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); - cube: { + } - uniforms: { - tCube: { value: null }, - tFlip: { value: - 1 }, - opacity: { value: 1.0 } - }, + updateRange.count = - 1; // reset range - vertexShader: ShaderChunk.cube_vert, - fragmentShader: ShaderChunk.cube_frag + } - }, + } - equirect: { + // - uniforms: { - tEquirect: { value: null }, - }, + function get( attribute ) { - vertexShader: ShaderChunk.equirect_vert, - fragmentShader: ShaderChunk.equirect_frag + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - }, + return buffers.get( attribute ); - distanceRGBA: { + } - uniforms: mergeUniforms( [ - UniformsLib.common, - UniformsLib.displacementmap, - { - referencePosition: { value: new Vector3() }, - nearDistance: { value: 1 }, - farDistance: { value: 1000 } - } - ] ), + function remove( attribute ) { - vertexShader: ShaderChunk.distanceRGBA_vert, - fragmentShader: ShaderChunk.distanceRGBA_frag + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - }, + var data = buffers.get( attribute ); - shadow: { + if ( data ) { - uniforms: mergeUniforms( [ - UniformsLib.lights, - UniformsLib.fog, - { - color: { value: new Color( 0x00000 ) }, - opacity: { value: 1.0 } - } ] ), + gl.deleteBuffer( data.buffer ); - vertexShader: ShaderChunk.shadow_vert, - fragmentShader: ShaderChunk.shadow_frag + buffers.delete( attribute ); } - }; - - ShaderLib.physical = { - - uniforms: mergeUniforms( [ - ShaderLib.standard.uniforms, - { - transparency: { value: 0 }, - clearcoat: { value: 0 }, - clearcoatRoughness: { value: 0 }, - sheen: { value: new Color( 0x000000 ) }, - clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, - clearcoatNormalMap: { value: null }, - } - ] ), - - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag + } - }; + function update( attribute, bufferType ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - function WebGLAnimation() { + var data = buffers.get( attribute ); - var context = null; - var isAnimating = false; - var animationLoop = null; + if ( data === undefined ) { - function onAnimationFrame( time, frame ) { + buffers.set( attribute, createBuffer( attribute, bufferType ) ); - if ( isAnimating === false ) { return; } + } else if ( data.version < attribute.version ) { - animationLoop( time, frame ); + updateBuffer( data.buffer, attribute, bufferType ); - context.requestAnimationFrame( onAnimationFrame ); + data.version = attribute.version; } - return { - - start: function () { + } - if ( isAnimating === true ) { return; } - if ( animationLoop === null ) { return; } + return { - context.requestAnimationFrame( onAnimationFrame ); + get: get, + remove: remove, + update: update - isAnimating = true; + }; - }, +} - stop: function () { +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - isAnimating = false; +// PlaneGeometry - }, +function PlaneGeometry( width, height, widthSegments, heightSegments ) { - setAnimationLoop: function ( callback ) { + Geometry.call( this ); - animationLoop = callback; + this.type = 'PlaneGeometry'; - }, + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - setContext: function ( value ) { + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + this.mergeVertices(); - context = value; +} - } +PlaneGeometry.prototype = Object.create( Geometry.prototype ); +PlaneGeometry.prototype.constructor = PlaneGeometry; - }; +// PlaneBufferGeometry - } +function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + BufferGeometry.call( this ); - function WebGLAttributes( gl ) { + this.type = 'PlaneBufferGeometry'; - var buffers = new WeakMap(); + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - function createBuffer( attribute, bufferType ) { + width = width || 1; + height = height || 1; - var array = attribute.array; - var usage = attribute.usage; + var width_half = width / 2; + var height_half = height / 2; - var buffer = gl.createBuffer(); + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - gl.bindBuffer( bufferType, buffer ); - gl.bufferData( bufferType, array, usage ); + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - attribute.onUploadCallback(); + var segment_width = width / gridX; + var segment_height = height / gridY; - var type = 5126; + var ix, iy; - if ( array instanceof Float32Array ) { + // buffers - type = 5126; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - } else if ( array instanceof Float64Array ) { + // generate vertices, normals and uvs - console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); + for ( iy = 0; iy < gridY1; iy ++ ) { - } else if ( array instanceof Uint16Array ) { + var y = iy * segment_height - height_half; - type = 5123; + for ( ix = 0; ix < gridX1; ix ++ ) { - } else if ( array instanceof Int16Array ) { + var x = ix * segment_width - width_half; - type = 5122; + vertices.push( x, - y, 0 ); - } else if ( array instanceof Uint32Array ) { + normals.push( 0, 0, 1 ); - type = 5125; + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); - } else if ( array instanceof Int32Array ) { + } - type = 5124; + } - } else if ( array instanceof Int8Array ) { + // indices - type = 5120; + for ( iy = 0; iy < gridY; iy ++ ) { - } else if ( array instanceof Uint8Array ) { + for ( ix = 0; ix < gridX; ix ++ ) { - type = 5121; + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - } + // faces - return { - buffer: buffer, - type: type, - bytesPerElement: array.BYTES_PER_ELEMENT, - version: attribute.version - }; + indices.push( a, b, d ); + indices.push( b, c, d ); } - function updateBuffer( buffer, attribute, bufferType ) { + } - var array = attribute.array; - var updateRange = attribute.updateRange; + // build geometry - gl.bindBuffer( bufferType, buffer ); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( updateRange.count === - 1 ) { +} - // Not using update ranges +PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - gl.bufferSubData( bufferType, 0, array ); +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; - } else { +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; - gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, - array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); +var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif"; - updateRange.count = - 1; // reset range +var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif"; - } +var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; - } +var begin_vertex = "vec3 transformed = vec3( position );"; - // +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; - function get( attribute ) { +var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif"; - if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; - return buffers.get( attribute ); +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; - } +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; - function remove( attribute ) { +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif"; - if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif"; - var data = buffers.get( attribute ); +var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; - if ( data ) { +var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - gl.deleteBuffer( data.buffer ); +var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - buffers.delete( attribute ); +var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; - } +var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}"; - } +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x); } else if (face == 1.0) {\n uv = vec2(-direction.x, -direction.z) / abs(direction.y); } else if (face == 2.0) {\n uv = vec2(-direction.x, direction.y) / abs(direction.z); } else if (face == 3.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x); } else if (face == 4.0) {\n uv = vec2(-direction.x, direction.z) / abs(direction.y); } else {\n uv = vec2(direction.x, direction.y) / abs(direction.z); }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif"; - function update( attribute, bufferType ) { +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; - if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; - var data = buffers.get( attribute ); +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; - if ( data === undefined ) { +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; - buffers.set( attribute, createBuffer( attribute, bufferType ) ); +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; - } else if ( data.version < attribute.version ) { +var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; - updateBuffer( data.buffer, attribute, bufferType ); +var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}"; - data.version = attribute.version; +var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec2 sampleUV = equirectUv( reflectVec );\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; - } +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; - } +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; - return { +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; - get: get, - remove: remove, - update: update +var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; - }; +var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif"; - } +var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif"; - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ +var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; - // PlaneGeometry +var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; - function PlaneGeometry( width, height, widthSegments, heightSegments ) { +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}"; - Geometry.call( this ); +var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif"; - this.type = 'PlaneGeometry'; +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; +var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif"; - this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - this.mergeVertices(); +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif"; - } +var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV = equirectUv( reflectVec );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif"; - PlaneGeometry.prototype = Object.create( Geometry.prototype ); - PlaneGeometry.prototype.constructor = PlaneGeometry; +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; - // PlaneBufferGeometry +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; - function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; - BufferGeometry.call( this ); +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; - this.type = 'PlaneBufferGeometry'; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif"; - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; - width = width || 1; - height = height || 1; +var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; - var width_half = width / 2; - var height_half = height / 2; +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif"; - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; +var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; - var segment_width = width / gridX; - var segment_height = height / gridY; +var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; - var ix, iy; +var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; - // buffers +var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; +var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif"; - // generate vertices, normals and uvs +var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; - for ( iy = 0; iy < gridY1; iy ++ ) { +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; - var y = iy * segment_height - height_half; +var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; - for ( ix = 0; ix < gridX1; ix ++ ) { +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; - var x = ix * segment_width - width_half; +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; - vertices.push( x, - y, 0 ); +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif"; - normals.push( 0, 0, 1 ); +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; - uvs.push( ix / gridX ); - uvs.push( 1 - ( iy / gridY ) ); +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif"; - } +var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; - } +var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif"; - // indices +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif"; - for ( iy = 0; iy < gridY; iy ++ ) { +var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; - for ( ix = 0; ix < gridX; ix ++ ) { +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif"; - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; - // faces +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; - indices.push( a, b, d ); - indices.push( b, c, d ); +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; - } +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; - } +var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; - // build geometry +var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; - } +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; - PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; +var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; - /** - * @author mrdoob / http://mrdoob.com/ - */ +var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; - function WebGLBackground( renderer, state, objects, premultipliedAlpha ) { +var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif"; - var clearColor = new Color( 0x000000 ); - var clearAlpha = 0; +var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}"; - var planeMesh; - var boxMesh; - // Store the current background texture and its `version` - // so we can recompile the material accordingly. - var currentBackground = null; - var currentBackgroundVersion = 0; +var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; - function render( renderList, scene, camera, forceClear ) { +var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; - var background = scene.background; +var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; - // Ignore background in AR - // TODO: Reconsider this. +var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; - var vr = renderer.vr; - var session = vr.getSession && vr.getSession(); +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; - if ( session && session.environmentBlendMode === 'additive' ) { +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; - background = null; +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; - } +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}"; - if ( background === null ) { +var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; - setClear( clearColor, clearAlpha ); - currentBackground = null; - currentBackgroundVersion = 0; +var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; - } else if ( background && background.isColor ) { +var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; - setClear( background, 1 ); - forceClear = true; - currentBackground = null; - currentBackgroundVersion = 0; +var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; - } +var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; - if ( renderer.autoClear || forceClear ) { +var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; - renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; - } +var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; - if ( background && ( background.isCubeTexture || background.isWebGLRenderTargetCube ) ) { +var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; - if ( boxMesh === undefined ) { +var cube_frag = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; - boxMesh = new Mesh( - new BoxBufferGeometry( 1, 1, 1 ), - new ShaderMaterial( { - type: 'BackgroundCubeMaterial', - uniforms: cloneUniforms( ShaderLib.cube.uniforms ), - vertexShader: ShaderLib.cube.vertexShader, - fragmentShader: ShaderLib.cube.fragmentShader, - side: BackSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); +var cube_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; - boxMesh.geometry.deleteAttribute( 'normal' ); - boxMesh.geometry.deleteAttribute( 'uv' ); +var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}"; - boxMesh.onBeforeRender = function ( renderer, scene, camera ) { +var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}"; - this.matrixWorld.copyPosition( camera.matrixWorld ); +var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; - }; +var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; - // enable code injection for non-built-in material - Object.defineProperty( boxMesh.material, 'map', { +var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; - get: function () { +var equirect_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; - return this.uniforms.tCube.value; +var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; - } +var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - } ); +var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - objects.update( boxMesh ); +var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - } +var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - var texture = background.isWebGLRenderTargetCube ? background.texture : background; - boxMesh.material.uniforms.tCube.value = texture; - boxMesh.material.uniforms.tFlip.value = ( background.isWebGLRenderTargetCube ) ? 1 : - 1; +var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - if ( currentBackground !== background || - currentBackgroundVersion !== texture.version ) { +var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - boxMesh.material.needsUpdate = true; +var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; - currentBackground = background; - currentBackgroundVersion = texture.version; +var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - } +var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; - // push to the pre-sorted opaque render list - renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); - - } else if ( background && background.isTexture ) { - - if ( planeMesh === undefined ) { - - planeMesh = new Mesh( - new PlaneBufferGeometry( 2, 2 ), - new ShaderMaterial( { - type: 'BackgroundMaterial', - uniforms: cloneUniforms( ShaderLib.background.uniforms ), - vertexShader: ShaderLib.background.vertexShader, - fragmentShader: ShaderLib.background.fragmentShader, - side: FrontSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); +var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - planeMesh.geometry.deleteAttribute( 'normal' ); +var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; - // enable code injection for non-built-in material - Object.defineProperty( planeMesh.material, 'map', { +var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - get: function () { +var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; - return this.uniforms.t2D.value; +var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}"; - } +var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; - } ); +var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; - objects.update( planeMesh ); +var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; - } +var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; - planeMesh.material.uniforms.t2D.value = background; +var shadow_vert = "#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; - if ( background.matrixAutoUpdate === true ) { +var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}"; - background.updateMatrix(); +var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; - } +var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_common_pars_fragment: envmap_common_pars_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_physical_pars_fragment: envmap_physical_pars_fragment, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars_begin: lights_pars_begin, + lights_toon_fragment: lights_toon_fragment, + lights_toon_pars_fragment: lights_toon_pars_fragment, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normalmap_pars_fragment: normalmap_pars_fragment, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, + clearcoat_pars_fragment: clearcoat_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, + + background_frag: background_frag, + background_vert: background_vert, + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshmatcap_frag: meshmatcap_frag, + meshmatcap_vert: meshmatcap_vert, + meshtoon_frag: meshtoon_frag, + meshtoon_vert: meshtoon_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert, + sprite_frag: sprite_frag, + sprite_vert: sprite_vert +}; + +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + */ + +var ShaderLib = { + + basic: { - planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), - if ( currentBackground !== background || - currentBackgroundVersion !== background.version ) { + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag - planeMesh.material.needsUpdate = true; + }, - currentBackground = background; - currentBackgroundVersion = background.version; + lambert: { - } + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) } + } + ] ), + + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, - // push to the pre-sorted opaque render list - renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); + phong: { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) }, + specular: { value: new Color( 0x111111 ) }, + shininess: { value: 30 } } + ] ), - } + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag - function setClear( color, alpha ) { + }, - state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha ); + standard: { - } + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) }, + roughness: { value: 1.0 }, + metalness: { value: 0.0 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), - return { + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - getClearColor: function () { + }, - return clearColor; + toon: { - }, - setClearColor: function ( color, alpha ) { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) }, + specular: { value: new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), - clearColor.set( color ); - clearAlpha = alpha !== undefined ? alpha : 1; - setClear( clearColor, clearAlpha ); + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag - }, - getClearAlpha: function () { + }, - return clearAlpha; + matcap: { - }, - setClearAlpha: function ( alpha ) { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ] ), - clearAlpha = alpha; - setClear( clearColor, clearAlpha ); + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag - }, - render: render + }, - }; + points: { - } + uniforms: mergeUniforms( [ + UniformsLib.points, + UniformsLib.fog + ] ), - /** - * @author mrdoob / http://mrdoob.com/ - */ + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag - function WebGLBufferRenderer( gl, extensions, info, capabilities ) { + }, - var isWebGL2 = capabilities.isWebGL2; + dashed: { - var mode; + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), - function setMode( value ) { + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag - mode = value; + }, - } + depth: { - function render( start, count ) { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), - gl.drawArrays( mode, start, count ); + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag - info.update( count, mode ); + }, - } + normal: { - function renderInstances( geometry, start, count, primcount ) { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), - if ( primcount === 0 ) { return; } + vertexShader: ShaderChunk.normal_vert, + fragmentShader: ShaderChunk.normal_frag - var extension, methodName; + }, - if ( isWebGL2 ) { + sprite: { - extension = gl; - methodName = 'drawArraysInstanced'; + uniforms: mergeUniforms( [ + UniformsLib.sprite, + UniformsLib.fog + ] ), - } else { + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag - extension = extensions.get( 'ANGLE_instanced_arrays' ); - methodName = 'drawArraysInstancedANGLE'; + }, - if ( extension === null ) { + background: { - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + uniforms: { + uvTransform: { value: new Matrix3() }, + t2D: { value: null }, + }, - } + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag - } + }, + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - extension[ methodName ]( mode, start, count, primcount ); + cube: { - info.update( count, mode, primcount ); + uniforms: mergeUniforms( [ + UniformsLib.envmap, + { + opacity: { value: 1.0 } + } + ] ), - } + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag - // + }, - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + equirect: { - } + uniforms: { + tEquirect: { value: null }, + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag - function WebGLCapabilities( gl, extensions, parameters ) { + }, - var maxAnisotropy; + distanceRGBA: { - function getMaxAnisotropy() { + uniforms: mergeUniforms( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), - if ( maxAnisotropy !== undefined ) { return maxAnisotropy; } + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + }, - if ( extension !== null ) { + shadow: { - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); + uniforms: mergeUniforms( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), - } else { + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag - maxAnisotropy = 0; + } - } +}; - return maxAnisotropy; +ShaderLib.physical = { + uniforms: mergeUniforms( [ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, + clearcoatNormalMap: { value: null }, + sheen: { value: new Color( 0x000000 ) }, + transparency: { value: 0 }, } + ] ), - function getMaxPrecision( precision ) { + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - if ( precision === 'highp' ) { +}; - if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 && - gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - return 'highp'; +function WebGLBackground( renderer, state, objects, premultipliedAlpha ) { - } + var clearColor = new Color( 0x000000 ); + var clearAlpha = 0; - precision = 'mediump'; + var planeMesh; + var boxMesh; - } + var currentBackground = null; + var currentBackgroundVersion = 0; + var currentTonemapping = null; - if ( precision === 'mediump' ) { + function render( renderList, scene, camera, forceClear ) { - if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 && - gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) { + var background = scene.background; - return 'mediump'; + // Ignore background in AR + // TODO: Reconsider this. - } + var xr = renderer.xr; + var session = xr.getSession && xr.getSession(); - } + if ( session && session.environmentBlendMode === 'additive' ) { - return 'lowp'; + background = null; } - /* eslint-disable no-undef */ - var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) || - ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext ); - /* eslint-enable no-undef */ + if ( background === null ) { - var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - var maxPrecision = getMaxPrecision( precision ); + setClear( clearColor, clearAlpha ); - if ( maxPrecision !== precision ) { + } else if ( background && background.isColor ) { - console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); - precision = maxPrecision; + setClear( background, 1 ); + forceClear = true; } - var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; - - var maxTextures = gl.getParameter( 34930 ); - var maxVertexTextures = gl.getParameter( 35660 ); - var maxTextureSize = gl.getParameter( 3379 ); - var maxCubemapSize = gl.getParameter( 34076 ); - - var maxAttributes = gl.getParameter( 34921 ); - var maxVertexUniforms = gl.getParameter( 36347 ); - var maxVaryings = gl.getParameter( 36348 ); - var maxFragmentUniforms = gl.getParameter( 36349 ); + if ( renderer.autoClear || forceClear ) { - var vertexTextures = maxVertexTextures > 0; - var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' ); - var floatVertexTextures = vertexTextures && floatFragmentTextures; + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); - var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0; + } - return { + if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) { - isWebGL2: isWebGL2, + if ( boxMesh === undefined ) { - getMaxAnisotropy: getMaxAnisotropy, - getMaxPrecision: getMaxPrecision, + boxMesh = new Mesh( + new BoxBufferGeometry( 1, 1, 1 ), + new ShaderMaterial( { + type: 'BackgroundCubeMaterial', + uniforms: cloneUniforms( ShaderLib.cube.uniforms ), + vertexShader: ShaderLib.cube.vertexShader, + fragmentShader: ShaderLib.cube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); - precision: precision, - logarithmicDepthBuffer: logarithmicDepthBuffer, + boxMesh.geometry.deleteAttribute( 'normal' ); + boxMesh.geometry.deleteAttribute( 'uv' ); - maxTextures: maxTextures, - maxVertexTextures: maxVertexTextures, - maxTextureSize: maxTextureSize, - maxCubemapSize: maxCubemapSize, + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { - maxAttributes: maxAttributes, - maxVertexUniforms: maxVertexUniforms, - maxVaryings: maxVaryings, - maxFragmentUniforms: maxFragmentUniforms, + this.matrixWorld.copyPosition( camera.matrixWorld ); - vertexTextures: vertexTextures, - floatFragmentTextures: floatFragmentTextures, - floatVertexTextures: floatVertexTextures, + }; - maxSamples: maxSamples + // enable code injection for non-built-in material + Object.defineProperty( boxMesh.material, 'envMap', { - }; + get: function () { - } + return this.uniforms.envMap.value; - /** - * @author tschw - */ + } - function WebGLClipping() { + } ); - var scope = this, + objects.update( boxMesh ); - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + } - plane = new Plane(), - viewNormalMatrix = new Matrix3(), + var texture = background.isWebGLCubeRenderTarget ? background.texture : background; - uniform = { value: null, needsUpdate: false }; + boxMesh.material.uniforms.envMap.value = texture; + boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1; - this.uniform = uniform; - this.numPlanes = 0; - this.numIntersection = 0; + if ( currentBackground !== background || + currentBackgroundVersion !== texture.version || + currentTonemapping !== renderer.toneMapping ) { - this.init = function ( planes, enableLocalClipping, camera ) { + boxMesh.material.needsUpdate = true; - var enabled = - planes.length !== 0 || - enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || - localClippingEnabled; + currentBackground = background; + currentBackgroundVersion = texture.version; + currentTonemapping = renderer.toneMapping; - localClippingEnabled = enableLocalClipping; + } - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + // push to the pre-sorted opaque render list + renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); - return enabled; + } else if ( background && background.isTexture ) { - }; + if ( planeMesh === undefined ) { - this.beginShadows = function () { + planeMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new ShaderMaterial( { + type: 'BackgroundMaterial', + uniforms: cloneUniforms( ShaderLib.background.uniforms ), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + } ) + ); - renderingShadows = true; - projectPlanes( null ); + planeMesh.geometry.deleteAttribute( 'normal' ); - }; + // enable code injection for non-built-in material + Object.defineProperty( planeMesh.material, 'map', { - this.endShadows = function () { + get: function () { - renderingShadows = false; - resetGlobalState(); + return this.uniforms.t2D.value; - }; + } - this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) { + } ); - if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { + objects.update( planeMesh ); - // there's no local clipping + } - if ( renderingShadows ) { + planeMesh.material.uniforms.t2D.value = background; - // there's no global clipping + if ( background.matrixAutoUpdate === true ) { - projectPlanes( null ); + background.updateMatrix(); - } else { + } - resetGlobalState(); + planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); - } + if ( currentBackground !== background || + currentBackgroundVersion !== background.version || + currentTonemapping !== renderer.toneMapping ) { - } else { + planeMesh.material.needsUpdate = true; - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; - dstArray = cache.clippingState || null; + } - uniform.value = dstArray; // ensure unique state - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + // push to the pre-sorted opaque render list + renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); - for ( var i = 0; i !== lGlobal; ++ i ) { + } - dstArray[ i ] = globalState[ i ]; + } - } + function setClear( color, alpha ) { - cache.clippingState = dstArray; - this.numIntersection = clipIntersection ? this.numPlanes : 0; - this.numPlanes += nGlobal; + state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha ); - } + } + return { - }; + getClearColor: function () { - function resetGlobalState() { + return clearColor; - if ( uniform.value !== globalState ) { + }, + setClearColor: function ( color, alpha ) { - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + clearColor.set( color ); + clearAlpha = alpha !== undefined ? alpha : 1; + setClear( clearColor, clearAlpha ); - } + }, + getClearAlpha: function () { - scope.numPlanes = numGlobalPlanes; - scope.numIntersection = 0; + return clearAlpha; - } + }, + setClearAlpha: function ( alpha ) { - function projectPlanes( planes, camera, dstOffset, skipTransform ) { + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + }, + render: render - if ( nPlanes !== 0 ) { + }; - dstArray = uniform.value; +} - if ( skipTransform !== true || dstArray === null ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; +function WebGLBufferRenderer( gl, extensions, info, capabilities ) { - viewNormalMatrix.getNormalMatrix( viewMatrix ); + var isWebGL2 = capabilities.isWebGL2; - if ( dstArray === null || dstArray.length < flatSize ) { + var mode; - dstArray = new Float32Array( flatSize ); + function setMode( value ) { - } + mode = value; - for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + } - plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + function render( start, count ) { - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + gl.drawArrays( mode, start, count ); - } + info.update( count, mode ); - } + } - uniform.value = dstArray; - uniform.needsUpdate = true; + function renderInstances( geometry, start, count, primcount ) { - } + if ( primcount === 0 ) return; - scope.numPlanes = nPlanes; + var extension, methodName; - return dstArray; + if ( isWebGL2 ) { - } + extension = gl; + methodName = 'drawArraysInstanced'; - } + } else { - /** - * @author mrdoob / http://mrdoob.com/ - */ + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawArraysInstancedANGLE'; - function WebGLExtensions( gl ) { + if ( extension === null ) { - var extensions = {}; + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - return { + } - get: function ( name ) { + } - if ( extensions[ name ] !== undefined ) { + extension[ methodName ]( mode, start, count, primcount ); - return extensions[ name ]; + info.update( count, mode, primcount ); - } + } - var extension; + // - switch ( name ) { + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; +} - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - break; +/** + * @author mrdoob / http://mrdoob.com/ + */ - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - break; +function WebGLCapabilities( gl, extensions, parameters ) { - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + var maxAnisotropy; - default: - extension = gl.getExtension( name ); + function getMaxAnisotropy() { - } + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - if ( extension === null ) { + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + if ( extension !== null ) { - } + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - extensions[ name ] = extension; + } else { - return extension; + maxAnisotropy = 0; - } + } - }; + return maxAnisotropy; } - /** - * @author mrdoob / http://mrdoob.com/ - */ + function getMaxPrecision( precision ) { - function WebGLGeometries( gl, attributes, info ) { + if ( precision === 'highp' ) { - var geometries = new WeakMap(); - var wireframeAttributes = new WeakMap(); + if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 && + gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) { - function onGeometryDispose( event ) { + return 'highp'; - var geometry = event.target; - var buffergeometry = geometries.get( geometry ); + } - if ( buffergeometry.index !== null ) { + precision = 'mediump'; - attributes.remove( buffergeometry.index ); + } - } + if ( precision === 'mediump' ) { - for ( var name in buffergeometry.attributes ) { + if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 && + gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) { - attributes.remove( buffergeometry.attributes[ name ] ); + return 'mediump'; } - geometry.removeEventListener( 'dispose', onGeometryDispose ); + } + + return 'lowp'; - geometries.delete( geometry ); + } - var attribute = wireframeAttributes.get( buffergeometry ); + /* eslint-disable no-undef */ + var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) || + ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext ); + /* eslint-enable no-undef */ - if ( attribute ) { + var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + var maxPrecision = getMaxPrecision( precision ); - attributes.remove( attribute ); - wireframeAttributes.delete( buffergeometry ); + if ( maxPrecision !== precision ) { - } + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; - // + } - info.memory.geometries --; + var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; - } + var maxTextures = gl.getParameter( 34930 ); + var maxVertexTextures = gl.getParameter( 35660 ); + var maxTextureSize = gl.getParameter( 3379 ); + var maxCubemapSize = gl.getParameter( 34076 ); - function get( object, geometry ) { + var maxAttributes = gl.getParameter( 34921 ); + var maxVertexUniforms = gl.getParameter( 36347 ); + var maxVaryings = gl.getParameter( 36348 ); + var maxFragmentUniforms = gl.getParameter( 36349 ); - var buffergeometry = geometries.get( geometry ); + var vertexTextures = maxVertexTextures > 0; + var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' ); + var floatVertexTextures = vertexTextures && floatFragmentTextures; - if ( buffergeometry ) { return buffergeometry; } + var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0; - geometry.addEventListener( 'dispose', onGeometryDispose ); + return { - if ( geometry.isBufferGeometry ) { + isWebGL2: isWebGL2, - buffergeometry = geometry; + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, - } else if ( geometry.isGeometry ) { + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, - if ( geometry._bufferGeometry === undefined ) { + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, - geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, - } + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures, - buffergeometry = geometry._bufferGeometry; + maxSamples: maxSamples - } + }; - geometries.set( geometry, buffergeometry ); +} - info.memory.geometries ++; +/** + * @author tschw + */ - return buffergeometry; +function WebGLClipping() { - } + var scope = this, - function update( geometry ) { + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - var index = geometry.index; - var geometryAttributes = geometry.attributes; + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - if ( index !== null ) { + uniform = { value: null, needsUpdate: false }; - attributes.update( index, 34963 ); + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; - } + this.init = function ( planes, enableLocalClipping, camera ) { - for ( var name in geometryAttributes ) { + var enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; - attributes.update( geometryAttributes[ name ], 34962 ); + localClippingEnabled = enableLocalClipping; - } + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - // morph targets + return enabled; - var morphAttributes = geometry.morphAttributes; + }; - for ( var name in morphAttributes ) { + this.beginShadows = function () { - var array = morphAttributes[ name ]; + renderingShadows = true; + projectPlanes( null ); - for ( var i = 0, l = array.length; i < l; i ++ ) { + }; - attributes.update( array[ i ], 34962 ); + this.endShadows = function () { - } + renderingShadows = false; + resetGlobalState(); - } + }; - } + this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) { - function updateWireframeAttribute( geometry ) { + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { - var indices = []; + // there's no local clipping - var geometryIndex = geometry.index; - var geometryPosition = geometry.attributes.position; - var version = 0; + if ( renderingShadows ) { - if ( geometryIndex !== null ) { + // there's no global clipping - var array = geometryIndex.array; - version = geometryIndex.version; + projectPlanes( null ); - for ( var i = 0, l = array.length; i < l; i += 3 ) { + } else { - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + resetGlobalState(); - indices.push( a, b, b, c, c, a ); + } - } + } else { - } else { + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - var array = geometryPosition.array; - version = geometryPosition.version; + dstArray = cache.clippingState || null; - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + uniform.value = dstArray; // ensure unique state - var a = i + 0; - var b = i + 1; - var c = i + 2; + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - indices.push( a, b, b, c, c, a ); + for ( var i = 0; i !== lGlobal; ++ i ) { - } + dstArray[ i ] = globalState[ i ]; } - var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); - attribute.version = version; + cache.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; - attributes.update( attribute, 34963 ); + } - // - var previousAttribute = wireframeAttributes.get( geometry ); + }; - if ( previousAttribute ) { attributes.remove( previousAttribute ); } + function resetGlobalState() { - // + if ( uniform.value !== globalState ) { - wireframeAttributes.set( geometry, attribute ); + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; } - function getWireframeAttribute( geometry ) { + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + + } - var currentAttribute = wireframeAttributes.get( geometry ); + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - if ( currentAttribute ) { + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - var geometryIndex = geometry.index; + if ( nPlanes !== 0 ) { - if ( geometryIndex !== null ) { + dstArray = uniform.value; - // if the attribute is obsolete, create a new one + if ( skipTransform !== true || dstArray === null ) { - if ( currentAttribute.version < geometryIndex.version ) { + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - updateWireframeAttribute( geometry ); + viewNormalMatrix.getNormalMatrix( viewMatrix ); - } + if ( dstArray === null || dstArray.length < flatSize ) { + + dstArray = new Float32Array( flatSize ); } - } else { + for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { + + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); + + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - updateWireframeAttribute( geometry ); + } } - return wireframeAttributes.get( geometry ); + uniform.value = dstArray; + uniform.needsUpdate = true; } - return { + scope.numPlanes = nPlanes; + scope.numIntersection = 0; - get: get, - update: update, + return dstArray; - getWireframeAttribute: getWireframeAttribute + } - }; +} - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - /** - * @author mrdoob / http://mrdoob.com/ - */ +function WebGLExtensions( gl ) { - function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { + var extensions = {}; - var isWebGL2 = capabilities.isWebGL2; + return { - var mode; + get: function ( name ) { - function setMode( value ) { + if ( extensions[ name ] !== undefined ) { - mode = value; + return extensions[ name ]; - } + } - var type, bytesPerElement; + var extension; - function setIndex( value ) { + switch ( name ) { - type = value.type; - bytesPerElement = value.bytesPerElement; + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - } + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; - function render( start, count ) { + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; - gl.drawElements( mode, count, type, start * bytesPerElement ); + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - info.update( count, mode ); + default: + extension = gl.getExtension( name ); - } + } - function renderInstances( geometry, start, count, primcount ) { + if ( extension === null ) { - if ( primcount === 0 ) { return; } + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - var extension, methodName; + } - if ( isWebGL2 ) { + extensions[ name ] = extension; - extension = gl; - methodName = 'drawElementsInstanced'; + return extension; - } else { + } - extension = extensions.get( 'ANGLE_instanced_arrays' ); - methodName = 'drawElementsInstancedANGLE'; + }; - if ( extension === null ) { +} - console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function WebGLGeometries( gl, attributes, info ) { - } + var geometries = new WeakMap(); + var wireframeAttributes = new WeakMap(); + + function onGeometryDispose( event ) { + + var geometry = event.target; + var buffergeometry = geometries.get( geometry ); - extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); + if ( buffergeometry.index !== null ) { - info.update( count, mode, primcount ); + attributes.remove( buffergeometry.index ); } - // + for ( var name in buffergeometry.attributes ) { - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + attributes.remove( buffergeometry.attributes[ name ] ); - } + } - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + geometry.removeEventListener( 'dispose', onGeometryDispose ); - function WebGLInfo( gl ) { + geometries.delete( geometry ); - var memory = { - geometries: 0, - textures: 0 - }; + var attribute = wireframeAttributes.get( buffergeometry ); - var render = { - frame: 0, - calls: 0, - triangles: 0, - points: 0, - lines: 0 - }; + if ( attribute ) { - function update( count, mode, instanceCount ) { + attributes.remove( attribute ); + wireframeAttributes.delete( buffergeometry ); - instanceCount = instanceCount || 1; + } - render.calls ++; + // - switch ( mode ) { + info.memory.geometries --; - case 4: - render.triangles += instanceCount * ( count / 3 ); - break; + } - case 5: - case 6: - render.triangles += instanceCount * ( count - 2 ); - break; + function get( object, geometry ) { - case 1: - render.lines += instanceCount * ( count / 2 ); - break; + var buffergeometry = geometries.get( geometry ); - case 3: - render.lines += instanceCount * ( count - 1 ); - break; + if ( buffergeometry ) return buffergeometry; - case 2: - render.lines += instanceCount * count; - break; + geometry.addEventListener( 'dispose', onGeometryDispose ); - case 0: - render.points += instanceCount * count; - break; + if ( geometry.isBufferGeometry ) { - default: - console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); - break; + buffergeometry = geometry; - } + } else if ( geometry.isGeometry ) { - } + if ( geometry._bufferGeometry === undefined ) { + + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); - function reset() { + } - render.frame ++; - render.calls = 0; - render.triangles = 0; - render.points = 0; - render.lines = 0; + buffergeometry = geometry._bufferGeometry; } - return { - memory: memory, - render: render, - programs: null, - autoReset: true, - reset: reset, - update: update - }; + geometries.set( geometry, buffergeometry ); + + info.memory.geometries ++; + + return buffergeometry; } - /** - * @author mrdoob / http://mrdoob.com/ - */ + function update( geometry ) { - function absNumericalSort( a, b ) { + var index = geometry.index; + var geometryAttributes = geometry.attributes; - return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); + if ( index !== null ) { - } + attributes.update( index, 34963 ); - function WebGLMorphtargets( gl ) { + } - var influencesList = {}; - var morphInfluences = new Float32Array( 8 ); + for ( var name in geometryAttributes ) { - function update( object, geometry, material, program ) { + attributes.update( geometryAttributes[ name ], 34962 ); - var objectInfluences = object.morphTargetInfluences; + } - var length = objectInfluences.length; + // morph targets - var influences = influencesList[ geometry.id ]; + var morphAttributes = geometry.morphAttributes; - if ( influences === undefined ) { + for ( var name in morphAttributes ) { - // initialise list + var array = morphAttributes[ name ]; - influences = []; + for ( var i = 0, l = array.length; i < l; i ++ ) { - for ( var i = 0; i < length; i ++ ) { + attributes.update( array[ i ], 34962 ); - influences[ i ] = [ i, 0 ]; + } - } + } - influencesList[ geometry.id ] = influences; + } - } + function updateWireframeAttribute( geometry ) { - var morphTargets = material.morphTargets && geometry.morphAttributes.position; - var morphNormals = material.morphNormals && geometry.morphAttributes.normal; + var indices = []; - // Remove current morphAttributes + var geometryIndex = geometry.index; + var geometryPosition = geometry.attributes.position; + var version = 0; - for ( var i = 0; i < length; i ++ ) { + if ( geometryIndex !== null ) { - var influence = influences[ i ]; + var array = geometryIndex.array; + version = geometryIndex.version; - if ( influence[ 1 ] !== 0 ) { + for ( var i = 0, l = array.length; i < l; i += 3 ) { - if ( morphTargets ) { geometry.deleteAttribute( 'morphTarget' + i ); } - if ( morphNormals ) { geometry.deleteAttribute( 'morphNormal' + i ); } + var a = array[ i + 0 ]; + var b = array[ i + 1 ]; + var c = array[ i + 2 ]; - } + indices.push( a, b, b, c, c, a ); } - // Collect influences + } else { - for ( var i = 0; i < length; i ++ ) { + var array = geometryPosition.array; + version = geometryPosition.version; - var influence = influences[ i ]; + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - influence[ 0 ] = i; - influence[ 1 ] = objectInfluences[ i ]; + var a = i + 0; + var b = i + 1; + var c = i + 2; + + indices.push( a, b, b, c, c, a ); } - influences.sort( absNumericalSort ); + } - // Add morphAttributes + var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + attribute.version = version; - var morphInfluencesSum = 0; + attributes.update( attribute, 34963 ); - for ( var i = 0; i < 8; i ++ ) { + // - var influence = influences[ i ]; + var previousAttribute = wireframeAttributes.get( geometry ); - if ( influence ) { + if ( previousAttribute ) attributes.remove( previousAttribute ); - var index = influence[ 0 ]; - var value = influence[ 1 ]; + // - if ( value ) { + wireframeAttributes.set( geometry, attribute ); - if ( morphTargets ) { geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); } - if ( morphNormals ) { geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); } + } - morphInfluences[ i ] = value; - morphInfluencesSum += value; - continue; + function getWireframeAttribute( geometry ) { - } + var currentAttribute = wireframeAttributes.get( geometry ); - } + if ( currentAttribute ) { - morphInfluences[ i ] = 0; + var geometryIndex = geometry.index; - } + if ( geometryIndex !== null ) { - // GLSL shader uses formula baseinfluence * base + sum(target * influence) - // This allows us to switch between absolute morphs and relative morphs without changing shader code - // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) - var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + // if the attribute is obsolete, create a new one - program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); - program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); + if ( currentAttribute.version < geometryIndex.version ) { - } + updateWireframeAttribute( geometry ); - return { + } - update: update + } - }; + } else { - } + updateWireframeAttribute( geometry ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebGLObjects( gl, geometries, attributes, info ) { + return wireframeAttributes.get( geometry ); - var updateList = {}; + } - function update( object ) { + return { - var frame = info.render.frame; + get: get, + update: update, - var geometry = object.geometry; - var buffergeometry = geometries.get( object, geometry ); + getWireframeAttribute: getWireframeAttribute - // Update once per frame + }; - if ( updateList[ buffergeometry.id ] !== frame ) { +} - if ( geometry.isGeometry ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - buffergeometry.updateFromObject( object ); +function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { - } + var isWebGL2 = capabilities.isWebGL2; - geometries.update( buffergeometry ); + var mode; - updateList[ buffergeometry.id ] = frame; + function setMode( value ) { - } + mode = value; - if ( object.isInstancedMesh ) { + } - attributes.update( object.instanceMatrix, 34962 ); + var type, bytesPerElement; - } + function setIndex( value ) { - return buffergeometry; + type = value.type; + bytesPerElement = value.bytesPerElement; - } + } - function dispose() { + function render( start, count ) { - updateList = {}; + gl.drawElements( mode, count, type, start * bytesPerElement ); - } + info.update( count, mode ); - return { + } - update: update, - dispose: dispose + function renderInstances( geometry, start, count, primcount ) { - }; + if ( primcount === 0 ) return; - } + var extension, methodName; - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( isWebGL2 ) { - function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + extension = gl; + methodName = 'drawElementsInstanced'; - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - format = format !== undefined ? format : RGBFormat; + } else { - Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + extension = extensions.get( 'ANGLE_instanced_arrays' ); + methodName = 'drawElementsInstancedANGLE'; - this.flipY = false; + if ( extension === null ) { - } + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - CubeTexture.prototype = Object.create( Texture.prototype ); - CubeTexture.prototype.constructor = CubeTexture; + } - CubeTexture.prototype.isCubeTexture = true; + } - Object.defineProperty( CubeTexture.prototype, 'images', { + extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); - get: function () { + info.update( count, mode, primcount ); - return this.image; + } - }, + // - set: function ( value ) { + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - this.image = value; +} - } +/** + * @author Mugen87 / https://github.com/Mugen87 + */ - } ); +function WebGLInfo( gl ) { - /** - * @author Takahiro https://github.com/takahirox - */ + var memory = { + geometries: 0, + textures: 0 + }; - function DataTexture2DArray( data, width, height, depth ) { + var render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; - Texture.call( this, null ); + function update( count, mode, instanceCount ) { - this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; + instanceCount = instanceCount || 1; - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + render.calls ++; - this.wrapR = ClampToEdgeWrapping; + switch ( mode ) { - this.generateMipmaps = false; - this.flipY = false; + case 4: + render.triangles += instanceCount * ( count / 3 ); + break; - this.needsUpdate = true; + case 1: + render.lines += instanceCount * ( count / 2 ); + break; - } + case 3: + render.lines += instanceCount * ( count - 1 ); + break; - DataTexture2DArray.prototype = Object.create( Texture.prototype ); - DataTexture2DArray.prototype.constructor = DataTexture2DArray; - DataTexture2DArray.prototype.isDataTexture2DArray = true; + case 2: + render.lines += instanceCount * count; + break; - /** - * @author Artur Trzesiok - */ + case 0: + render.points += instanceCount * count; + break; - function DataTexture3D( data, width, height, depth ) { + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; - // We're going to add .setXXX() methods for setting properties later. - // Users can still set in DataTexture3D directly. - // - // var texture = new THREE.DataTexture3D( data, width, height, depth ); - // texture.anisotropy = 16; - // - // See #14839 + } - Texture.call( this, null ); + } - this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; + function reset() { - this.magFilter = NearestFilter; - this.minFilter = NearestFilter; + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; - this.wrapR = ClampToEdgeWrapping; + } - this.generateMipmaps = false; - this.flipY = false; + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; - this.needsUpdate = true; +} +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function absNumericalSort( a, b ) { - DataTexture3D.prototype = Object.create( Texture.prototype ); - DataTexture3D.prototype.constructor = DataTexture3D; - DataTexture3D.prototype.isDataTexture3D = true; + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); - /** - * @author tschw - * @author Mugen87 / https://github.com/Mugen87 - * @author mrdoob / http://mrdoob.com/ - * - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [textures] ) - * - * uploads a uniform value(s) - * the 'textures' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (textures factorizations): - * - * .upload( gl, seq, values, textures ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * - * Methods of the top-level container (textures factorizations): - * - * .setValue( gl, name, value, textures ) - * - * sets uniform with name 'name' to 'value' - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - */ +} + +function WebGLMorphtargets( gl ) { - var emptyTexture = new Texture(); - var emptyTexture2dArray = new DataTexture2DArray(); - var emptyTexture3d = new DataTexture3D(); - var emptyCubeTexture = new CubeTexture(); + var influencesList = {}; + var morphInfluences = new Float32Array( 8 ); - // --- Utilities --- + function update( object, geometry, material, program ) { - // Array Caches (provide typed arrays for temporary by size) + var objectInfluences = object.morphTargetInfluences; - var arrayCacheF32 = []; - var arrayCacheI32 = []; + // When object doesn't have morph target influences defined, we treat it as a 0-length array + // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences - // Float32Array caches used for uploading Matrix uniforms + var length = objectInfluences === undefined ? 0 : objectInfluences.length; - var mat4array = new Float32Array( 16 ); - var mat3array = new Float32Array( 9 ); - var mat2array = new Float32Array( 4 ); + var influences = influencesList[ geometry.id ]; - // Flattening for arrays of vectors and matrices + if ( influences === undefined ) { - function flatten( array, nBlocks, blockSize ) { + // initialise list - var firstElem = array[ 0 ]; + influences = []; - if ( firstElem <= 0 || firstElem > 0 ) { return array; } - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + for ( var i = 0; i < length; i ++ ) { - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + influences[ i ] = [ i, 0 ]; - if ( r === undefined ) { + } - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; + influencesList[ geometry.id ] = influences; } - if ( nBlocks !== 0 ) { + var morphTargets = material.morphTargets && geometry.morphAttributes.position; + var morphNormals = material.morphNormals && geometry.morphAttributes.normal; - firstElem.toArray( r, 0 ); + // Remove current morphAttributes - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + for ( var i = 0; i < length; i ++ ) { - offset += blockSize; - array[ i ].toArray( r, offset ); + var influence = influences[ i ]; - } + if ( influence[ 1 ] !== 0 ) { - } + if ( morphTargets ) geometry.deleteAttribute( 'morphTarget' + i ); + if ( morphNormals ) geometry.deleteAttribute( 'morphNormal' + i ); - return r; + } - } + } - function arraysEqual( a, b ) { + // Collect influences - if ( a.length !== b.length ) { return false; } + for ( var i = 0; i < length; i ++ ) { - for ( var i = 0, l = a.length; i < l; i ++ ) { + var influence = influences[ i ]; - if ( a[ i ] !== b[ i ] ) { return false; } + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; } - return true; + influences.sort( absNumericalSort ); - } + // Add morphAttributes - function copyArray( a, b ) { + var morphInfluencesSum = 0; - for ( var i = 0, l = b.length; i < l; i ++ ) { + for ( var i = 0; i < 8; i ++ ) { - a[ i ] = b[ i ]; + var influence = influences[ i ]; - } + if ( influence ) { - } + var index = influence[ 0 ]; + var value = influence[ 1 ]; + + if ( value ) { - // Texture unit allocation + if ( morphTargets ) geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); + if ( morphNormals ) geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); - function allocTexUnits( textures, n ) { + morphInfluences[ i ] = value; + morphInfluencesSum += value; + continue; - var r = arrayCacheI32[ n ]; + } - if ( r === undefined ) { + } - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + morphInfluences[ i ] = 0; } - for ( var i = 0; i !== n; ++ i ) - { r[ i ] = textures.allocateTextureUnit(); } + // GLSL shader uses formula baseinfluence * base + sum(target * influence) + // This allows us to switch between absolute morphs and relative morphs without changing shader code + // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) + var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; - return r; + program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); } - // --- Setters --- - - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + return { - // Single scalar + update: update - function setValueV1f( gl, v ) { - - var cache = this.cache; + }; - if ( cache[ 0 ] === v ) { return; } +} - gl.uniform1f( this.addr, v ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - cache[ 0 ] = v; +function WebGLObjects( gl, geometries, attributes, info ) { - } + var updateMap = new WeakMap(); - // Single float vector (from flat array or THREE.VectorN) + function update( object ) { - function setValueV2f( gl, v ) { + var frame = info.render.frame; - var cache = this.cache; + var geometry = object.geometry; + var buffergeometry = geometries.get( object, geometry ); - if ( v.x !== undefined ) { + // Update once per frame - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { + if ( updateMap.get( buffergeometry ) !== frame ) { - gl.uniform2f( this.addr, v.x, v.y ); + if ( geometry.isGeometry ) { - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; + buffergeometry.updateFromObject( object ); } - } else { + geometries.update( buffergeometry ); - if ( arraysEqual( cache, v ) ) { return; } + updateMap.set( buffergeometry, frame ); - gl.uniform2fv( this.addr, v ); + } + + if ( object.isInstancedMesh ) { - copyArray( cache, v ); + attributes.update( object.instanceMatrix, 34962 ); } + return buffergeometry; + + } + + function dispose() { + + updateMap = new WeakMap(); + } - function setValueV3f( gl, v ) { + return { - var cache = this.cache; + update: update, + dispose: dispose - if ( v.x !== undefined ) { + }; - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { +} - gl.uniform3f( this.addr, v.x, v.y, v.z ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; +function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - } + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + format = format !== undefined ? format : RGBFormat; - } else if ( v.r !== undefined ) { + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { + this.flipY = false; - gl.uniform3f( this.addr, v.r, v.g, v.b ); +} - cache[ 0 ] = v.r; - cache[ 1 ] = v.g; - cache[ 2 ] = v.b; +CubeTexture.prototype = Object.create( Texture.prototype ); +CubeTexture.prototype.constructor = CubeTexture; - } +CubeTexture.prototype.isCubeTexture = true; - } else { +Object.defineProperty( CubeTexture.prototype, 'images', { - if ( arraysEqual( cache, v ) ) { return; } + get: function () { - gl.uniform3fv( this.addr, v ); + return this.image; - copyArray( cache, v ); + }, - } + set: function ( value ) { + + this.image = value; } - function setValueV4f( gl, v ) { +} ); - var cache = this.cache; +/** + * @author Takahiro https://github.com/takahirox + */ - if ( v.x !== undefined ) { +function DataTexture2DArray( data, width, height, depth ) { - if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { + Texture.call( this, null ); - gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; - cache[ 0 ] = v.x; - cache[ 1 ] = v.y; - cache[ 2 ] = v.z; - cache[ 3 ] = v.w; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; - } + this.wrapR = ClampToEdgeWrapping; - } else { + this.generateMipmaps = false; + this.flipY = false; - if ( arraysEqual( cache, v ) ) { return; } + this.needsUpdate = true; - gl.uniform4fv( this.addr, v ); +} - copyArray( cache, v ); +DataTexture2DArray.prototype = Object.create( Texture.prototype ); +DataTexture2DArray.prototype.constructor = DataTexture2DArray; +DataTexture2DArray.prototype.isDataTexture2DArray = true; - } +/** + * @author Artur Trzesiok + */ - } +function DataTexture3D( data, width, height, depth ) { - // Single matrix (from flat array or MatrixN) + // We're going to add .setXXX() methods for setting properties later. + // Users can still set in DataTexture3D directly. + // + // var texture = new THREE.DataTexture3D( data, width, height, depth ); + // texture.anisotropy = 16; + // + // See #14839 + + Texture.call( this, null ); + + this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; + + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + + this.wrapR = ClampToEdgeWrapping; - function setValueM2( gl, v ) { + this.generateMipmaps = false; + this.flipY = false; - var cache = this.cache; - var elements = v.elements; + this.needsUpdate = true; - if ( elements === undefined ) { - if ( arraysEqual( cache, v ) ) { return; } +} - gl.uniformMatrix2fv( this.addr, false, v ); +DataTexture3D.prototype = Object.create( Texture.prototype ); +DataTexture3D.prototype.constructor = DataTexture3D; +DataTexture3D.prototype.isDataTexture3D = true; - copyArray( cache, v ); +/** + * @author tschw + * @author Mugen87 / https://github.com/Mugen87 + * @author mrdoob / http://mrdoob.com/ + * + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [textures] ) + * + * uploads a uniform value(s) + * the 'textures' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (textures factorizations): + * + * .upload( gl, seq, values, textures ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (textures factorizations): + * + * .setValue( gl, name, value, textures ) + * + * sets uniform with name 'name' to 'value' + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ - } else { +var emptyTexture = new Texture(); +var emptyTexture2dArray = new DataTexture2DArray(); +var emptyTexture3d = new DataTexture3D(); +var emptyCubeTexture = new CubeTexture(); - if ( arraysEqual( cache, elements ) ) { return; } +// --- Utilities --- - mat2array.set( elements ); +// Array Caches (provide typed arrays for temporary by size) - gl.uniformMatrix2fv( this.addr, false, mat2array ); +var arrayCacheF32 = []; +var arrayCacheI32 = []; - copyArray( cache, elements ); +// Float32Array caches used for uploading Matrix uniforms - } +var mat4array = new Float32Array( 16 ); +var mat3array = new Float32Array( 9 ); +var mat2array = new Float32Array( 4 ); - } +// Flattening for arrays of vectors and matrices - function setValueM3( gl, v ) { +function flatten( array, nBlocks, blockSize ) { - var cache = this.cache; - var elements = v.elements; + var firstElem = array[ 0 ]; - if ( elements === undefined ) { + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - if ( arraysEqual( cache, v ) ) { return; } + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - gl.uniformMatrix3fv( this.addr, false, v ); + if ( r === undefined ) { - copyArray( cache, v ); + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - } else { + } - if ( arraysEqual( cache, elements ) ) { return; } + if ( nBlocks !== 0 ) { - mat3array.set( elements ); + firstElem.toArray( r, 0 ); - gl.uniformMatrix3fv( this.addr, false, mat3array ); + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - copyArray( cache, elements ); + offset += blockSize; + array[ i ].toArray( r, offset ); } } - function setValueM4( gl, v ) { + return r; - var cache = this.cache; - var elements = v.elements; +} - if ( elements === undefined ) { +function arraysEqual( a, b ) { - if ( arraysEqual( cache, v ) ) { return; } + if ( a.length !== b.length ) return false; - gl.uniformMatrix4fv( this.addr, false, v ); + for ( var i = 0, l = a.length; i < l; i ++ ) { - copyArray( cache, v ); + if ( a[ i ] !== b[ i ] ) return false; - } else { + } - if ( arraysEqual( cache, elements ) ) { return; } + return true; - mat4array.set( elements ); +} - gl.uniformMatrix4fv( this.addr, false, mat4array ); +function copyArray( a, b ) { - copyArray( cache, elements ); + for ( var i = 0, l = b.length; i < l; i ++ ) { - } + a[ i ] = b[ i ]; } - // Single texture (2D / Cube) - - function setValueT1( gl, v, textures ) { +} - var cache = this.cache; - var unit = textures.allocateTextureUnit(); +// Texture unit allocation - if ( cache[ 0 ] !== unit ) { +function allocTexUnits( textures, n ) { - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + var r = arrayCacheI32[ n ]; - } + if ( r === undefined ) { - textures.safeSetTexture2D( v || emptyTexture, unit ); + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; } - function setValueT2DArray1( gl, v, textures ) { - - var cache = this.cache; - var unit = textures.allocateTextureUnit(); - - if ( cache[ 0 ] !== unit ) { - - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + for ( var i = 0; i !== n; ++ i ) + r[ i ] = textures.allocateTextureUnit(); - } + return r; - textures.setTexture2DArray( v || emptyTexture2dArray, unit ); +} - } +// --- Setters --- - function setValueT3D1( gl, v, textures ) { +// Note: Defining these methods externally, because they come in a bunch +// and this way their names minify. - var cache = this.cache; - var unit = textures.allocateTextureUnit(); +// Single scalar - if ( cache[ 0 ] !== unit ) { +function setValueV1f( gl, v ) { - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + var cache = this.cache; - } + if ( cache[ 0 ] === v ) return; - textures.setTexture3D( v || emptyTexture3d, unit ); + gl.uniform1f( this.addr, v ); - } + cache[ 0 ] = v; - function setValueT6( gl, v, textures ) { +} - var cache = this.cache; - var unit = textures.allocateTextureUnit(); +// Single float vector (from flat array or THREE.VectorN) - if ( cache[ 0 ] !== unit ) { +function setValueV2f( gl, v ) { - gl.uniform1i( this.addr, unit ); - cache[ 0 ] = unit; + var cache = this.cache; - } + if ( v.x !== undefined ) { - textures.safeSetTextureCube( v || emptyCubeTexture, unit ); + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { - } + gl.uniform2f( this.addr, v.x, v.y ); - // Integer / Boolean vectors or arrays thereof (always flat arrays) + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; - function setValueV1i( gl, v ) { + } - var cache = this.cache; + } else { - if ( cache[ 0 ] === v ) { return; } + if ( arraysEqual( cache, v ) ) return; - gl.uniform1i( this.addr, v ); + gl.uniform2fv( this.addr, v ); - cache[ 0 ] = v; + copyArray( cache, v ); } - function setValueV2i( gl, v ) { +} - var cache = this.cache; +function setValueV3f( gl, v ) { - if ( arraysEqual( cache, v ) ) { return; } + var cache = this.cache; - gl.uniform2iv( this.addr, v ); + if ( v.x !== undefined ) { - copyArray( cache, v ); + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { - } + gl.uniform3f( this.addr, v.x, v.y, v.z ); - function setValueV3i( gl, v ) { + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; - var cache = this.cache; + } - if ( arraysEqual( cache, v ) ) { return; } + } else if ( v.r !== undefined ) { - gl.uniform3iv( this.addr, v ); + if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { - copyArray( cache, v ); + gl.uniform3f( this.addr, v.r, v.g, v.b ); - } + cache[ 0 ] = v.r; + cache[ 1 ] = v.g; + cache[ 2 ] = v.b; - function setValueV4i( gl, v ) { + } - var cache = this.cache; + } else { - if ( arraysEqual( cache, v ) ) { return; } + if ( arraysEqual( cache, v ) ) return; - gl.uniform4iv( this.addr, v ); + gl.uniform3fv( this.addr, v ); copyArray( cache, v ); } - // Helper to pick the right setter for the singular case +} - function getSingularSetter( type ) { +function setValueV4f( gl, v ) { - switch ( type ) { + var cache = this.cache; - case 0x1406: return setValueV1f; // FLOAT - case 0x8b50: return setValueV2f; // _VEC2 - case 0x8b51: return setValueV3f; // _VEC3 - case 0x8b52: return setValueV4f; // _VEC4 + if ( v.x !== undefined ) { - case 0x8b5a: return setValueM2; // _MAT2 - case 0x8b5b: return setValueM3; // _MAT3 - case 0x8b5c: return setValueM4; // _MAT4 + if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { - case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES - case 0x8b5f: return setValueT3D1; // SAMPLER_3D - case 0x8b60: return setValueT6; // SAMPLER_CUBE - case 0x8DC1: return setValueT2DArray1; // SAMPLER_2D_ARRAY + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 + cache[ 0 ] = v.x; + cache[ 1 ] = v.y; + cache[ 2 ] = v.z; + cache[ 3 ] = v.w; } - } + } else { + + if ( arraysEqual( cache, v ) ) return; - // Array of scalars - function setValueV1fArray( gl, v ) { + gl.uniform4fv( this.addr, v ); - gl.uniform1fv( this.addr, v ); + copyArray( cache, v ); } - // Integer / Boolean vectors or arrays thereof (always flat arrays) - function setValueV1iArray( gl, v ) { +} - gl.uniform1iv( this.addr, v ); +// Single matrix (from flat array or MatrixN) - } +function setValueM2( gl, v ) { - function setValueV2iArray( gl, v ) { + var cache = this.cache; + var elements = v.elements; - gl.uniform2iv( this.addr, v ); + if ( elements === undefined ) { - } + if ( arraysEqual( cache, v ) ) return; + + gl.uniformMatrix2fv( this.addr, false, v ); - function setValueV3iArray( gl, v ) { + copyArray( cache, v ); - gl.uniform3iv( this.addr, v ); + } else { - } + if ( arraysEqual( cache, elements ) ) return; - function setValueV4iArray( gl, v ) { + mat2array.set( elements ); - gl.uniform4iv( this.addr, v ); + gl.uniformMatrix2fv( this.addr, false, mat2array ); - } + copyArray( cache, elements ); + } - // Array of vectors (flat or from THREE classes) +} - function setValueV2fArray( gl, v ) { +function setValueM3( gl, v ) { - var data = flatten( v, this.size, 2 ); + var cache = this.cache; + var elements = v.elements; - gl.uniform2fv( this.addr, data ); + if ( elements === undefined ) { - } + if ( arraysEqual( cache, v ) ) return; - function setValueV3fArray( gl, v ) { + gl.uniformMatrix3fv( this.addr, false, v ); - var data = flatten( v, this.size, 3 ); + copyArray( cache, v ); - gl.uniform3fv( this.addr, data ); + } else { - } + if ( arraysEqual( cache, elements ) ) return; - function setValueV4fArray( gl, v ) { + mat3array.set( elements ); - var data = flatten( v, this.size, 4 ); + gl.uniformMatrix3fv( this.addr, false, mat3array ); - gl.uniform4fv( this.addr, data ); + copyArray( cache, elements ); } - // Array of matrices (flat or from THREE clases) +} - function setValueM2Array( gl, v ) { +function setValueM4( gl, v ) { - var data = flatten( v, this.size, 4 ); + var cache = this.cache; + var elements = v.elements; - gl.uniformMatrix2fv( this.addr, false, data ); + if ( elements === undefined ) { - } + if ( arraysEqual( cache, v ) ) return; - function setValueM3Array( gl, v ) { + gl.uniformMatrix4fv( this.addr, false, v ); - var data = flatten( v, this.size, 9 ); + copyArray( cache, v ); - gl.uniformMatrix3fv( this.addr, false, data ); + } else { - } + if ( arraysEqual( cache, elements ) ) return; - function setValueM4Array( gl, v ) { + mat4array.set( elements ); - var data = flatten( v, this.size, 16 ); + gl.uniformMatrix4fv( this.addr, false, mat4array ); - gl.uniformMatrix4fv( this.addr, false, data ); + copyArray( cache, elements ); } - // Array of textures (2D / Cube) - - function setValueT1Array( gl, v, textures ) { - - var n = v.length; +} - var units = allocTexUnits( textures, n ); +// Single texture (2D / Cube) - gl.uniform1iv( this.addr, units ); +function setValueT1( gl, v, textures ) { - for ( var i = 0; i !== n; ++ i ) { + var cache = this.cache; + var unit = textures.allocateTextureUnit(); - textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] ); + if ( cache[ 0 ] !== unit ) { - } + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; } - function setValueT6Array( gl, v, textures ) { - - var n = v.length; + textures.safeSetTexture2D( v || emptyTexture, unit ); - var units = allocTexUnits( textures, n ); +} - gl.uniform1iv( this.addr, units ); +function setValueT2DArray1( gl, v, textures ) { - for ( var i = 0; i !== n; ++ i ) { + var cache = this.cache; + var unit = textures.allocateTextureUnit(); - textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + if ( cache[ 0 ] !== unit ) { - } + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; } - // Helper to pick the right setter for a pure (bottom-level) array + textures.setTexture2DArray( v || emptyTexture2dArray, unit ); - function getPureArraySetter( type ) { +} - switch ( type ) { +function setValueT3D1( gl, v, textures ) { - case 0x1406: return setValueV1fArray; // FLOAT - case 0x8b50: return setValueV2fArray; // _VEC2 - case 0x8b51: return setValueV3fArray; // _VEC3 - case 0x8b52: return setValueV4fArray; // _VEC4 + var cache = this.cache; + var unit = textures.allocateTextureUnit(); - case 0x8b5a: return setValueM2Array; // _MAT2 - case 0x8b5b: return setValueM3Array; // _MAT3 - case 0x8b5c: return setValueM4Array; // _MAT4 + if ( cache[ 0 ] !== unit ) { - case 0x8b5e: return setValueT1Array; // SAMPLER_2D - case 0x8b60: return setValueT6Array; // SAMPLER_CUBE + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; - case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL - case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 - case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 - case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 + } - } + textures.setTexture3D( v || emptyTexture3d, unit ); - } +} - // --- Uniform Classes --- +function setValueT6( gl, v, textures ) { - function SingleUniform( id, activeInfo, addr ) { + var cache = this.cache; + var unit = textures.allocateTextureUnit(); - this.id = id; - this.addr = addr; - this.cache = []; - this.setValue = getSingularSetter( activeInfo.type ); + if ( cache[ 0 ] !== unit ) { - // this.path = activeInfo.name; // DEBUG + gl.uniform1i( this.addr, unit ); + cache[ 0 ] = unit; } - function PureArrayUniform( id, activeInfo, addr ) { + textures.safeSetTextureCube( v || emptyCubeTexture, unit ); - this.id = id; - this.addr = addr; - this.cache = []; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); +} - // this.path = activeInfo.name; // DEBUG - - } +// Integer / Boolean vectors or arrays thereof (always flat arrays) - PureArrayUniform.prototype.updateCache = function ( data ) { +function setValueV1i( gl, v ) { - var cache = this.cache; + var cache = this.cache; - if ( data instanceof Float32Array && cache.length !== data.length ) { + if ( cache[ 0 ] === v ) return; - this.cache = new Float32Array( data.length ); + gl.uniform1i( this.addr, v ); - } + cache[ 0 ] = v; - copyArray( cache, data ); +} - }; +function setValueV2i( gl, v ) { - function StructuredUniform( id ) { + var cache = this.cache; - this.id = id; + if ( arraysEqual( cache, v ) ) return; - this.seq = []; - this.map = {}; + gl.uniform2iv( this.addr, v ); - } + copyArray( cache, v ); - StructuredUniform.prototype.setValue = function ( gl, value, textures ) { +} - var seq = this.seq; +function setValueV3i( gl, v ) { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + var cache = this.cache; - var u = seq[ i ]; - u.setValue( gl, value[ u.id ], textures ); + if ( arraysEqual( cache, v ) ) return; - } + gl.uniform3iv( this.addr, v ); - }; + copyArray( cache, v ); - // --- Top-level --- +} - // Parser - builds up the property tree from the path strings +function setValueV4i( gl, v ) { - var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; + var cache = this.cache; - // extracts - // - the identifier (member name or array index) - // - followed by an optional right bracket (found when array index) - // - followed by an optional left bracket or dot (type of subscript) - // - // Note: These portions can be read in a non-overlapping fashion and - // allow straightforward parsing of the hierarchy that WebGL encodes - // in the uniform names. + if ( arraysEqual( cache, v ) ) return; - function addUniform( container, uniformObject ) { + gl.uniform4iv( this.addr, v ); - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + copyArray( cache, v ); - } +} - function parseUniform( activeInfo, addr, container ) { +// uint - var path = activeInfo.name, - pathLength = path.length; +function setValueV1ui( gl, v ) { - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + var cache = this.cache; - while ( true ) { + if ( cache[ 0 ] === v ) return; - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + gl.uniform1ui( this.addr, v ); - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + cache[ 0 ] = v; - if ( idIsIndex ) { id = id | 0; } // convert to integer +} - if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { +// Helper to pick the right setter for the singular case - // bare name or "pure" bottom-level array "[0]" suffix +function getSingularSetter( type ) { - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + switch ( type ) { - break; + case 0x1406: return setValueV1f; // FLOAT + case 0x8b50: return setValueV2f; // _VEC2 + case 0x8b51: return setValueV3f; // _VEC3 + case 0x8b52: return setValueV4f; // _VEC4 - } else { + case 0x8b5a: return setValueM2; // _MAT2 + case 0x8b5b: return setValueM3; // _MAT3 + case 0x8b5c: return setValueM4; // _MAT4 - // step into inner node / create it in case it doesn't exist + case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 - var map = container.map, next = map[ id ]; + case 0x1405: return setValueV1ui; // UINT - if ( next === undefined ) { + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1; - next = new StructuredUniform( id ); - addUniform( container, next ); + case 0x8b5f: // SAMPLER_3D + case 0x8dcb: // INT_SAMPLER_3D + case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D + return setValueT3D1; - } + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6; - container = next; + case 0x8dc1: // SAMPLER_2D_ARRAY + case 0x8dcf: // INT_SAMPLER_2D_ARRAY + case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW + return setValueT2DArray1; - } + } - } +} - } +// Array of scalars +function setValueV1fArray( gl, v ) { - // Root Container + gl.uniform1fv( this.addr, v ); - function WebGLUniforms( gl, program ) { +} - this.seq = []; - this.map = {}; +// Integer / Boolean vectors or arrays thereof (always flat arrays) +function setValueV1iArray( gl, v ) { - var n = gl.getProgramParameter( program, 35718 ); + gl.uniform1iv( this.addr, v ); - for ( var i = 0; i < n; ++ i ) { +} - var info = gl.getActiveUniform( program, i ), - addr = gl.getUniformLocation( program, info.name ); +function setValueV2iArray( gl, v ) { - parseUniform( info, addr, this ); + gl.uniform2iv( this.addr, v ); - } +} - } +function setValueV3iArray( gl, v ) { - WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { + gl.uniform3iv( this.addr, v ); - var u = this.map[ name ]; +} - if ( u !== undefined ) { u.setValue( gl, value, textures ); } +function setValueV4iArray( gl, v ) { - }; + gl.uniform4iv( this.addr, v ); - WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { +} - var v = object[ name ]; - if ( v !== undefined ) { this.setValue( gl, name, v ); } +// Array of vectors (flat or from THREE classes) - }; +function setValueV2fArray( gl, v ) { + var data = flatten( v, this.size, 2 ); - // Static interface + gl.uniform2fv( this.addr, data ); - WebGLUniforms.upload = function ( gl, seq, values, textures ) { +} - for ( var i = 0, n = seq.length; i !== n; ++ i ) { +function setValueV3fArray( gl, v ) { - var u = seq[ i ], - v = values[ u.id ]; + var data = flatten( v, this.size, 3 ); - if ( v.needsUpdate !== false ) { + gl.uniform3fv( this.addr, data ); - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, textures ); +} - } +function setValueV4fArray( gl, v ) { - } + var data = flatten( v, this.size, 4 ); - }; + gl.uniform4fv( this.addr, data ); - WebGLUniforms.seqWithValue = function ( seq, values ) { +} - var r = []; +// Array of matrices (flat or from THREE clases) - for ( var i = 0, n = seq.length; i !== n; ++ i ) { +function setValueM2Array( gl, v ) { - var u = seq[ i ]; - if ( u.id in values ) { r.push( u ); } + var data = flatten( v, this.size, 4 ); - } + gl.uniformMatrix2fv( this.addr, false, data ); - return r; +} - }; +function setValueM3Array( gl, v ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + var data = flatten( v, this.size, 9 ); - function WebGLShader( gl, type, string ) { + gl.uniformMatrix3fv( this.addr, false, data ); - var shader = gl.createShader( type ); +} - gl.shaderSource( shader, string ); - gl.compileShader( shader ); +function setValueM4Array( gl, v ) { - return shader; + var data = flatten( v, this.size, 16 ); - } + gl.uniformMatrix4fv( this.addr, false, data ); - /** - * @author mrdoob / http://mrdoob.com/ - */ +} - var programIdCount = 0; +// Array of textures (2D / Cube) - function addLineNumbers( string ) { +function setValueT1Array( gl, v, textures ) { - var lines = string.split( '\n' ); + var n = v.length; - for ( var i = 0; i < lines.length; i ++ ) { + var units = allocTexUnits( textures, n ); - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; + gl.uniform1iv( this.addr, units ); - } + for ( var i = 0; i !== n; ++ i ) { - return lines.join( '\n' ); + textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] ); } - function getEncodingComponents( encoding ) { +} - switch ( encoding ) { +function setValueT6Array( gl, v, textures ) { - case LinearEncoding: - return [ 'Linear', '( value )' ]; - case sRGBEncoding: - return [ 'sRGB', '( value )' ]; - case RGBEEncoding: - return [ 'RGBE', '( value )' ]; - case RGBM7Encoding: - return [ 'RGBM', '( value, 7.0 )' ]; - case RGBM16Encoding: - return [ 'RGBM', '( value, 16.0 )' ]; - case RGBDEncoding: - return [ 'RGBD', '( value, 256.0 )' ]; - case GammaEncoding: - return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ]; - case LogLuvEncoding: - return [ 'LogLuv', '( value )' ]; - default: - throw new Error( 'unsupported encoding: ' + encoding ); + var n = v.length; - } + var units = allocTexUnits( textures, n ); - } + gl.uniform1iv( this.addr, units ); - function getShaderErrors( gl, shader, type ) { + for ( var i = 0; i !== n; ++ i ) { - var status = gl.getShaderParameter( shader, 35713 ); - var log = gl.getShaderInfoLog( shader ).trim(); + textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - if ( status && log === '' ) { return ''; } + } - // --enable-privileged-webgl-extension - // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); +} - var source = gl.getShaderSource( shader ); +// Helper to pick the right setter for a pure (bottom-level) array - return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source ); +function getPureArraySetter( type ) { - } + switch ( type ) { - function getTexelDecodingFunction( functionName, encoding ) { + case 0x1406: return setValueV1fArray; // FLOAT + case 0x8b50: return setValueV2fArray; // _VEC2 + case 0x8b51: return setValueV3fArray; // _VEC3 + case 0x8b52: return setValueV4fArray; // _VEC4 - var components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; + case 0x8b5a: return setValueM2Array; // _MAT2 + case 0x8b5b: return setValueM3Array; // _MAT3 + case 0x8b5c: return setValueM4Array; // _MAT4 - } + case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL + case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 + case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 + case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 - function getTexelEncodingFunction( functionName, encoding ) { + case 0x8b5e: // SAMPLER_2D + case 0x8d66: // SAMPLER_EXTERNAL_OES + case 0x8dca: // INT_SAMPLER_2D + case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D + case 0x8b62: // SAMPLER_2D_SHADOW + return setValueT1Array; - var components = getEncodingComponents( encoding ); - return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; + case 0x8b60: // SAMPLER_CUBE + case 0x8dcc: // INT_SAMPLER_CUBE + case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE + case 0x8dc5: // SAMPLER_CUBE_SHADOW + return setValueT6Array; } - function getToneMappingFunction( functionName, toneMapping ) { +} - var toneMappingName; +// --- Uniform Classes --- - switch ( toneMapping ) { +function SingleUniform( id, activeInfo, addr ) { - case LinearToneMapping: - toneMappingName = 'Linear'; - break; + this.id = id; + this.addr = addr; + this.cache = []; + this.setValue = getSingularSetter( activeInfo.type ); - case ReinhardToneMapping: - toneMappingName = 'Reinhard'; - break; + // this.path = activeInfo.name; // DEBUG - case Uncharted2ToneMapping: - toneMappingName = 'Uncharted2'; - break; +} - case CineonToneMapping: - toneMappingName = 'OptimizedCineon'; - break; +function PureArrayUniform( id, activeInfo, addr ) { - case ACESFilmicToneMapping: - toneMappingName = 'ACESFilmic'; - break; + this.id = id; + this.addr = addr; + this.cache = []; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); + // this.path = activeInfo.name; // DEBUG - } +} - return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; +PureArrayUniform.prototype.updateCache = function ( data ) { - } + var cache = this.cache; - function generateExtensions( extensions, parameters, rendererExtensions ) { + if ( data instanceof Float32Array && cache.length !== data.length ) { - extensions = extensions || {}; + this.cache = new Float32Array( data.length ); - var chunks = [ - ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', - ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '' - ]; + } - return chunks.filter( filterEmptyLine ).join( '\n' ); + copyArray( cache, data ); - } +}; - function generateDefines( defines ) { +function StructuredUniform( id ) { - var chunks = []; + this.id = id; - for ( var name in defines ) { + this.seq = []; + this.map = {}; - var value = defines[ name ]; +} - if ( value === false ) { continue; } +StructuredUniform.prototype.setValue = function ( gl, value, textures ) { - chunks.push( '#define ' + name + ' ' + value ); + var seq = this.seq; - } + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - return chunks.join( '\n' ); + var u = seq[ i ]; + u.setValue( gl, value[ u.id ], textures ); } - function fetchAttributeLocations( gl, program ) { +}; - var attributes = {}; +// --- Top-level --- - var n = gl.getProgramParameter( program, 35721 ); +// Parser - builds up the property tree from the path strings - for ( var i = 0; i < n; i ++ ) { +var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; - var info = gl.getActiveAttrib( program, i ); - var name = info.name; +// extracts +// - the identifier (member name or array index) +// - followed by an optional right bracket (found when array index) +// - followed by an optional left bracket or dot (type of subscript) +// +// Note: These portions can be read in a non-overlapping fashion and +// allow straightforward parsing of the hierarchy that WebGL encodes +// in the uniform names. - // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); +function addUniform( container, uniformObject ) { - attributes[ name ] = gl.getAttribLocation( program, name ); + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - } +} - return attributes; +function parseUniform( activeInfo, addr, container ) { - } + var path = activeInfo.name, + pathLength = path.length; - function filterEmptyLine( string ) { + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - return string !== ''; + while ( true ) { - } + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - function replaceLightNums( string, parameters ) { + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) - .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) - .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) - .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); + if ( idIsIndex ) id = id | 0; // convert to integer - } + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { - function replaceClippingPlaneNums( string, parameters ) { + // bare name or "pure" bottom-level array "[0]" suffix - return string - .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) - .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - } + break; - // Resolve Includes + } else { - var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + // step into inner node / create it in case it doesn't exist - function resolveIncludes( string ) { + var map = container.map, next = map[ id ]; - return string.replace( includePattern, includeReplacer ); + if ( next === undefined ) { - } + next = new StructuredUniform( id ); + addUniform( container, next ); + + } - function includeReplacer( match, include ) { + container = next; - var string = ShaderChunk[ include ]; + } - if ( string === undefined ) { + } - throw new Error( 'Can not resolve #include <' + include + '>' ); +} - } +// Root Container - return resolveIncludes( string ); +function WebGLUniforms( gl, program ) { - } + this.seq = []; + this.map = {}; - // Unroll Loops + var n = gl.getProgramParameter( program, 35718 ); - var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; + for ( var i = 0; i < n; ++ i ) { - function unrollLoops( string ) { + var info = gl.getActiveUniform( program, i ), + addr = gl.getUniformLocation( program, info.name ); - return string.replace( loopPattern, loopReplacer ); + parseUniform( info, addr, this ); } - function loopReplacer( match, start, end, snippet ) { +} - var string = ''; +WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { + var u = this.map[ name ]; - string += snippet - .replace( /\[ i \]/g, '[ ' + i + ' ]' ) - .replace( /UNROLLED_LOOP_INDEX/g, i ); + if ( u !== undefined ) u.setValue( gl, value, textures ); - } +}; - return string; +WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { - } + var v = object[ name ]; - // + if ( v !== undefined ) this.setValue( gl, name, v ); - function generatePrecision( parameters ) { +}; - var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;"; - if ( parameters.precision === "highp" ) { +// Static interface - precisionstring += "\n#define HIGH_PRECISION"; +WebGLUniforms.upload = function ( gl, seq, values, textures ) { - } else if ( parameters.precision === "mediump" ) { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - precisionstring += "\n#define MEDIUM_PRECISION"; + var u = seq[ i ], + v = values[ u.id ]; - } else if ( parameters.precision === "lowp" ) { + if ( v.needsUpdate !== false ) { - precisionstring += "\n#define LOW_PRECISION"; + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, textures ); } - return precisionstring; - } - function generateShadowMapTypeDefine( parameters ) { +}; - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; +WebGLUniforms.seqWithValue = function ( seq, values ) { - if ( parameters.shadowMapType === PCFShadowMap ) { + var r = []; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; + } - } else if ( parameters.shadowMapType === VSMShadowMap ) { + return r; - shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; +}; - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - return shadowMapTypeDefine; +function WebGLShader( gl, type, string ) { - } + var shader = gl.createShader( type ); - function generateEnvMapTypeDefine( parameters ) { + gl.shaderSource( shader, string ); + gl.compileShader( shader ); - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + return shader; - if ( parameters.envMap ) { +} - switch ( parameters.envMapMode ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; +var programIdCount = 0; - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; +function addLineNumbers( string ) { - case EquirectangularReflectionMapping: - case EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; + var lines = string.split( '\n' ); - case SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; + for ( var i = 0; i < lines.length; i ++ ) { - } + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - } + } - return envMapTypeDefine; + return lines.join( '\n' ); - } +} - function generateEnvMapModeDefine( parameters ) { +function getEncodingComponents( encoding ) { - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + switch ( encoding ) { - if ( parameters.envMap ) { + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + case RGBEEncoding: + return [ 'RGBE', '( value )' ]; + case RGBM7Encoding: + return [ 'RGBM', '( value, 7.0 )' ]; + case RGBM16Encoding: + return [ 'RGBM', '( value, 16.0 )' ]; + case RGBDEncoding: + return [ 'RGBD', '( value, 256.0 )' ]; + case GammaEncoding: + return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ]; + case LogLuvEncoding: + return [ 'LogLuv', '( value )' ]; + default: + throw new Error( 'unsupported encoding: ' + encoding ); - switch ( parameters.envMapMode ) { + } - case CubeRefractionMapping: - case EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; +} - } +function getShaderErrors( gl, shader, type ) { - } + var status = gl.getShaderParameter( shader, 35713 ); + var log = gl.getShaderInfoLog( shader ).trim(); - return envMapModeDefine; + if ( status && log === '' ) return ''; - } + // --enable-privileged-webgl-extension + // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - function generateEnvMapBlendingDefine( parameters ) { + var source = gl.getShaderSource( shader ); - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source ); - if ( parameters.envMap ) { +} - switch ( parameters.combine ) { +function getTexelDecodingFunction( functionName, encoding ) { - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; + var components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; +} - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; +function getTexelEncodingFunction( functionName, encoding ) { - } + var components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; - } - - return envMapBlendingDefine; - - } +} - function WebGLProgram( renderer, extensions, cacheKey, material, shader, parameters ) { +function getToneMappingFunction( functionName, toneMapping ) { - var gl = renderer.getContext(); + var toneMappingName; - var defines = material.defines; + switch ( toneMapping ) { - var vertexShader = shader.vertexShader; - var fragmentShader = shader.fragmentShader; - var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); - var envMapTypeDefine = generateEnvMapTypeDefine( parameters ); - var envMapModeDefine = generateEnvMapModeDefine( parameters ); - var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); + case LinearToneMapping: + toneMappingName = 'Linear'; + break; + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; + case Uncharted2ToneMapping: + toneMappingName = 'Uncharted2'; + break; - var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions ); + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; - var customDefines = generateDefines( defines ); + case ACESFilmicToneMapping: + toneMappingName = 'ACESFilmic'; + break; - var program = gl.createProgram(); + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); - var prefixVertex, prefixFragment; - - var numMultiviewViews = parameters.numMultiviewViews; + } - if ( material.isRawShaderMaterial ) { + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; - prefixVertex = [ +} - customDefines +function generateExtensions( parameters ) { - ].filter( filterEmptyLine ).join( '\n' ); + var chunks = [ + ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', + ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; - if ( prefixVertex.length > 0 ) { + return chunks.filter( filterEmptyLine ).join( '\n' ); - prefixVertex += '\n'; +} - } +function generateDefines( defines ) { - prefixFragment = [ + var chunks = []; - customExtensions, - customDefines + for ( var name in defines ) { - ].filter( filterEmptyLine ).join( '\n' ); + var value = defines[ name ]; - if ( prefixFragment.length > 0 ) { + if ( value === false ) continue; - prefixFragment += '\n'; + chunks.push( '#define ' + name + ' ' + value ); - } + } - } else { + return chunks.join( '\n' ); - prefixVertex = [ +} - generatePrecision( parameters ), +function fetchAttributeLocations( gl, program ) { - '#define SHADER_NAME ' + shader.name, + var attributes = {}; - customDefines, + var n = gl.getProgramParameter( program, 35721 ); - parameters.instancing ? '#define USE_INSTANCING' : '', - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', + for ( var i = 0; i < n; i ++ ) { - '#define GAMMA_FACTOR ' + gammaFactorDefine, + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - '#define MAX_BONES ' + parameters.maxBones, - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + attributes[ name ] = gl.getAttribLocation( program, name ); - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', - parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + } - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + return attributes; - parameters.flatShading ? '#define FLAT_SHADED' : '', +} - parameters.skinning ? '#define USE_SKINNING' : '', - parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', +function filterEmptyLine( string ) { - parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', - parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + return string !== ''; - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', +} - parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', +function replaceLightNums( string, parameters ) { - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && ( parameters.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) + .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) + .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) + .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); - 'uniform mat4 modelMatrix;', - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', +} - '#ifdef USE_INSTANCING', +function replaceClippingPlaneNums( string, parameters ) { - ' attribute mat4 instanceMatrix;', + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); - '#endif', +} - 'attribute vec3 position;', - 'attribute vec3 normal;', - 'attribute vec2 uv;', +// Resolve Includes - '#ifdef USE_TANGENT', +var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; - ' attribute vec4 tangent;', +function resolveIncludes( string ) { - '#endif', + return string.replace( includePattern, includeReplacer ); - '#ifdef USE_COLOR', +} - ' attribute vec3 color;', +function includeReplacer( match, include ) { - '#endif', + var string = ShaderChunk[ include ]; - '#ifdef USE_MORPHTARGETS', + if ( string === undefined ) { - ' attribute vec3 morphTarget0;', - ' attribute vec3 morphTarget1;', - ' attribute vec3 morphTarget2;', - ' attribute vec3 morphTarget3;', + throw new Error( 'Can not resolve #include <' + include + '>' ); - ' #ifdef USE_MORPHNORMALS', + } - ' attribute vec3 morphNormal0;', - ' attribute vec3 morphNormal1;', - ' attribute vec3 morphNormal2;', - ' attribute vec3 morphNormal3;', + return resolveIncludes( string ); - ' #else', +} - ' attribute vec3 morphTarget4;', - ' attribute vec3 morphTarget5;', - ' attribute vec3 morphTarget6;', - ' attribute vec3 morphTarget7;', +// Unroll Loops - ' #endif', +var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; +var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g; - '#endif', +function unrollLoops( string ) { - '#ifdef USE_SKINNING', + return string + .replace( unrollLoopPattern, loopReplacer ) + .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer ); - ' attribute vec4 skinIndex;', - ' attribute vec4 skinWeight;', +} - '#endif', +function deprecatedLoopReplacer( match, start, end, snippet ) { - '\n' + console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' ); + return loopReplacer( match, start, end, snippet ); - ].filter( filterEmptyLine ).join( '\n' ); +} - prefixFragment = [ +function loopReplacer( match, start, end, snippet ) { - customExtensions, + var string = ''; - generatePrecision( parameters ), + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - '#define SHADER_NAME ' + shader.name, + string += snippet + .replace( /\[ i \]/g, '[ ' + i + ' ]' ) + .replace( /UNROLLED_LOOP_INDEX/g, i ); - customDefines, + } - parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer + return string; - '#define GAMMA_FACTOR ' + gammaFactorDefine, +} - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', +// - parameters.map ? '#define USE_MAP' : '', - parameters.matcap ? '#define USE_MATCAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapTypeDefine : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.envMap ? '#define ' + envMapBlendingDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', - ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', - parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', +function generatePrecision( parameters ) { - parameters.sheen ? '#define USE_SHEEN' : '', + var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;"; - parameters.vertexTangents ? '#define USE_TANGENT' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', - parameters.vertexUvs ? '#define USE_UV' : '', - parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', + if ( parameters.precision === "highp" ) { - parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', + precisionstring += "\n#define HIGH_PRECISION"; - parameters.flatShading ? '#define FLAT_SHADED' : '', + } else if ( parameters.precision === "mediump" ) { - parameters.doubleSided ? '#define DOUBLE_SIDED' : '', - parameters.flipSided ? '#define FLIP_SIDED' : '', + precisionstring += "\n#define MEDIUM_PRECISION"; - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', - parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', + } else if ( parameters.precision === "lowp" ) { - parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', + precisionstring += "\n#define LOW_PRECISION"; - parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', + } - parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && ( parameters.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + return precisionstring; - ( ( material.extensions ? material.extensions.shaderTextureLOD : false ) || parameters.envMap ) && ( parameters.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '', +} - 'uniform mat4 viewMatrix;', - 'uniform vec3 cameraPosition;', - 'uniform bool isOrthographic;', +function generateShadowMapTypeDefine( parameters ) { - ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', - ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - parameters.dithering ? '#define DITHERING' : '', + if ( parameters.shadowMapType === PCFShadowMap ) { - ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? - ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below - parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', - parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '', - parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', - parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '', + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - '\n' + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - ].filter( filterEmptyLine ).join( '\n' ); + } else if ( parameters.shadowMapType === VSMShadowMap ) { - } + shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; - vertexShader = resolveIncludes( vertexShader ); - vertexShader = replaceLightNums( vertexShader, parameters ); - vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); + } - fragmentShader = resolveIncludes( fragmentShader ); - fragmentShader = replaceLightNums( fragmentShader, parameters ); - fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); + return shadowMapTypeDefine; - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); +} - if ( parameters.isWebGL2 && ! material.isRawShaderMaterial ) { +function generateEnvMapTypeDefine( parameters ) { - var isGLSL3ShaderMaterial = false; + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var versionRegex = /^\s*#version\s+300\s+es\s*\n/; + if ( parameters.envMap ) { - if ( material.isShaderMaterial && - vertexShader.match( versionRegex ) !== null && - fragmentShader.match( versionRegex ) !== null ) { + switch ( parameters.envMapMode ) { - isGLSL3ShaderMaterial = true; + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - vertexShader = vertexShader.replace( versionRegex, '' ); - fragmentShader = fragmentShader.replace( versionRegex, '' ); + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - } + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - // GLSL 3.0 conversion + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; - prefixVertex = [ - '#version 300 es\n', - '#define attribute in', - '#define varying out', - '#define texture2D texture' - ].join( '\n' ) + '\n' + prefixVertex; + } - prefixFragment = [ - '#version 300 es\n', - '#define varying in', - isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', - isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor', - '#define gl_FragDepthEXT gl_FragDepth', - '#define texture2D texture', - '#define textureCube texture', - '#define texture2DProj textureProj', - '#define texture2DLodEXT textureLod', - '#define texture2DProjLodEXT textureProjLod', - '#define textureCubeLodEXT textureLod', - '#define texture2DGradEXT textureGrad', - '#define texture2DProjGradEXT textureProjGrad', - '#define textureCubeGradEXT textureGrad' - ].join( '\n' ) + '\n' + prefixFragment; + } - // Multiview + return envMapTypeDefine; - if ( numMultiviewViews > 0 ) { +} - prefixVertex = prefixVertex.replace( - '#version 300 es\n', - [ - '#version 300 es\n', - '#extension GL_OVR_multiview2 : require', - 'layout(num_views = ' + numMultiviewViews + ') in;', - '#define VIEW_ID gl_ViewID_OVR' - ].join( '\n' ) - ); +function generateEnvMapModeDefine( parameters ) { - prefixVertex = prefixVertex.replace( - [ - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform mat4 viewMatrix;', - 'uniform mat3 normalMatrix;' - ].join( '\n' ), - [ - 'uniform mat4 modelViewMatrices[' + numMultiviewViews + '];', - 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];', - 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', - 'uniform mat3 normalMatrices[' + numMultiviewViews + '];', - - '#define modelViewMatrix modelViewMatrices[VIEW_ID]', - '#define projectionMatrix projectionMatrices[VIEW_ID]', - '#define viewMatrix viewMatrices[VIEW_ID]', - '#define normalMatrix normalMatrices[VIEW_ID]' - ].join( '\n' ) - ); + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - prefixFragment = prefixFragment.replace( - '#version 300 es\n', - [ - '#version 300 es\n', - '#extension GL_OVR_multiview2 : require', - '#define VIEW_ID gl_ViewID_OVR' - ].join( '\n' ) - ); + if ( parameters.envMap ) { - prefixFragment = prefixFragment.replace( - 'uniform mat4 viewMatrix;', - [ - 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', - '#define viewMatrix viewMatrices[VIEW_ID]' - ].join( '\n' ) - ); + switch ( parameters.envMapMode ) { - } + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; } - var vertexGlsl = prefixVertex + vertexShader; - var fragmentGlsl = prefixFragment + fragmentShader; + } + + return envMapModeDefine; - // console.log( '*VERTEX*', vertexGlsl ); - // console.log( '*FRAGMENT*', fragmentGlsl ); +} - var glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); - var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); +function generateEnvMapBlendingDefine( parameters ) { - gl.attachShader( program, glVertexShader ); - gl.attachShader( program, glFragmentShader ); + var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; - // Force a particular attribute to index 0. + if ( parameters.envMap ) { - if ( material.index0AttributeName !== undefined ) { + switch ( parameters.combine ) { - gl.bindAttribLocation( program, 0, material.index0AttributeName ); + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - } else if ( parameters.morphTargets === true ) { + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - // programs with morphTargets displace position out of attribute 0 - gl.bindAttribLocation( program, 0, 'position' ); + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; } - gl.linkProgram( program ); + } - // check for link errors - if ( renderer.debug.checkShaderErrors ) { + return envMapBlendingDefine; - var programLog = gl.getProgramInfoLog( program ).trim(); - var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); - var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); +} - var runnable = true; - var haveDiagnostics = true; +function WebGLProgram( renderer, cacheKey, parameters ) { - if ( gl.getProgramParameter( program, 35714 ) === false ) { + var gl = renderer.getContext(); - runnable = false; + var defines = parameters.defines; - var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); - var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); + var vertexShader = parameters.vertexShader; + var fragmentShader = parameters.fragmentShader; + var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); + var envMapTypeDefine = generateEnvMapTypeDefine( parameters ); + var envMapModeDefine = generateEnvMapModeDefine( parameters ); + var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); - console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors ); - } else if ( programLog !== '' ) { + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); + var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); - } else if ( vertexLog === '' || fragmentLog === '' ) { + var customDefines = generateDefines( defines ); - haveDiagnostics = false; + var program = gl.createProgram(); - } + var prefixVertex, prefixFragment; - if ( haveDiagnostics ) { + if ( parameters.isRawShaderMaterial ) { - this.diagnostics = { + prefixVertex = [ - runnable: runnable, - material: material, + customDefines - programLog: programLog, + ].filter( filterEmptyLine ).join( '\n' ); - vertexShader: { + if ( prefixVertex.length > 0 ) { - log: vertexLog, - prefix: prefixVertex + prefixVertex += '\n'; - }, + } - fragmentShader: { + prefixFragment = [ - log: fragmentLog, - prefix: prefixFragment + customExtensions, + customDefines - } + ].filter( filterEmptyLine ).join( '\n' ); - }; + if ( prefixFragment.length > 0 ) { - } + prefixFragment += '\n'; } - // clean up - - gl.deleteShader( glVertexShader ); - gl.deleteShader( glFragmentShader ); - - // set up caching for uniform locations - - var cachedUniforms; + } else { - this.getUniforms = function () { + prefixVertex = [ - if ( cachedUniforms === undefined ) { + generatePrecision( parameters ), - cachedUniforms = new WebGLUniforms( gl, program ); + '#define SHADER_NAME ' + parameters.shaderName, - } - - return cachedUniforms; - - }; + customDefines, - // set up caching for attribute locations + parameters.instancing ? '#define USE_INSTANCING' : '', + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - var cachedAttributes; + '#define GAMMA_FACTOR ' + gammaFactorDefine, - this.getAttributes = function () { + '#define MAX_BONES ' + parameters.maxBones, + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', - if ( cachedAttributes === undefined ) { + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', - cachedAttributes = fetchAttributeLocations( gl, program ); + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - } + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', - return cachedAttributes; + parameters.flatShading ? '#define FLAT_SHADED' : '', - }; + parameters.skinning ? '#define USE_SKINNING' : '', + parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', - // free resource + parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', + parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - this.destroy = function () { + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - gl.deleteProgram( program ); - this.program = undefined; + parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', - }; + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - // + 'uniform mat4 modelMatrix;', + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform mat4 viewMatrix;', + 'uniform mat3 normalMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', - this.name = shader.name; - this.id = programIdCount ++; - this.cacheKey = cacheKey; - this.usedTimes = 1; - this.program = program; - this.vertexShader = glVertexShader; - this.fragmentShader = glFragmentShader; - this.numMultiviewViews = numMultiviewViews; + '#ifdef USE_INSTANCING', - return this; + ' attribute mat4 instanceMatrix;', - } + '#endif', - /** - * @author mrdoob / http://mrdoob.com/ - */ + 'attribute vec3 position;', + 'attribute vec3 normal;', + 'attribute vec2 uv;', - function WebGLPrograms( renderer, extensions, capabilities ) { - - var programs = []; - - var isWebGL2 = capabilities.isWebGL2; - var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; - var floatVertexTextures = capabilities.floatVertexTextures; - var precision = capabilities.precision; - var maxVertexUniforms = capabilities.maxVertexUniforms; - var vertexTextures = capabilities.vertexTextures; - - var shaderIDs = { - MeshDepthMaterial: 'depth', - MeshDistanceMaterial: 'distanceRGBA', - MeshNormalMaterial: 'normal', - MeshBasicMaterial: 'basic', - MeshLambertMaterial: 'lambert', - MeshPhongMaterial: 'phong', - MeshToonMaterial: 'phong', - MeshStandardMaterial: 'physical', - MeshPhysicalMaterial: 'physical', - MeshMatcapMaterial: 'matcap', - LineBasicMaterial: 'basic', - LineDashedMaterial: 'dashed', - PointsMaterial: 'points', - ShadowMaterial: 'shadow', - SpriteMaterial: 'sprite' - }; + '#ifdef USE_TANGENT', - var parameterNames = [ - "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "numMultiviewViews", - "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", - "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", - "roughnessMap", "metalnessMap", "gradientMap", - "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", - "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", - "maxBones", "useVertexTexture", "morphTargets", "morphNormals", - "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", - "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", - "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", - "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', - "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", - "sheen" - ]; + ' attribute vec4 tangent;', + '#endif', - function allocateBones( object ) { + '#ifdef USE_COLOR', - var skeleton = object.skeleton; - var bones = skeleton.bones; + ' attribute vec3 color;', - if ( floatVertexTextures ) { + '#endif', - return 1024; + '#ifdef USE_MORPHTARGETS', - } else { + ' attribute vec3 morphTarget0;', + ' attribute vec3 morphTarget1;', + ' attribute vec3 morphTarget2;', + ' attribute vec3 morphTarget3;', - // default for when object is not specified - // ( for example when prebuilding shader to be used with multiple objects ) - // - // - leave some extra space for other uniforms - // - limit here is ANGLE's 254 max uniform vectors - // (up to 54 should be safe) + ' #ifdef USE_MORPHNORMALS', - var nVertexUniforms = maxVertexUniforms; - var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); + ' attribute vec3 morphNormal0;', + ' attribute vec3 morphNormal1;', + ' attribute vec3 morphNormal2;', + ' attribute vec3 morphNormal3;', - var maxBones = Math.min( nVertexMatrices, bones.length ); + ' #else', - if ( maxBones < bones.length ) { + ' attribute vec3 morphTarget4;', + ' attribute vec3 morphTarget5;', + ' attribute vec3 morphTarget6;', + ' attribute vec3 morphTarget7;', - console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); - return 0; + ' #endif', - } + '#endif', - return maxBones; + '#ifdef USE_SKINNING', - } + ' attribute vec4 skinIndex;', + ' attribute vec4 skinWeight;', - } + '#endif', - function getTextureEncodingFromMap( map, gammaOverrideLinear ) { + '\n' - var encoding; + ].filter( filterEmptyLine ).join( '\n' ); - if ( ! map ) { + prefixFragment = [ - encoding = LinearEncoding; + customExtensions, - } else if ( map.isTexture ) { + generatePrecision( parameters ), - encoding = map.encoding; + '#define SHADER_NAME ' + parameters.shaderName, - } else if ( map.isWebGLRenderTarget ) { + customDefines, - console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); - encoding = map.texture.encoding; + parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer - } + '#define GAMMA_FACTOR ' + gammaFactorDefine, - // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point. - if ( encoding === LinearEncoding && gammaOverrideLinear ) { + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', - encoding = GammaEncoding; + parameters.map ? '#define USE_MAP' : '', + parameters.matcap ? '#define USE_MATCAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapTypeDefine : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.envMap ? '#define ' + envMapBlendingDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', + ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', + parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', + parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', + parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - } + parameters.sheen ? '#define USE_SHEEN' : '', - return encoding; + parameters.vertexTangents ? '#define USE_TANGENT' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', + parameters.vertexUvs ? '#define USE_UV' : '', + parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', - } + parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', - this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) { + parameters.flatShading ? '#define FLAT_SHADED' : '', - var shaderID = shaderIDs[ material.type ]; + parameters.doubleSided ? '#define DOUBLE_SIDED' : '', + parameters.flipSided ? '#define FLIP_SIDED' : '', - // heuristics to create shader parameters according to lights in the scene - // (not to blow over maxLights budget) + parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', + parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0; + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', - if ( material.precision !== null ) { + parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', - precision = capabilities.getMaxPrecision( material.precision ); + parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', + ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - if ( precision !== material.precision ) { + ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '', - console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + 'uniform mat4 viewMatrix;', + 'uniform vec3 cameraPosition;', + 'uniform bool isOrthographic;', - } + ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', - } + parameters.dithering ? '#define DITHERING' : '', - var currentRenderTarget = renderer.getRenderTarget(); - var numMultiviewViews = currentRenderTarget && currentRenderTarget.isWebGLMultiviewRenderTarget ? currentRenderTarget.numViews : 0; + ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ) ? + ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below + parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', + parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '', + parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', + parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', + parameters.lightMapEncoding ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '', + parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '', - var parameters = { + parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', - isWebGL2: isWebGL2, + '\n' - shaderID: shaderID, + ].filter( filterEmptyLine ).join( '\n' ); - precision: precision, + } - instancing: object.isInstancedMesh === true, + vertexShader = resolveIncludes( vertexShader ); + vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); - supportsVertexTextures: vertexTextures, - numMultiviewViews: numMultiviewViews, - outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ), - map: !! material.map, - mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ), - matcap: !! material.matcap, - matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ), - envMap: !! material.envMap, - envMapMode: material.envMap && material.envMap.mapping, - envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ), - envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ), - lightMap: !! material.lightMap, - aoMap: !! material.aoMap, - emissiveMap: !! material.emissiveMap, - emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ), - bumpMap: !! material.bumpMap, - normalMap: !! material.normalMap, - objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, - tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, - clearcoatNormalMap: !! material.clearcoatNormalMap, - displacementMap: !! material.displacementMap, - roughnessMap: !! material.roughnessMap, - metalnessMap: !! material.metalnessMap, - specularMap: !! material.specularMap, - alphaMap: !! material.alphaMap, + fragmentShader = resolveIncludes( fragmentShader ); + fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); - gradientMap: !! material.gradientMap, + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); - sheen: !! material.sheen, + if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) { - combine: material.combine, + var isGLSL3ShaderMaterial = false; - vertexTangents: ( material.normalMap && material.vertexTangents ), - vertexColors: material.vertexColors, - vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.displacementMap, - uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap, + var versionRegex = /^\s*#version\s+300\s+es\s*\n/; - fog: !! fog, - useFog: material.fog, - fogExp2: ( fog && fog.isFogExp2 ), + if ( parameters.isShaderMaterial && + vertexShader.match( versionRegex ) !== null && + fragmentShader.match( versionRegex ) !== null ) { - flatShading: material.flatShading, + isGLSL3ShaderMaterial = true; - sizeAttenuation: material.sizeAttenuation, - logarithmicDepthBuffer: logarithmicDepthBuffer, + vertexShader = vertexShader.replace( versionRegex, '' ); + fragmentShader = fragmentShader.replace( versionRegex, '' ); - skinning: material.skinning && maxBones > 0, - maxBones: maxBones, - useVertexTexture: floatVertexTextures, + } - morphTargets: material.morphTargets, - morphNormals: material.morphNormals, - maxMorphTargets: renderer.maxMorphTargets, - maxMorphNormals: renderer.maxMorphNormals, + // GLSL 3.0 conversion - numDirLights: lights.directional.length, - numPointLights: lights.point.length, - numSpotLights: lights.spot.length, - numRectAreaLights: lights.rectArea.length, - numHemiLights: lights.hemi.length, + prefixVertex = [ + '#version 300 es\n', + '#define attribute in', + '#define varying out', + '#define texture2D texture' + ].join( '\n' ) + '\n' + prefixVertex; - numDirLightShadows: lights.directionalShadowMap.length, - numPointLightShadows: lights.pointShadowMap.length, - numSpotLightShadows: lights.spotShadowMap.length, + prefixFragment = [ + '#version 300 es\n', + '#define varying in', + isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', + isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor', + '#define gl_FragDepthEXT gl_FragDepth', + '#define texture2D texture', + '#define textureCube texture', + '#define texture2DProj textureProj', + '#define texture2DLodEXT textureLod', + '#define texture2DProjLodEXT textureProjLod', + '#define textureCubeLodEXT textureLod', + '#define texture2DGradEXT textureGrad', + '#define texture2DProjGradEXT textureProjGrad', + '#define textureCubeGradEXT textureGrad' + ].join( '\n' ) + '\n' + prefixFragment; - numClippingPlanes: nClipPlanes, - numClipIntersection: nClipIntersection, + } - dithering: material.dithering, + var vertexGlsl = prefixVertex + vertexShader; + var fragmentGlsl = prefixFragment + fragmentShader; - shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, - shadowMapType: renderer.shadowMap.type, + // console.log( '*VERTEX*', vertexGlsl ); + // console.log( '*FRAGMENT*', fragmentGlsl ); - toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, - physicallyCorrectLights: renderer.physicallyCorrectLights, + var glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); + var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); - premultipliedAlpha: material.premultipliedAlpha, + gl.attachShader( program, glVertexShader ); + gl.attachShader( program, glFragmentShader ); - alphaTest: material.alphaTest, - doubleSided: material.side === DoubleSide, - flipSided: material.side === BackSide, + // Force a particular attribute to index 0. - depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false + if ( parameters.index0AttributeName !== undefined ) { - }; + gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); - return parameters; + } else if ( parameters.morphTargets === true ) { - }; + // programs with morphTargets displace position out of attribute 0 + gl.bindAttribLocation( program, 0, 'position' ); - this.getProgramCacheKey = function ( material, parameters ) { + } - var array = []; + gl.linkProgram( program ); - if ( parameters.shaderID ) { + // check for link errors + if ( renderer.debug.checkShaderErrors ) { - array.push( parameters.shaderID ); + var programLog = gl.getProgramInfoLog( program ).trim(); + var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); - } else { + var runnable = true; + var haveDiagnostics = true; - array.push( material.fragmentShader ); - array.push( material.vertexShader ); + if ( gl.getProgramParameter( program, 35714 ) === false ) { - } + runnable = false; - if ( material.defines !== undefined ) { + var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); + var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); - for ( var name in material.defines ) { + console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors ); - array.push( name ); - array.push( material.defines[ name ] ); + } else if ( programLog !== '' ) { - } + console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); - } + } else if ( vertexLog === '' || fragmentLog === '' ) { - for ( var i = 0; i < parameterNames.length; i ++ ) { + haveDiagnostics = false; - array.push( parameters[ parameterNames[ i ] ] ); + } - } + if ( haveDiagnostics ) { - array.push( material.onBeforeCompile.toString() ); + this.diagnostics = { - array.push( renderer.gammaOutput ); + runnable: runnable, - array.push( renderer.gammaFactor ); + programLog: programLog, - return array.join(); + vertexShader: { - }; + log: vertexLog, + prefix: prefixVertex - this.acquireProgram = function ( material, shader, parameters, cacheKey ) { + }, - var program; + fragmentShader: { - // Check if code has been already compiled - for ( var p = 0, pl = programs.length; p < pl; p ++ ) { + log: fragmentLog, + prefix: prefixFragment - var preexistingProgram = programs[ p ]; + } - if ( preexistingProgram.cacheKey === cacheKey ) { + }; - program = preexistingProgram; - ++ program.usedTimes; + } - break; + } - } + // Clean up - } + // Crashes in iOS9 and iOS10. #18402 + // gl.detachShader( program, glVertexShader ); + // gl.detachShader( program, glFragmentShader ); - if ( program === undefined ) { + gl.deleteShader( glVertexShader ); + gl.deleteShader( glFragmentShader ); - program = new WebGLProgram( renderer, extensions, cacheKey, material, shader, parameters ); - programs.push( program ); + // set up caching for uniform locations - } + var cachedUniforms; - return program; + this.getUniforms = function () { - }; + if ( cachedUniforms === undefined ) { - this.releaseProgram = function ( program ) { + cachedUniforms = new WebGLUniforms( gl, program ); - if ( -- program.usedTimes === 0 ) { + } - // Remove from unordered set - var i = programs.indexOf( program ); - programs[ i ] = programs[ programs.length - 1 ]; - programs.pop(); + return cachedUniforms; - // Free WebGL resources - program.destroy(); + }; - } + // set up caching for attribute locations - }; + var cachedAttributes; - // Exposed for resource monitoring & error feedback via renderer.info: - this.programs = programs; + this.getAttributes = function () { - } + if ( cachedAttributes === undefined ) { - /** - * @author fordacious / fordacious.github.io - */ + cachedAttributes = fetchAttributeLocations( gl, program ); - function WebGLProperties() { + } - var properties = new WeakMap(); + return cachedAttributes; - function get( object ) { + }; - var map = properties.get( object ); + // free resource - if ( map === undefined ) { + this.destroy = function () { - map = {}; - properties.set( object, map ); + gl.deleteProgram( program ); + this.program = undefined; - } + }; - return map; + // - } + this.name = parameters.shaderName; + this.id = programIdCount ++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + + return this; + +} + +/** + * @author mrdoob / http://mrdoob.com/ + */ + +function WebGLPrograms( renderer, extensions, capabilities ) { + + var programs = []; + + var isWebGL2 = capabilities.isWebGL2; + var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + var floatVertexTextures = capabilities.floatVertexTextures; + var precision = capabilities.precision; + var maxVertexUniforms = capabilities.maxVertexUniforms; + var vertexTextures = capabilities.vertexTextures; + + var shaderIDs = { + MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', + MeshNormalMaterial: 'normal', + MeshBasicMaterial: 'basic', + MeshLambertMaterial: 'lambert', + MeshPhongMaterial: 'phong', + MeshToonMaterial: 'toon', + MeshStandardMaterial: 'physical', + MeshPhysicalMaterial: 'physical', + MeshMatcapMaterial: 'matcap', + LineBasicMaterial: 'basic', + LineDashedMaterial: 'dashed', + PointsMaterial: 'points', + ShadowMaterial: 'shadow', + SpriteMaterial: 'sprite' + }; - function remove( object ) { + var parameterNames = [ + "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", + "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", + "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", + "roughnessMap", "metalnessMap", "gradientMap", + "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", + "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", + "maxBones", "useVertexTexture", "morphTargets", "morphNormals", + "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", + "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", + "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", + "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', + "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", + "sheen" + ]; - properties.delete( object ); + function getShaderObject( material, shaderID ) { - } + var shaderobject; - function update( object, key, value ) { + if ( shaderID ) { - properties.get( object )[ key ] = value; + var shader = ShaderLib[ shaderID ]; - } + shaderobject = { + name: material.type, + uniforms: UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - function dispose() { + } else { - properties = new WeakMap(); + shaderobject = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; } - return { - get: get, - remove: remove, - update: update, - dispose: dispose - }; + return shaderobject; } - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function painterSortStable( a, b ) { - - if ( a.groupOrder !== b.groupOrder ) { + function allocateBones( object ) { - return a.groupOrder - b.groupOrder; + var skeleton = object.skeleton; + var bones = skeleton.bones; - } else if ( a.renderOrder !== b.renderOrder ) { + if ( floatVertexTextures ) { - return a.renderOrder - b.renderOrder; + return 1024; - } else if ( a.program !== b.program ) { + } else { - return a.program.id - b.program.id; + // default for when object is not specified + // ( for example when prebuilding shader to be used with multiple objects ) + // + // - leave some extra space for other uniforms + // - limit here is ANGLE's 254 max uniform vectors + // (up to 54 should be safe) - } else if ( a.material.id !== b.material.id ) { + var nVertexUniforms = maxVertexUniforms; + var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); - return a.material.id - b.material.id; + var maxBones = Math.min( nVertexMatrices, bones.length ); - } else if ( a.z !== b.z ) { + if ( maxBones < bones.length ) { - return a.z - b.z; + console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); + return 0; - } else { + } - return a.id - b.id; + return maxBones; } } - function reversePainterSortStable( a, b ) { - - if ( a.groupOrder !== b.groupOrder ) { + function getTextureEncodingFromMap( map ) { - return a.groupOrder - b.groupOrder; + var encoding; - } else if ( a.renderOrder !== b.renderOrder ) { + if ( ! map ) { - return a.renderOrder - b.renderOrder; + encoding = LinearEncoding; - } else if ( a.z !== b.z ) { + } else if ( map.isTexture ) { - return b.z - a.z; + encoding = map.encoding; - } else { + } else if ( map.isWebGLRenderTarget ) { - return a.id - b.id; + console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); + encoding = map.texture.encoding; } + return encoding; + } + this.getParameters = function ( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) { + + var fog = scene.fog; + var environment = material.isMeshStandardMaterial ? scene.environment : null; + + var envMap = material.envMap || environment; - function WebGLRenderList() { + var shaderID = shaderIDs[ material.type ]; - var renderItems = []; - var renderItemsIndex = 0; + // heuristics to create shader parameters according to lights in the scene + // (not to blow over maxLights budget) - var opaque = []; - var transparent = []; + var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0; - var defaultProgram = { id: - 1 }; + if ( material.precision !== null ) { - function init() { + precision = capabilities.getMaxPrecision( material.precision ); - renderItemsIndex = 0; + if ( precision !== material.precision ) { - opaque.length = 0; - transparent.length = 0; + console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); + + } } - function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { + var shaderobject = getShaderObject( material, shaderID ); + material.onBeforeCompile( shaderobject, renderer ); - var renderItem = renderItems[ renderItemsIndex ]; + var currentRenderTarget = renderer.getRenderTarget(); - if ( renderItem === undefined ) { + var parameters = { - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - program: material.program || defaultProgram, - groupOrder: groupOrder, - renderOrder: object.renderOrder, - z: z, - group: group - }; + isWebGL2: isWebGL2, - renderItems[ renderItemsIndex ] = renderItem; + shaderID: shaderID, + shaderName: shaderobject.name, - } else { + uniforms: shaderobject.uniforms, + vertexShader: shaderobject.vertexShader, + fragmentShader: shaderobject.fragmentShader, + defines: material.defines, - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.program = material.program || defaultProgram; - renderItem.groupOrder = groupOrder; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + isRawShaderMaterial: material.isRawShaderMaterial, + isShaderMaterial: material.isShaderMaterial, - } + precision: precision, - renderItemsIndex ++; + instancing: object.isInstancedMesh === true, + + supportsVertexTextures: vertexTextures, + outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding, + map: !! material.map, + mapEncoding: getTextureEncodingFromMap( material.map ), + matcap: !! material.matcap, + matcapEncoding: getTextureEncodingFromMap( material.matcap ), + envMap: !! envMap, + envMapMode: envMap && envMap.mapping, + envMapEncoding: getTextureEncodingFromMap( envMap ), + envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ), + lightMap: !! material.lightMap, + lightMapEncoding: getTextureEncodingFromMap( material.lightMap ), + aoMap: !! material.aoMap, + emissiveMap: !! material.emissiveMap, + emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ), + bumpMap: !! material.bumpMap, + normalMap: !! material.normalMap, + objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, + tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, + clearcoatMap: !! material.clearcoatMap, + clearcoatRoughnessMap: !! material.clearcoatRoughnessMap, + clearcoatNormalMap: !! material.clearcoatNormalMap, + displacementMap: !! material.displacementMap, + roughnessMap: !! material.roughnessMap, + metalnessMap: !! material.metalnessMap, + specularMap: !! material.specularMap, + alphaMap: !! material.alphaMap, + + gradientMap: !! material.gradientMap, + + sheen: !! material.sheen, + + combine: material.combine, + + vertexTangents: ( material.normalMap && material.vertexTangents ), + vertexColors: material.vertexColors, + vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap, + uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap, + + fog: !! fog, + useFog: material.fog, + fogExp2: ( fog && fog.isFogExp2 ), + + flatShading: material.flatShading, + + sizeAttenuation: material.sizeAttenuation, + logarithmicDepthBuffer: logarithmicDepthBuffer, - return renderItem; + skinning: material.skinning && maxBones > 0, + maxBones: maxBones, + useVertexTexture: floatVertexTextures, - } + morphTargets: material.morphTargets, + morphNormals: material.morphNormals, + maxMorphTargets: renderer.maxMorphTargets, + maxMorphNormals: renderer.maxMorphNormals, - function push( object, geometry, material, groupOrder, z, group ) { + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, - var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, - ( material.transparent === true ? transparent : opaque ).push( renderItem ); + numClippingPlanes: nClipPlanes, + numClipIntersection: nClipIntersection, - } + dithering: material.dithering, - function unshift( object, geometry, material, groupOrder, z, group ) { + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, - var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); + toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, + physicallyCorrectLights: renderer.physicallyCorrectLights, - ( material.transparent === true ? transparent : opaque ).unshift( renderItem ); + premultipliedAlpha: material.premultipliedAlpha, - } + alphaTest: material.alphaTest, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, - function sort() { + depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, - if ( opaque.length > 1 ) { opaque.sort( painterSortStable ); } - if ( transparent.length > 1 ) { transparent.sort( reversePainterSortStable ); } + index0AttributeName: material.index0AttributeName, - } + extensionDerivatives: material.extensions && material.extensions.derivatives, + extensionFragDepth: material.extensions && material.extensions.fragDepth, + extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, + extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, - return { - opaque: opaque, - transparent: transparent, + rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null, + rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null, + rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null, - init: init, - push: push, - unshift: unshift, + onBeforeCompile: material.onBeforeCompile - sort: sort }; - } + return parameters; + + }; - function WebGLRenderLists() { + this.getProgramCacheKey = function ( parameters ) { - var lists = new WeakMap(); + var array = []; - function onSceneDispose( event ) { + if ( parameters.shaderID ) { - var scene = event.target; + array.push( parameters.shaderID ); - scene.removeEventListener( 'dispose', onSceneDispose ); + } else { - lists.delete( scene ); + array.push( parameters.fragmentShader ); + array.push( parameters.vertexShader ); } - function get( scene, camera ) { + if ( parameters.defines !== undefined ) { - var cameras = lists.get( scene ); - var list; - if ( cameras === undefined ) { + for ( var name in parameters.defines ) { - list = new WebGLRenderList(); - lists.set( scene, new WeakMap() ); - lists.get( scene ).set( camera, list ); + array.push( name ); + array.push( parameters.defines[ name ] ); - scene.addEventListener( 'dispose', onSceneDispose ); + } - } else { + } - list = cameras.get( camera ); - if ( list === undefined ) { + if ( parameters.isRawShaderMaterial === undefined ) { - list = new WebGLRenderList(); - cameras.set( camera, list ); + for ( var i = 0; i < parameterNames.length; i ++ ) { - } + array.push( parameters[ parameterNames[ i ] ] ); } - return list; + array.push( renderer.outputEncoding ); + array.push( renderer.gammaFactor ); } - function dispose() { + array.push( parameters.onBeforeCompile.toString() ); - lists = new WeakMap(); + return array.join(); - } + }; - return { - get: get, - dispose: dispose - }; + this.acquireProgram = function ( parameters, cacheKey ) { - } + var program; - /** - * @author mrdoob / http://mrdoob.com/ - */ + // Check if code has been already compiled + for ( var p = 0, pl = programs.length; p < pl; p ++ ) { - function UniformsCache() { + var preexistingProgram = programs[ p ]; - var lights = {}; + if ( preexistingProgram.cacheKey === cacheKey ) { - return { + program = preexistingProgram; + ++ program.usedTimes; - get: function ( light ) { + break; - if ( lights[ light.id ] !== undefined ) { + } - return lights[ light.id ]; + } - } + if ( program === undefined ) { - var uniforms; + program = new WebGLProgram( renderer, cacheKey, parameters ); + programs.push( program ); - switch ( light.type ) { + } - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color(), + return program; - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + }; - case 'SpotLight': - uniforms = { - position: new Vector3(), - direction: new Vector3(), - color: new Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; + this.releaseProgram = function ( program ) { - case 'PointLight': - uniforms = { - position: new Vector3(), - color: new Color(), - distance: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2(), - shadowCameraNear: 1, - shadowCameraFar: 1000 - }; - break; + if ( -- program.usedTimes === 0 ) { - case 'HemisphereLight': - uniforms = { - direction: new Vector3(), - skyColor: new Color(), - groundColor: new Color() - }; - break; + // Remove from unordered set + var i = programs.indexOf( program ); + programs[ i ] = programs[ programs.length - 1 ]; + programs.pop(); - case 'RectAreaLight': - uniforms = { - color: new Color(), - position: new Vector3(), - halfWidth: new Vector3(), - halfHeight: new Vector3() - // TODO (abelnation): set RectAreaLight shadow uniforms - }; - break; + // Free WebGL resources + program.destroy(); - } + } - lights[ light.id ] = uniforms; + }; - return uniforms; + // Exposed for resource monitoring & error feedback via renderer.info: + this.programs = programs; - } +} - }; +/** + * @author fordacious / fordacious.github.io + */ - } +function WebGLProperties() { + + var properties = new WeakMap(); + + function get( object ) { - var nextVersion = 0; + var map = properties.get( object ); - function shadowCastingLightsFirst( lightA, lightB ) { + if ( map === undefined ) { - return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 ); + map = {}; + properties.set( object, map ); + + } + + return map; } - function WebGLLights() { + function remove( object ) { - var cache = new UniformsCache(); + properties.delete( object ); - var state = { + } - version: 0, + function update( object, key, value ) { - hash: { - directionalLength: - 1, - pointLength: - 1, - spotLength: - 1, - rectAreaLength: - 1, - hemiLength: - 1, + properties.get( object )[ key ] = value; - numDirectionalShadows: - 1, - numPointShadows: - 1, - numSpotShadows: - 1, - }, + } - ambient: [ 0, 0, 0 ], - probe: [], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - rectArea: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + function dispose() { - numDirectionalShadows: - 1, - numPointShadows: - 1, - numSpotShadows: - 1 + properties = new WeakMap(); - }; + } - for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); } + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; - var vector3 = new Vector3(); - var matrix4 = new Matrix4(); - var matrix42 = new Matrix4(); +} - function setup( lights, shadows, camera ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var r = 0, g = 0, b = 0; +function painterSortStable( a, b ) { - for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); } + if ( a.groupOrder !== b.groupOrder ) { - var directionalLength = 0; - var pointLength = 0; - var spotLength = 0; - var rectAreaLength = 0; - var hemiLength = 0; + return a.groupOrder - b.groupOrder; - var numDirectionalShadows = 0; - var numPointShadows = 0; - var numSpotShadows = 0; + } else if ( a.renderOrder !== b.renderOrder ) { - var viewMatrix = camera.matrixWorldInverse; + return a.renderOrder - b.renderOrder; - lights.sort( shadowCastingLightsFirst ); + } else if ( a.program !== b.program ) { - for ( var i = 0, l = lights.length; i < l; i ++ ) { + return a.program.id - b.program.id; - var light = lights[ i ]; + } else if ( a.material.id !== b.material.id ) { - var color = light.color; - var intensity = light.intensity; - var distance = light.distance; + return a.material.id - b.material.id; - var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + } else if ( a.z !== b.z ) { - if ( light.isAmbientLight ) { + return a.z - b.z; - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + } else { - } else if ( light.isLightProbe ) { + return a.id - b.id; - for ( var j = 0; j < 9; j ++ ) { + } - state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); +} - } +function reversePainterSortStable( a, b ) { - } else if ( light.isDirectionalLight ) { + if ( a.groupOrder !== b.groupOrder ) { - var uniforms = cache.get( light ); + return a.groupOrder - b.groupOrder; - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + } else if ( a.renderOrder !== b.renderOrder ) { - uniforms.shadow = light.castShadow; + return a.renderOrder - b.renderOrder; - if ( light.castShadow ) { + } else if ( a.z !== b.z ) { - var shadow = light.shadow; + return b.z - a.z; - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; + } else { - state.directionalShadowMap[ directionalLength ] = shadowMap; - state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + return a.id - b.id; - numDirectionalShadows ++; + } - } +} - state.directional[ directionalLength ] = uniforms; - directionalLength ++; +function WebGLRenderList() { - } else if ( light.isSpotLight ) { + var renderItems = []; + var renderItemsIndex = 0; - var uniforms = cache.get( light ); + var opaque = []; + var transparent = []; - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + var defaultProgram = { id: - 1 }; - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + function init() { - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + renderItemsIndex = 0; - uniforms.coneCos = Math.cos( light.angle ); - uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); - uniforms.decay = light.decay; + opaque.length = 0; + transparent.length = 0; - uniforms.shadow = light.castShadow; + } - if ( light.castShadow ) { + function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { - var shadow = light.shadow; + var renderItem = renderItems[ renderItemsIndex ]; - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; + if ( renderItem === undefined ) { - state.spotShadowMap[ spotLength ] = shadowMap; - state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + program: material.program || defaultProgram, + groupOrder: groupOrder, + renderOrder: object.renderOrder, + z: z, + group: group + }; - numSpotShadows ++; + renderItems[ renderItemsIndex ] = renderItem; - } + } else { - state.spot[ spotLength ] = uniforms; + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.program = material.program || defaultProgram; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; - spotLength ++; + } - } else if ( light.isRectAreaLight ) { + renderItemsIndex ++; - var uniforms = cache.get( light ); + return renderItem; - // (a) intensity is the total visible light emitted - //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); + } - // (b) intensity is the brightness of the light - uniforms.color.copy( color ).multiplyScalar( intensity ); + function push( object, geometry, material, groupOrder, z, group ) { - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); - // extract local rotation of light to derive width/height half vectors - matrix42.identity(); - matrix4.copy( light.matrixWorld ); - matrix4.premultiply( viewMatrix ); - matrix42.extractRotation( matrix4 ); + ( material.transparent === true ? transparent : opaque ).push( renderItem ); - uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); - uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + } - uniforms.halfWidth.applyMatrix4( matrix42 ); - uniforms.halfHeight.applyMatrix4( matrix42 ); + function unshift( object, geometry, material, groupOrder, z, group ) { - // TODO (abelnation): RectAreaLight distance? - // uniforms.distance = distance; + var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); - state.rectArea[ rectAreaLength ] = uniforms; + ( material.transparent === true ? transparent : opaque ).unshift( renderItem ); - rectAreaLength ++; + } - } else if ( light.isPointLight ) { + function sort( customOpaqueSort, customTransparentSort ) { - var uniforms = cache.get( light ); + if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable ); + if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable ); - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + } - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = light.decay; + function finish() { - uniforms.shadow = light.castShadow; + // Clear references from inactive renderItems in the list - if ( light.castShadow ) { + for ( var i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) { - var shadow = light.shadow; + var renderItem = renderItems[ i ]; - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; - uniforms.shadowCameraNear = shadow.camera.near; - uniforms.shadowCameraFar = shadow.camera.far; + if ( renderItem.id === null ) break; - state.pointShadowMap[ pointLength ] = shadowMap; - state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.program = null; + renderItem.group = null; - numPointShadows ++; + } - } + } - state.point[ pointLength ] = uniforms; + return { + opaque: opaque, + transparent: transparent, - pointLength ++; + init: init, + push: push, + unshift: unshift, + finish: finish, - } else if ( light.isHemisphereLight ) { + sort: sort + }; - var uniforms = cache.get( light ); +} - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); +function WebGLRenderLists() { - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + var lists = new WeakMap(); - state.hemi[ hemiLength ] = uniforms; + function onSceneDispose( event ) { - hemiLength ++; + var scene = event.target; - } + scene.removeEventListener( 'dispose', onSceneDispose ); - } + lists.delete( scene ); - state.ambient[ 0 ] = r; - state.ambient[ 1 ] = g; - state.ambient[ 2 ] = b; + } - var hash = state.hash; + function get( scene, camera ) { - if ( hash.directionalLength !== directionalLength || - hash.pointLength !== pointLength || - hash.spotLength !== spotLength || - hash.rectAreaLength !== rectAreaLength || - hash.hemiLength !== hemiLength || - hash.numDirectionalShadows !== numDirectionalShadows || - hash.numPointShadows !== numPointShadows || - hash.numSpotShadows !== numSpotShadows ) { + var cameras = lists.get( scene ); + var list; + if ( cameras === undefined ) { - state.directional.length = directionalLength; - state.spot.length = spotLength; - state.rectArea.length = rectAreaLength; - state.point.length = pointLength; - state.hemi.length = hemiLength; + list = new WebGLRenderList(); + lists.set( scene, new WeakMap() ); + lists.get( scene ).set( camera, list ); - state.directionalShadowMap.length = numDirectionalShadows; - state.pointShadowMap.length = numPointShadows; - state.spotShadowMap.length = numSpotShadows; - state.directionalShadowMatrix.length = numDirectionalShadows; - state.pointShadowMatrix.length = numPointShadows; - state.spotShadowMatrix.length = numSpotShadows; + scene.addEventListener( 'dispose', onSceneDispose ); - hash.directionalLength = directionalLength; - hash.pointLength = pointLength; - hash.spotLength = spotLength; - hash.rectAreaLength = rectAreaLength; - hash.hemiLength = hemiLength; + } else { - hash.numDirectionalShadows = numDirectionalShadows; - hash.numPointShadows = numPointShadows; - hash.numSpotShadows = numSpotShadows; + list = cameras.get( camera ); + if ( list === undefined ) { - state.version = nextVersion ++; + list = new WebGLRenderList(); + cameras.set( camera, list ); } } - return { - setup: setup, - state: state - }; + return list; } - /** - * @author Mugen87 / https://github.com/Mugen87 - */ + function dispose() { - function WebGLRenderState() { + lists = new WeakMap(); - var lights = new WebGLLights(); + } - var lightsArray = []; - var shadowsArray = []; + return { + get: get, + dispose: dispose + }; - function init() { +} - lightsArray.length = 0; - shadowsArray.length = 0; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function UniformsCache() { - function pushLight( light ) { + var lights = {}; - lightsArray.push( light ); + return { - } + get: function ( light ) { - function pushShadow( shadowLight ) { + if ( lights[ light.id ] !== undefined ) { - shadowsArray.push( shadowLight ); + return lights[ light.id ]; - } + } - function setupLights( camera ) { + var uniforms; - lights.setup( lightsArray, shadowsArray, camera ); + switch ( light.type ) { - } + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; - var state = { - lightsArray: lightsArray, - shadowsArray: shadowsArray, + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; - lights: lights - }; + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; - return { - init: init, - state: state, - setupLights: setupLights, + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - pushLight: pushLight, - pushShadow: pushShadow - }; + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; - } + } - function WebGLRenderStates() { + lights[ light.id ] = uniforms; - var renderStates = new WeakMap(); + return uniforms; - function onSceneDispose( event ) { + } - var scene = event.target; + }; - scene.removeEventListener( 'dispose', onSceneDispose ); +} - renderStates.delete( scene ); +function ShadowUniformsCache() { - } + var lights = {}; - function get( scene, camera ) { + return { - var renderState; + get: function ( light ) { - if ( renderStates.has( scene ) === false ) { + if ( lights[ light.id ] !== undefined ) { - renderState = new WebGLRenderState(); - renderStates.set( scene, new WeakMap() ); - renderStates.get( scene ).set( camera, renderState ); + return lights[ light.id ]; - scene.addEventListener( 'dispose', onSceneDispose ); + } - } else { + var uniforms; - if ( renderStates.get( scene ).has( camera ) === false ) { + switch ( light.type ) { - renderState = new WebGLRenderState(); - renderStates.get( scene ).set( camera, renderState ); + case 'DirectionalLight': + uniforms = { + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - } else { + case 'SpotLight': + uniforms = { + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - renderState = renderStates.get( scene ).get( camera ); + case 'PointLight': + uniforms = { + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; - } + // TODO (abelnation): set RectAreaLight shadow uniforms } - return renderState; + lights[ light.id ] = uniforms; - } - - function dispose() { - - renderStates = new WeakMap(); + return uniforms; } - return { - get: get, - dispose: dispose - }; + }; - } +} - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / https://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } - */ - function MeshDepthMaterial( parameters ) { - Material.call( this ); +var nextVersion = 0; - this.type = 'MeshDepthMaterial'; +function shadowCastingLightsFirst( lightA, lightB ) { - this.depthPacking = BasicDepthPacking; + return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 ); - this.skinning = false; - this.morphTargets = false; +} - this.map = null; +function WebGLLights() { - this.alphaMap = null; + var cache = new UniformsCache(); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + var shadowCache = ShadowUniformsCache(); - this.wireframe = false; - this.wireframeLinewidth = 1; + var state = { - this.fog = false; + version: 0, - this.setValues( parameters ); + hash: { + directionalLength: - 1, + pointLength: - 1, + spotLength: - 1, + rectAreaLength: - 1, + hemiLength: - 1, - } + numDirectionalShadows: - 1, + numPointShadows: - 1, + numSpotShadows: - 1 + }, - MeshDepthMaterial.prototype = Object.create( Material.prototype ); - MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; + ambient: [ 0, 0, 0 ], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadow: [], + spotShadowMap: [], + spotShadowMatrix: [], + rectArea: [], + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [] - MeshDepthMaterial.prototype.isMeshDepthMaterial = true; + }; - MeshDepthMaterial.prototype.copy = function ( source ) { + for ( var i = 0; i < 9; i ++ ) state.probe.push( new Vector3() ); - Material.prototype.copy.call( this, source ); + var vector3 = new Vector3(); + var matrix4 = new Matrix4(); + var matrix42 = new Matrix4(); - this.depthPacking = source.depthPacking; + function setup( lights, shadows, camera ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + var r = 0, g = 0, b = 0; - this.map = source.map; + for ( var i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 ); - this.alphaMap = source.alphaMap; + var directionalLength = 0; + var pointLength = 0; + var spotLength = 0; + var rectAreaLength = 0; + var hemiLength = 0; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + var numDirectionalShadows = 0; + var numPointShadows = 0; + var numSpotShadows = 0; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + var viewMatrix = camera.matrixWorldInverse; - return this; + lights.sort( shadowCastingLightsFirst ); - }; + for ( var i = 0, l = lights.length; i < l; i ++ ) { - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * referencePosition: , - * nearDistance: , - * farDistance: , - * - * skinning: , - * morphTargets: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: - * - * } - */ + var light = lights[ i ]; - function MeshDistanceMaterial( parameters ) { + var color = light.color; + var intensity = light.intensity; + var distance = light.distance; - Material.call( this ); + var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - this.type = 'MeshDistanceMaterial'; + if ( light.isAmbientLight ) { - this.referencePosition = new Vector3(); - this.nearDistance = 1; - this.farDistance = 1000; + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - this.skinning = false; - this.morphTargets = false; + } else if ( light.isLightProbe ) { - this.map = null; + for ( var j = 0; j < 9; j ++ ) { - this.alphaMap = null; + state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + } - this.fog = false; + } else if ( light.isDirectionalLight ) { - this.setValues( parameters ); + var uniforms = cache.get( light ); - } + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - MeshDistanceMaterial.prototype = Object.create( Material.prototype ); - MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial; + if ( light.castShadow ) { - MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; + var shadow = light.shadow; - MeshDistanceMaterial.prototype.copy = function ( source ) { + var shadowUniforms = shadowCache.get( light ); - Material.prototype.copy.call( this, source ); + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; - this.referencePosition.copy( source.referencePosition ); - this.nearDistance = source.nearDistance; - this.farDistance = source.farDistance; + state.directionalShadow[ directionalLength ] = shadowUniforms; + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + numDirectionalShadows ++; - this.map = source.map; + } - this.alphaMap = source.alphaMap; + state.directional[ directionalLength ] = uniforms; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + directionalLength ++; - return this; + } else if ( light.isSpotLight ) { - }; + var uniforms = cache.get( light ); - var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpack2HalfToRGBA ( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = light.decay; - var _frustum = new Frustum(), + if ( light.castShadow ) { - _shadowMapSize = new Vector2(), - _viewportSize = new Vector2(), + var shadow = light.shadow; - _viewport = new Vector4(), + var shadowUniforms = shadowCache.get( light ); - _depthMaterials = [], - _distanceMaterials = [], + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; - _materialCache = {}; + state.spotShadow[ spotLength ] = shadowUniforms; + state.spotShadowMap[ spotLength ] = shadowMap; + state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; + numSpotShadows ++; - var shadowMaterialVertical = new ShaderMaterial( { + } - defines: { - SAMPLE_RATE: 2.0 / 8.0, - HALF_SAMPLE_RATE: 1.0 / 8.0 - }, + state.spot[ spotLength ] = uniforms; - uniforms: { - shadow_pass: { value: null }, - resolution: { value: new Vector2() }, - radius: { value: 4.0 } - }, + spotLength ++; - vertexShader: vsm_vert, + } else if ( light.isRectAreaLight ) { - fragmentShader: vsm_frag + var uniforms = cache.get( light ); - } ); + // (a) intensity is the total visible light emitted + //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); - var shadowMaterialHorizonal = shadowMaterialVertical.clone(); - shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1; + // (b) intensity is the brightness of the light + uniforms.color.copy( color ).multiplyScalar( intensity ); - var fullScreenTri = new BufferGeometry(); - fullScreenTri.setAttribute( - "position", - new BufferAttribute( - new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), - 3 - ) - ); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); - var scope = this; + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); - this.enabled = false; + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); - this.autoUpdate = true; - this.needsUpdate = false; + // TODO (abelnation): RectAreaLight distance? + // uniforms.distance = distance; - this.type = PCFShadowMap; + state.rectArea[ rectAreaLength ] = uniforms; - this.render = function ( lights, scene, camera ) { + rectAreaLength ++; - if ( scope.enabled === false ) { return; } - if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; } + } else if ( light.isPointLight ) { - if ( lights.length === 0 ) { return; } + var uniforms = cache.get( light ); - var currentRenderTarget = _renderer.getRenderTarget(); - var activeCubeFace = _renderer.getActiveCubeFace(); - var activeMipmapLevel = _renderer.getActiveMipmapLevel(); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - var _state = _renderer.state; + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = light.decay; - // Set GL state for depth map. - _state.setBlending( NoBlending ); - _state.buffers.color.setClear( 1, 1, 1, 1 ); - _state.buffers.depth.setTest( true ); - _state.setScissorTest( false ); + if ( light.castShadow ) { - // render depth map + var shadow = light.shadow; - for ( var i = 0, il = lights.length; i < il; i ++ ) { + var shadowUniforms = shadowCache.get( light ); - var light = lights[ i ]; - var shadow = light.shadow; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; - if ( shadow === undefined ) { + state.pointShadow[ pointLength ] = shadowUniforms; + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + numPointShadows ++; } - _shadowMapSize.copy( shadow.mapSize ); + state.point[ pointLength ] = uniforms; - var shadowFrameExtents = shadow.getFrameExtents(); + pointLength ++; - _shadowMapSize.multiply( shadowFrameExtents ); + } else if ( light.isHemisphereLight ) { - _viewportSize.copy( shadow.mapSize ); + var uniforms = cache.get( light ); - if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) { + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); - console.warn( 'THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing' ); + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); - if ( _shadowMapSize.x > maxTextureSize ) { + state.hemi[ hemiLength ] = uniforms; - _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x ); - _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; - shadow.mapSize.x = _viewportSize.x; - - } + hemiLength ++; - if ( _shadowMapSize.y > maxTextureSize ) { + } - _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y ); - _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; - shadow.mapSize.y = _viewportSize.y; + } - } + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; - } + var hash = state.hash; - if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + if ( hash.directionalLength !== directionalLength || + hash.pointLength !== pointLength || + hash.spotLength !== spotLength || + hash.rectAreaLength !== rectAreaLength || + hash.hemiLength !== hemiLength || + hash.numDirectionalShadows !== numDirectionalShadows || + hash.numPointShadows !== numPointShadows || + hash.numSpotShadows !== numSpotShadows ) { - var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - shadow.map.texture.name = light.name + ".shadowMap"; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotShadowMatrix.length = numSpotShadows; - shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; - shadow.camera.updateProjectionMatrix(); + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; - } + state.version = nextVersion ++; - if ( shadow.map === null ) { + } - var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + } - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - shadow.map.texture.name = light.name + ".shadowMap"; + return { + setup: setup, + state: state + }; - shadow.camera.updateProjectionMatrix(); +} - } +/** + * @author Mugen87 / https://github.com/Mugen87 + */ - _renderer.setRenderTarget( shadow.map ); - _renderer.clear(); +function WebGLRenderState() { - var viewportCount = shadow.getViewportCount(); + var lights = new WebGLLights(); - for ( var vp = 0; vp < viewportCount; vp ++ ) { + var lightsArray = []; + var shadowsArray = []; - var viewport = shadow.getViewport( vp ); + function init() { - _viewport.set( - _viewportSize.x * viewport.x, - _viewportSize.y * viewport.y, - _viewportSize.x * viewport.z, - _viewportSize.y * viewport.w - ); + lightsArray.length = 0; + shadowsArray.length = 0; - _state.viewport( _viewport ); + } - shadow.updateMatrices( light, vp ); + function pushLight( light ) { - _frustum = shadow.getFrustum(); + lightsArray.push( light ); - renderObject( scene, camera, shadow.camera, light, this.type ); + } - } + function pushShadow( shadowLight ) { - // do blur pass for VSM + shadowsArray.push( shadowLight ); - if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { + } - VSMPass( shadow, camera ); + function setupLights( camera ) { - } + lights.setup( lightsArray, shadowsArray, camera ); - } + } - scope.needsUpdate = false; + var state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, - _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); + lights: lights + }; - }; + return { + init: init, + state: state, + setupLights: setupLights, - function VSMPass( shadow, camera ) { + pushLight: pushLight, + pushShadow: pushShadow + }; - var geometry = _objects.update( fullScreenMesh ); +} - // vertical pass +function WebGLRenderStates() { - shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; - shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; - shadowMaterialVertical.uniforms.radius.value = shadow.radius; - _renderer.setRenderTarget( shadow.mapPass ); - _renderer.clear(); - _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); + var renderStates = new WeakMap(); - // horizonal pass + function onSceneDispose( event ) { - shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture; - shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize; - shadowMaterialHorizonal.uniforms.radius.value = shadow.radius; - _renderer.setRenderTarget( shadow.map ); - _renderer.clear(); - _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null ); + var scene = event.target; - } + scene.removeEventListener( 'dispose', onSceneDispose ); - function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) { + renderStates.delete( scene ); - var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; + } - var material = _depthMaterials[ index ]; + function get( scene, camera ) { - if ( material === undefined ) { + var renderState; - material = new MeshDepthMaterial( { + if ( renderStates.has( scene ) === false ) { - depthPacking: RGBADepthPacking, + renderState = new WebGLRenderState(); + renderStates.set( scene, new WeakMap() ); + renderStates.get( scene ).set( camera, renderState ); - morphTargets: useMorphing, - skinning: useSkinning + scene.addEventListener( 'dispose', onSceneDispose ); - } ); + } else { - _depthMaterials[ index ] = material; + if ( renderStates.get( scene ).has( camera ) === false ) { - } + renderState = new WebGLRenderState(); + renderStates.get( scene ).set( camera, renderState ); - return material; + } else { - } + renderState = renderStates.get( scene ).get( camera ); - function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) { + } - var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; + } - var material = _distanceMaterials[ index ]; + return renderState; - if ( material === undefined ) { + } - material = new MeshDistanceMaterial( { + function dispose() { - morphTargets: useMorphing, - skinning: useSkinning + renderStates = new WeakMap(); - } ); + } - _distanceMaterials[ index ] = material; + return { + get: get, + dispose: dispose + }; - } +} - return material; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / https://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * opacity: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - } +function MeshDepthMaterial( parameters ) { - function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { + Material.call( this ); - var geometry = object.geometry; + this.type = 'MeshDepthMaterial'; - var result = null; + this.depthPacking = BasicDepthPacking; - var getMaterialVariant = getDepthMaterialVariant; - var customMaterial = object.customDepthMaterial; + this.skinning = false; + this.morphTargets = false; - if ( light.isPointLight === true ) { + this.map = null; - getMaterialVariant = getDistanceMaterialVariant; - customMaterial = object.customDistanceMaterial; + this.alphaMap = null; - } + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - if ( customMaterial === undefined ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - var useMorphing = false; + this.fog = false; - if ( material.morphTargets === true ) { + this.setValues( parameters ); - if ( geometry.isBufferGeometry === true ) { +} - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; +MeshDepthMaterial.prototype = Object.create( Material.prototype ); +MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - } else if ( geometry.isGeometry === true ) { +MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; +MeshDepthMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - } + this.depthPacking = source.depthPacking; - var useSkinning = false; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - if ( object.isSkinnedMesh === true ) { + this.map = source.map; - if ( material.skinning === true ) { + this.alphaMap = source.alphaMap; - useSkinning = true; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - } else { + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); + return this; - } +}; - } +/** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * referencePosition: , + * nearDistance: , + * farDistance: , + * + * skinning: , + * morphTargets: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: + * + * } + */ - var useInstancing = object.isInstancedMesh === true; +function MeshDistanceMaterial( parameters ) { - result = getMaterialVariant( useMorphing, useSkinning, useInstancing ); + Material.call( this ); - } else { + this.type = 'MeshDistanceMaterial'; - result = customMaterial; + this.referencePosition = new Vector3(); + this.nearDistance = 1; + this.farDistance = 1000; - } + this.skinning = false; + this.morphTargets = false; - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + this.map = null; - // in this case we need a unique material instance reflecting the - // appropriate state + this.alphaMap = null; - var keyA = result.uuid, keyB = material.uuid; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - var materialsForVariant = _materialCache[ keyA ]; + this.fog = false; - if ( materialsForVariant === undefined ) { + this.setValues( parameters ); - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; +} - } +MeshDistanceMaterial.prototype = Object.create( Material.prototype ); +MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial; - var cachedMaterial = materialsForVariant[ keyB ]; +MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; - if ( cachedMaterial === undefined ) { +MeshDistanceMaterial.prototype.copy = function ( source ) { - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + Material.prototype.copy.call( this, source ); - } + this.referencePosition.copy( source.referencePosition ); + this.nearDistance = source.nearDistance; + this.farDistance = source.farDistance; - result = cachedMaterial; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - } + this.map = source.map; - result.visible = material.visible; - result.wireframe = material.wireframe; + this.alphaMap = source.alphaMap; - if ( type === VSMShadowMap ) { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; + return this; - } else { +}; - result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; +var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; - } +var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; - result.clipIntersection = material.clipIntersection; +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; +function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { - if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { + var _frustum = new Frustum(), - result.referencePosition.setFromMatrixPosition( light.matrixWorld ); - result.nearDistance = shadowCameraNear; - result.farDistance = shadowCameraFar; + _shadowMapSize = new Vector2(), + _viewportSize = new Vector2(), - } + _viewport = new Vector4(), - return result; + _depthMaterials = [], + _distanceMaterials = [], - } + _materialCache = {}; - function renderObject( object, camera, shadowCamera, light, type ) { + var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; - if ( object.visible === false ) { return; } + var shadowMaterialVertical = new ShaderMaterial( { - var visible = object.layers.test( camera.layers ); + defines: { + SAMPLE_RATE: 2.0 / 8.0, + HALF_SAMPLE_RATE: 1.0 / 8.0 + }, - if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4.0 } + }, - if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + vertexShader: vsm_vert, - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + fragmentShader: vsm_frag - var geometry = _objects.update( object ); - var material = object.material; + } ); - if ( Array.isArray( material ) ) { + var shadowMaterialHorizonal = shadowMaterialVertical.clone(); + shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1; - var groups = geometry.groups; + var fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + "position", + new BufferAttribute( + new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), + 3 + ) + ); - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); - var group = groups[ k ]; - var groupMaterial = material[ group.materialIndex ]; + var scope = this; - if ( groupMaterial && groupMaterial.visible ) { + this.enabled = false; - var depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); + this.autoUpdate = true; + this.needsUpdate = false; - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + this.type = PCFShadowMap; - } + this.render = function ( lights, scene, camera ) { - } + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - } else if ( material.visible ) { + if ( lights.length === 0 ) return; - var depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); + var currentRenderTarget = _renderer.getRenderTarget(); + var activeCubeFace = _renderer.getActiveCubeFace(); + var activeMipmapLevel = _renderer.getActiveMipmapLevel(); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + var _state = _renderer.state; - } + // Set GL state for depth map. + _state.setBlending( NoBlending ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); - } + // render depth map - } + for ( var i = 0, il = lights.length; i < il; i ++ ) { - var children = object.children; + var light = lights[ i ]; + var shadow = light.shadow; - for ( var i = 0, l = children.length; i < l; i ++ ) { + if ( shadow === undefined ) { - renderObject( children[ i ], camera, shadowCamera, light, type ); + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; } - } + _shadowMapSize.copy( shadow.mapSize ); - } + var shadowFrameExtents = shadow.getFrameExtents(); - /** - * @author mrdoob / http://mrdoob.com/ - */ + _shadowMapSize.multiply( shadowFrameExtents ); - function WebGLState( gl, extensions, capabilities ) { + _viewportSize.copy( shadow.mapSize ); - var isWebGL2 = capabilities.isWebGL2; + if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) { - function ColorBuffer() { + if ( _shadowMapSize.x > maxTextureSize ) { - var locked = false; + _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x ); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; - var color = new Vector4(); - var currentColorMask = null; - var currentColorClear = new Vector4( 0, 0, 0, 0 ); + } - return { + if ( _shadowMapSize.y > maxTextureSize ) { - setMask: function ( colorMask ) { + _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y ); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; - if ( currentColorMask !== colorMask && ! locked ) { + } - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + } - } + if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - }, + var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; - setLocked: function ( lock ) { + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + ".shadowMap"; - locked = lock; + shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - }, + shadow.camera.updateProjectionMatrix(); - setClear: function ( r, g, b, a, premultipliedAlpha ) { + } - if ( premultipliedAlpha === true ) { + if ( shadow.map === null ) { - r *= a; g *= a; b *= a; + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - } + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + ".shadowMap"; - color.set( r, g, b, a ); + shadow.camera.updateProjectionMatrix(); - if ( currentColorClear.equals( color ) === false ) { + } - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); - } + var viewportCount = shadow.getViewportCount(); - }, + for ( var vp = 0; vp < viewportCount; vp ++ ) { - reset: function () { + var viewport = shadow.getViewport( vp ); - locked = false; + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); - currentColorMask = null; - currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + _state.viewport( _viewport ); - } + shadow.updateMatrices( light, vp ); - }; + _frustum = shadow.getFrustum(); - } + renderObject( scene, camera, shadow.camera, light, this.type ); - function DepthBuffer() { + } - var locked = false; + // do blur pass for VSM - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { - return { + VSMPass( shadow, camera ); - setTest: function ( depthTest ) { + } - if ( depthTest ) { + } - enable( 2929 ); + scope.needsUpdate = false; - } else { + _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); - disable( 2929 ); + }; - } + function VSMPass( shadow, camera ) { - }, + var geometry = _objects.update( fullScreenMesh ); - setMask: function ( depthMask ) { + // vertical pass - if ( currentDepthMask !== depthMask && ! locked ) { + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.mapPass ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + // horizonal pass - } + shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizonal.uniforms.radius.value = shadow.radius; + _renderer.setRenderTarget( shadow.map ); + _renderer.clear(); + _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null ); - }, + } - setFunc: function ( depthFunc ) { + function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) { - if ( currentDepthFunc !== depthFunc ) { + var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - if ( depthFunc ) { + var material = _depthMaterials[ index ]; - switch ( depthFunc ) { + if ( material === undefined ) { - case NeverDepth: + material = new MeshDepthMaterial( { - gl.depthFunc( 512 ); - break; + depthPacking: RGBADepthPacking, - case AlwaysDepth: + morphTargets: useMorphing, + skinning: useSkinning - gl.depthFunc( 519 ); - break; + } ); - case LessDepth: + _depthMaterials[ index ] = material; - gl.depthFunc( 513 ); - break; + } - case LessEqualDepth: + return material; - gl.depthFunc( 515 ); - break; + } - case EqualDepth: + function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) { - gl.depthFunc( 514 ); - break; + var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; - case GreaterEqualDepth: + var material = _distanceMaterials[ index ]; - gl.depthFunc( 518 ); - break; + if ( material === undefined ) { - case GreaterDepth: + material = new MeshDistanceMaterial( { - gl.depthFunc( 516 ); - break; + morphTargets: useMorphing, + skinning: useSkinning - case NotEqualDepth: + } ); - gl.depthFunc( 517 ); - break; + _distanceMaterials[ index ] = material; - default: + } - gl.depthFunc( 515 ); + return material; - } + } - } else { + function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) { - gl.depthFunc( 515 ); + var result = null; - } + var getMaterialVariant = getDepthMaterialVariant; + var customMaterial = object.customDepthMaterial; - currentDepthFunc = depthFunc; + if ( light.isPointLight === true ) { - } + getMaterialVariant = getDistanceMaterialVariant; + customMaterial = object.customDistanceMaterial; - }, + } - setLocked: function ( lock ) { + if ( customMaterial === undefined ) { - locked = lock; + var useMorphing = false; - }, + if ( material.morphTargets === true ) { - setClear: function ( depth ) { + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - if ( currentDepthClear !== depth ) { + } - gl.clearDepth( depth ); - currentDepthClear = depth; + var useSkinning = false; - } + if ( object.isSkinnedMesh === true ) { - }, + if ( material.skinning === true ) { - reset: function () { + useSkinning = true; - locked = false; + } else { - currentDepthMask = null; - currentDepthFunc = null; - currentDepthClear = null; + console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); } - }; - - } - - function StencilBuffer() { - - var locked = false; - - var currentStencilMask = null; - var currentStencilFunc = null; - var currentStencilRef = null; - var currentStencilFuncMask = null; - var currentStencilFail = null; - var currentStencilZFail = null; - var currentStencilZPass = null; - var currentStencilClear = null; + } - return { + var useInstancing = object.isInstancedMesh === true; - setTest: function ( stencilTest ) { + result = getMaterialVariant( useMorphing, useSkinning, useInstancing ); - if ( ! locked ) { + } else { - if ( stencilTest ) { + result = customMaterial; - enable( 2960 ); + } - } else { + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - disable( 2960 ); + // in this case we need a unique material instance reflecting the + // appropriate state - } + var keyA = result.uuid, keyB = material.uuid; - } + var materialsForVariant = _materialCache[ keyA ]; - }, + if ( materialsForVariant === undefined ) { - setMask: function ( stencilMask ) { + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - if ( currentStencilMask !== stencilMask && ! locked ) { + } - gl.stencilMask( stencilMask ); - currentStencilMask = stencilMask; + var cachedMaterial = materialsForVariant[ keyB ]; - } + if ( cachedMaterial === undefined ) { - }, + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + } - if ( currentStencilFunc !== stencilFunc || - currentStencilRef !== stencilRef || - currentStencilFuncMask !== stencilMask ) { + result = cachedMaterial; - gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); + } - currentStencilFunc = stencilFunc; - currentStencilRef = stencilRef; - currentStencilFuncMask = stencilMask; + result.visible = material.visible; + result.wireframe = material.wireframe; - } + if ( type === VSMShadowMap ) { - }, + result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; - setOp: function ( stencilFail, stencilZFail, stencilZPass ) { + } else { - if ( currentStencilFail !== stencilFail || - currentStencilZFail !== stencilZFail || - currentStencilZPass !== stencilZPass ) { + result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; - gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); + } - currentStencilFail = stencilFail; - currentStencilZFail = stencilZFail; - currentStencilZPass = stencilZPass; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; - } + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - }, + if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { - setLocked: function ( lock ) { + result.referencePosition.setFromMatrixPosition( light.matrixWorld ); + result.nearDistance = shadowCameraNear; + result.farDistance = shadowCameraFar; - locked = lock; + } - }, + return result; - setClear: function ( stencil ) { + } - if ( currentStencilClear !== stencil ) { + function renderObject( object, camera, shadowCamera, light, type ) { - gl.clearStencil( stencil ); - currentStencilClear = stencil; + if ( object.visible === false ) return; - } + var visible = object.layers.test( camera.layers ); - }, + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { - reset: function () { + if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { - locked = false; + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); - currentStencilMask = null; - currentStencilFunc = null; - currentStencilRef = null; - currentStencilFuncMask = null; - currentStencilFail = null; - currentStencilZFail = null; - currentStencilZPass = null; - currentStencilClear = null; + var geometry = _objects.update( object ); + var material = object.material; - } + if ( Array.isArray( material ) ) { - }; + var groups = geometry.groups; - } + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { - // + var group = groups[ k ]; + var groupMaterial = material[ group.materialIndex ]; - var colorBuffer = new ColorBuffer(); - var depthBuffer = new DepthBuffer(); - var stencilBuffer = new StencilBuffer(); + if ( groupMaterial && groupMaterial.visible ) { - var maxVertexAttributes = gl.getParameter( 34921 ); - var newAttributes = new Uint8Array( maxVertexAttributes ); - var enabledAttributes = new Uint8Array( maxVertexAttributes ); - var attributeDivisors = new Uint8Array( maxVertexAttributes ); + var depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); - var enabledCapabilities = {}; + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); - var currentProgram = null; + } - var currentBlendingEnabled = null; - var currentBlending = null; - var currentBlendEquation = null; - var currentBlendSrc = null; - var currentBlendDst = null; - var currentBlendEquationAlpha = null; - var currentBlendSrcAlpha = null; - var currentBlendDstAlpha = null; - var currentPremultipledAlpha = false; + } - var currentFlipSided = null; - var currentCullFace = null; + } else if ( material.visible ) { - var currentLineWidth = null; + var depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type ); - var currentPolygonOffsetFactor = null; - var currentPolygonOffsetUnits = null; + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); - var maxTextures = gl.getParameter( 35661 ); + } - var lineWidthAvailable = false; - var version = 0; - var glVersion = gl.getParameter( 7938 ); + } - if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + } - version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] ); - lineWidthAvailable = ( version >= 1.0 ); + var children = object.children; - } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] ); - lineWidthAvailable = ( version >= 2.0 ); + renderObject( children[ i ], camera, shadowCamera, light, type ); } - var currentTextureSlot = null; - var currentBoundTextures = {}; + } - var currentScissor = new Vector4(); - var currentViewport = new Vector4(); +} - function createTexture( type, target, count ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. - var texture = gl.createTexture(); +function WebGLState( gl, extensions, capabilities ) { - gl.bindTexture( type, texture ); - gl.texParameteri( type, 10241, 9728 ); - gl.texParameteri( type, 10240, 9728 ); + var isWebGL2 = capabilities.isWebGL2; - for ( var i = 0; i < count; i ++ ) { + function ColorBuffer() { - gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data ); + var locked = false; - } + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4( 0, 0, 0, 0 ); - return texture; + return { - } + setMask: function ( colorMask ) { - var emptyTextures = {}; - emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 ); - emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 ); + if ( currentColorMask !== colorMask && ! locked ) { - // init + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; - colorBuffer.setClear( 0, 0, 0, 1 ); - depthBuffer.setClear( 1 ); - stencilBuffer.setClear( 0 ); + } - enable( 2929 ); - depthBuffer.setFunc( LessEqualDepth ); + }, - setFlipSided( false ); - setCullFace( CullFaceBack ); - enable( 2884 ); + setLocked: function ( lock ) { - setBlending( NoBlending ); + locked = lock; - // + }, - function initAttributes() { + setClear: function ( r, g, b, a, premultipliedAlpha ) { - for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + if ( premultipliedAlpha === true ) { - newAttributes[ i ] = 0; + r *= a; g *= a; b *= a; - } + } - } + color.set( r, g, b, a ); - function enableAttribute( attribute ) { + if ( currentColorClear.equals( color ) === false ) { - enableAttributeAndDivisor( attribute, 0 ); + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); - } + } - function enableAttributeAndDivisor( attribute, meshPerAttribute ) { + }, - newAttributes[ attribute ] = 1; + reset: function () { - if ( enabledAttributes[ attribute ] === 0 ) { + locked = false; - gl.enableVertexAttribArray( attribute ); - enabledAttributes[ attribute ] = 1; + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state } - if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { + }; - var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + } - extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); - attributeDivisors[ attribute ] = meshPerAttribute; + function DepthBuffer() { - } + var locked = false; - } + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; - function disableUnusedAttributes() { + return { - for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { + setTest: function ( depthTest ) { - if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { + if ( depthTest ) { - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + enable( 2929 ); - } + } else { - } + disable( 2929 ); - } + } - function enable( id ) { + }, - if ( enabledCapabilities[ id ] !== true ) { + setMask: function ( depthMask ) { - gl.enable( id ); - enabledCapabilities[ id ] = true; + if ( currentDepthMask !== depthMask && ! locked ) { - } + gl.depthMask( depthMask ); + currentDepthMask = depthMask; - } + } - function disable( id ) { + }, - if ( enabledCapabilities[ id ] !== false ) { + setFunc: function ( depthFunc ) { - gl.disable( id ); - enabledCapabilities[ id ] = false; + if ( currentDepthFunc !== depthFunc ) { - } + if ( depthFunc ) { - } + switch ( depthFunc ) { - function useProgram( program ) { + case NeverDepth: - if ( currentProgram !== program ) { + gl.depthFunc( 512 ); + break; - gl.useProgram( program ); + case AlwaysDepth: - currentProgram = program; + gl.depthFunc( 519 ); + break; - return true; + case LessDepth: - } + gl.depthFunc( 513 ); + break; - return false; + case LessEqualDepth: - } + gl.depthFunc( 515 ); + break; - var equationToGL = {}; - equationToGL[ AddEquation ] = 32774; - equationToGL[ SubtractEquation ] = 32778; - equationToGL[ ReverseSubtractEquation ] = 32779; + case EqualDepth: - if ( isWebGL2 ) { + gl.depthFunc( 514 ); + break; - equationToGL[ MinEquation ] = 32775; - equationToGL[ MaxEquation ] = 32776; + case GreaterEqualDepth: - } else { + gl.depthFunc( 518 ); + break; - var extension = extensions.get( 'EXT_blend_minmax' ); + case GreaterDepth: - if ( extension !== null ) { + gl.depthFunc( 516 ); + break; - equationToGL[ MinEquation ] = extension.MIN_EXT; - equationToGL[ MaxEquation ] = extension.MAX_EXT; + case NotEqualDepth: - } + gl.depthFunc( 517 ); + break; - } + default: + + gl.depthFunc( 515 ); - var factorToGL = {}; - factorToGL[ ZeroFactor ] = 0; - factorToGL[ OneFactor ] = 1; - factorToGL[ SrcColorFactor ] = 768; - factorToGL[ SrcAlphaFactor ] = 770; - factorToGL[ SrcAlphaSaturateFactor ] = 776; - factorToGL[ DstColorFactor ] = 774; - factorToGL[ DstAlphaFactor ] = 772; - factorToGL[ OneMinusSrcColorFactor ] = 769; - factorToGL[ OneMinusSrcAlphaFactor ] = 771; - factorToGL[ OneMinusDstColorFactor ] = 775; - factorToGL[ OneMinusDstAlphaFactor ] = 773; + } - function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + } else { - if ( blending === NoBlending ) { + gl.depthFunc( 515 ); - if ( currentBlendingEnabled ) { + } - disable( 3042 ); - currentBlendingEnabled = false; + currentDepthFunc = depthFunc; } - return; + }, - } + setLocked: function ( lock ) { - if ( ! currentBlendingEnabled ) { + locked = lock; - enable( 3042 ); - currentBlendingEnabled = true; + }, - } + setClear: function ( depth ) { - if ( blending !== CustomBlending ) { + if ( currentDepthClear !== depth ) { - if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { + gl.clearDepth( depth ); + currentDepthClear = depth; - if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { + } - gl.blendEquation( 32774 ); + }, - currentBlendEquation = AddEquation; - currentBlendEquationAlpha = AddEquation; + reset: function () { - } + locked = false; - if ( premultipliedAlpha ) { + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; - switch ( blending ) { + } - case NormalBlending: - gl.blendFuncSeparate( 1, 771, 1, 771 ); - break; + }; - case AdditiveBlending: - gl.blendFunc( 1, 1 ); - break; + } - case SubtractiveBlending: - gl.blendFuncSeparate( 0, 0, 769, 771 ); - break; + function StencilBuffer() { - case MultiplyBlending: - gl.blendFuncSeparate( 0, 768, 0, 770 ); - break; + var locked = false; - default: - console.error( 'THREE.WebGLState: Invalid blending: ', blending ); - break; + var currentStencilMask = null; + var currentStencilFunc = null; + var currentStencilRef = null; + var currentStencilFuncMask = null; + var currentStencilFail = null; + var currentStencilZFail = null; + var currentStencilZPass = null; + var currentStencilClear = null; - } + return { - } else { + setTest: function ( stencilTest ) { - switch ( blending ) { + if ( ! locked ) { - case NormalBlending: - gl.blendFuncSeparate( 770, 771, 1, 771 ); - break; + if ( stencilTest ) { - case AdditiveBlending: - gl.blendFunc( 770, 1 ); - break; + enable( 2960 ); - case SubtractiveBlending: - gl.blendFunc( 0, 769 ); - break; + } else { - case MultiplyBlending: - gl.blendFunc( 0, 768 ); - break; + disable( 2960 ); - default: - console.error( 'THREE.WebGLState: Invalid blending: ', blending ); - break; + } - } + } - } + }, + + setMask: function ( stencilMask ) { - currentBlendSrc = null; - currentBlendDst = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; + if ( currentStencilMask !== stencilMask && ! locked ) { - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; + gl.stencilMask( stencilMask ); + currentStencilMask = stencilMask; } - return; + }, - } + setFunc: function ( stencilFunc, stencilRef, stencilMask ) { + + if ( currentStencilFunc !== stencilFunc || + currentStencilRef !== stencilRef || + currentStencilFuncMask !== stencilMask ) { - // custom blending + gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); - blendEquationAlpha = blendEquationAlpha || blendEquation; - blendSrcAlpha = blendSrcAlpha || blendSrc; - blendDstAlpha = blendDstAlpha || blendDst; + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; - if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { + } + + }, - gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); + setOp: function ( stencilFail, stencilZFail, stencilZPass ) { - currentBlendEquation = blendEquation; - currentBlendEquationAlpha = blendEquationAlpha; + if ( currentStencilFail !== stencilFail || + currentStencilZFail !== stencilZFail || + currentStencilZPass !== stencilZPass ) { - } + gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); - if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; - gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); + } - currentBlendSrc = blendSrc; - currentBlendDst = blendDst; - currentBlendSrcAlpha = blendSrcAlpha; - currentBlendDstAlpha = blendDstAlpha; + }, - } + setLocked: function ( lock ) { - currentBlending = blending; - currentPremultipledAlpha = null; + locked = lock; - } + }, - function setMaterial( material, frontFaceCW ) { + setClear: function ( stencil ) { - material.side === DoubleSide - ? disable( 2884 ) - : enable( 2884 ); + if ( currentStencilClear !== stencil ) { - var flipSided = ( material.side === BackSide ); - if ( frontFaceCW ) { flipSided = ! flipSided; } + gl.clearStencil( stencil ); + currentStencilClear = stencil; - setFlipSided( flipSided ); + } - ( material.blending === NormalBlending && material.transparent === false ) - ? setBlending( NoBlending ) - : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + }, - depthBuffer.setFunc( material.depthFunc ); - depthBuffer.setTest( material.depthTest ); - depthBuffer.setMask( material.depthWrite ); - colorBuffer.setMask( material.colorWrite ); + reset: function () { - var stencilWrite = material.stencilWrite; - stencilBuffer.setTest( stencilWrite ); - if ( stencilWrite ) { + locked = false; - stencilBuffer.setMask( material.stencilWriteMask ); - stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); - stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; } - setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); + }; - } + } - // + // - function setFlipSided( flipSided ) { + var colorBuffer = new ColorBuffer(); + var depthBuffer = new DepthBuffer(); + var stencilBuffer = new StencilBuffer(); - if ( currentFlipSided !== flipSided ) { + var maxVertexAttributes = gl.getParameter( 34921 ); + var newAttributes = new Uint8Array( maxVertexAttributes ); + var enabledAttributes = new Uint8Array( maxVertexAttributes ); + var attributeDivisors = new Uint8Array( maxVertexAttributes ); - if ( flipSided ) { + var enabledCapabilities = {}; - gl.frontFace( 2304 ); + var currentProgram = null; - } else { + var currentBlendingEnabled = null; + var currentBlending = null; + var currentBlendEquation = null; + var currentBlendSrc = null; + var currentBlendDst = null; + var currentBlendEquationAlpha = null; + var currentBlendSrcAlpha = null; + var currentBlendDstAlpha = null; + var currentPremultipledAlpha = false; - gl.frontFace( 2305 ); + var currentFlipSided = null; + var currentCullFace = null; - } + var currentLineWidth = null; - currentFlipSided = flipSided; + var currentPolygonOffsetFactor = null; + var currentPolygonOffsetUnits = null; - } + var maxTextures = gl.getParameter( 35661 ); - } + var lineWidthAvailable = false; + var version = 0; + var glVersion = gl.getParameter( 7938 ); - function setCullFace( cullFace ) { + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { - if ( cullFace !== CullFaceNone ) { + version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); - enable( 2884 ); + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { - if ( cullFace !== currentCullFace ) { + version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); - if ( cullFace === CullFaceBack ) { + } - gl.cullFace( 1029 ); + var currentTextureSlot = null; + var currentBoundTextures = {}; - } else if ( cullFace === CullFaceFront ) { + var currentScissor = new Vector4(); + var currentViewport = new Vector4(); - gl.cullFace( 1028 ); + function createTexture( type, target, count ) { - } else { + var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. + var texture = gl.createTexture(); - gl.cullFace( 1032 ); + gl.bindTexture( type, texture ); + gl.texParameteri( type, 10241, 9728 ); + gl.texParameteri( type, 10240, 9728 ); - } + for ( var i = 0; i < count; i ++ ) { - } + gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data ); - } else { + } - disable( 2884 ); + return texture; - } + } - currentCullFace = cullFace; + var emptyTextures = {}; + emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 ); + emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 ); - } + // init - function setLineWidth( width ) { + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); - if ( width !== currentLineWidth ) { + enable( 2929 ); + depthBuffer.setFunc( LessEqualDepth ); - if ( lineWidthAvailable ) { gl.lineWidth( width ); } + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( 2884 ); - currentLineWidth = width; + setBlending( NoBlending ); - } + // + + function initAttributes() { + + for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { + + newAttributes[ i ] = 0; } - function setPolygonOffset( polygonOffset, factor, units ) { + } + + function enableAttribute( attribute ) { - if ( polygonOffset ) { + enableAttributeAndDivisor( attribute, 0 ); - enable( 32823 ); + } - if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { + function enableAttributeAndDivisor( attribute, meshPerAttribute ) { - gl.polygonOffset( factor, units ); + newAttributes[ attribute ] = 1; - currentPolygonOffsetFactor = factor; - currentPolygonOffsetUnits = units; + if ( enabledAttributes[ attribute ] === 0 ) { - } + gl.enableVertexAttribArray( attribute ); + enabledAttributes[ attribute ] = 1; - } else { + } - disable( 32823 ); + if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { - } + var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); + + extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); + attributeDivisors[ attribute ] = meshPerAttribute; } - function setScissorTest( scissorTest ) { + } - if ( scissorTest ) { + function disableUnusedAttributes() { - enable( 3089 ); + for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { - } else { + if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { - disable( 3089 ); + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; } } - // texture + } - function activeTexture( webglSlot ) { + function vertexAttribPointer( index, size, type, normalized, stride, offset ) { - if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; } + if ( isWebGL2 === true && ( type === 5124 || type === 5125 ) ) { - if ( currentTextureSlot !== webglSlot ) { + gl.vertexAttribIPointer( index, size, type, normalized, stride, offset ); - gl.activeTexture( webglSlot ); - currentTextureSlot = webglSlot; + } else { - } + gl.vertexAttribPointer( index, size, type, normalized, stride, offset ); } - function bindTexture( webglType, webglTexture ) { + } - if ( currentTextureSlot === null ) { + function enable( id ) { - activeTexture(); + if ( enabledCapabilities[ id ] !== true ) { - } + gl.enable( id ); + enabledCapabilities[ id ] = true; - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + } - if ( boundTexture === undefined ) { + } - boundTexture = { type: undefined, texture: undefined }; - currentBoundTextures[ currentTextureSlot ] = boundTexture; + function disable( id ) { - } + if ( enabledCapabilities[ id ] !== false ) { - if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { + gl.disable( id ); + enabledCapabilities[ id ] = false; - gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); + } - boundTexture.type = webglType; - boundTexture.texture = webglTexture; + } - } + function useProgram( program ) { - } + if ( currentProgram !== program ) { - function unbindTexture() { + gl.useProgram( program ); - var boundTexture = currentBoundTextures[ currentTextureSlot ]; + currentProgram = program; - if ( boundTexture !== undefined && boundTexture.type !== undefined ) { + return true; - gl.bindTexture( boundTexture.type, null ); + } - boundTexture.type = undefined; - boundTexture.texture = undefined; + return false; - } + } - } + var equationToGL = { + [ AddEquation ]: 32774, + [ SubtractEquation ]: 32778, + [ ReverseSubtractEquation ]: 32779 + }; - function compressedTexImage2D() { + if ( isWebGL2 ) { - try { + equationToGL[ MinEquation ] = 32775; + equationToGL[ MaxEquation ] = 32776; - gl.compressedTexImage2D.apply( gl, arguments ); + } else { - } catch ( error ) { + var extension = extensions.get( 'EXT_blend_minmax' ); - console.error( 'THREE.WebGLState:', error ); + if ( extension !== null ) { - } + equationToGL[ MinEquation ] = extension.MIN_EXT; + equationToGL[ MaxEquation ] = extension.MAX_EXT; } - function texImage2D() { + } + + var factorToGL = { + [ ZeroFactor ]: 0, + [ OneFactor ]: 1, + [ SrcColorFactor ]: 768, + [ SrcAlphaFactor ]: 770, + [ SrcAlphaSaturateFactor ]: 776, + [ DstColorFactor ]: 774, + [ DstAlphaFactor ]: 772, + [ OneMinusSrcColorFactor ]: 769, + [ OneMinusSrcAlphaFactor ]: 771, + [ OneMinusDstColorFactor ]: 775, + [ OneMinusDstAlphaFactor ]: 773 + }; - try { + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { - gl.texImage2D.apply( gl, arguments ); + if ( blending === NoBlending ) { - } catch ( error ) { + if ( currentBlendingEnabled ) { - console.error( 'THREE.WebGLState:', error ); + disable( 3042 ); + currentBlendingEnabled = false; } - } + return; - function texImage3D() { + } - try { + if ( ! currentBlendingEnabled ) { - gl.texImage3D.apply( gl, arguments ); + enable( 3042 ); + currentBlendingEnabled = true; - } catch ( error ) { + } - console.error( 'THREE.WebGLState:', error ); + if ( blending !== CustomBlending ) { - } + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - } + if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { - // + gl.blendEquation( 32774 ); - function scissor( scissor ) { + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; - if ( currentScissor.equals( scissor ) === false ) { + } - gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); - currentScissor.copy( scissor ); + if ( premultipliedAlpha ) { - } + switch ( blending ) { - } + case NormalBlending: + gl.blendFuncSeparate( 1, 771, 1, 771 ); + break; - function viewport( viewport ) { + case AdditiveBlending: + gl.blendFunc( 1, 1 ); + break; - if ( currentViewport.equals( viewport ) === false ) { + case SubtractiveBlending: + gl.blendFuncSeparate( 0, 0, 769, 771 ); + break; - gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); - currentViewport.copy( viewport ); + case MultiplyBlending: + gl.blendFuncSeparate( 0, 768, 0, 770 ); + break; - } + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; - } + } - // + } else { - function reset() { + switch ( blending ) { - for ( var i = 0; i < enabledAttributes.length; i ++ ) { + case NormalBlending: + gl.blendFuncSeparate( 770, 771, 1, 771 ); + break; - if ( enabledAttributes[ i ] === 1 ) { + case AdditiveBlending: + gl.blendFunc( 770, 1 ); + break; - gl.disableVertexAttribArray( i ); - enabledAttributes[ i ] = 0; + case SubtractiveBlending: + gl.blendFunc( 0, 769 ); + break; - } + case MultiplyBlending: + gl.blendFunc( 0, 768 ); + break; - } + default: + console.error( 'THREE.WebGLState: Invalid blending: ', blending ); + break; - enabledCapabilities = {}; + } - currentTextureSlot = null; - currentBoundTextures = {}; + } - currentProgram = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - currentBlending = null; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; - currentFlipSided = null; - currentCullFace = null; + } - colorBuffer.reset(); - depthBuffer.reset(); - stencilBuffer.reset(); + return; } - return { - - buffers: { - color: colorBuffer, - depth: depthBuffer, - stencil: stencilBuffer - }, + // custom blending - initAttributes: initAttributes, - enableAttribute: enableAttribute, - enableAttributeAndDivisor: enableAttributeAndDivisor, - disableUnusedAttributes: disableUnusedAttributes, - enable: enable, - disable: disable, + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; - useProgram: useProgram, + if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - setBlending: setBlending, - setMaterial: setMaterial, + gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); - setFlipSided: setFlipSided, - setCullFace: setCullFace, + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; - setLineWidth: setLineWidth, - setPolygonOffset: setPolygonOffset, + } - setScissorTest: setScissorTest, + if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - activeTexture: activeTexture, - bindTexture: bindTexture, - unbindTexture: unbindTexture, - compressedTexImage2D: compressedTexImage2D, - texImage2D: texImage2D, - texImage3D: texImage3D, + gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); - scissor: scissor, - viewport: viewport, + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; - reset: reset + } - }; + currentBlending = blending; + currentPremultipledAlpha = null; } - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { + function setMaterial( material, frontFaceCW ) { - var isWebGL2 = capabilities.isWebGL2; - var maxTextures = capabilities.maxTextures; - var maxCubemapSize = capabilities.maxCubemapSize; - var maxTextureSize = capabilities.maxTextureSize; - var maxSamples = capabilities.maxSamples; + material.side === DoubleSide + ? disable( 2884 ) + : enable( 2884 ); - var _videoTextures = new WeakMap(); - var _canvas; + var flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; - // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, - // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + setFlipSided( flipSided ); - var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' - && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null; + ( material.blending === NormalBlending && material.transparent === false ) + ? setBlending( NoBlending ) + : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - function createCanvas( width, height ) { + depthBuffer.setFunc( material.depthFunc ); + depthBuffer.setTest( material.depthTest ); + depthBuffer.setMask( material.depthWrite ); + colorBuffer.setMask( material.colorWrite ); - // Use OffscreenCanvas when available. Specially needed in web workers + var stencilWrite = material.stencilWrite; + stencilBuffer.setTest( stencilWrite ); + if ( stencilWrite ) { - return useOffscreenCanvas ? - new OffscreenCanvas( width, height ) : - document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + stencilBuffer.setMask( material.stencilWriteMask ); + stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); + stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); } - function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - - var scale = 1; + setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); - // handle case if texture exceeds max size + } - if ( image.width > maxSize || image.height > maxSize ) { + // - scale = maxSize / Math.max( image.width, image.height ); + function setFlipSided( flipSided ) { - } + if ( currentFlipSided !== flipSided ) { - // only perform resize if necessary + if ( flipSided ) { - if ( scale < 1 || needsPowerOfTwo === true ) { + gl.frontFace( 2304 ); - // only perform resize for certain image types + } else { - if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || - ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || - ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { + gl.frontFace( 2305 ); - var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor; + } - var width = floor( scale * image.width ); - var height = floor( scale * image.height ); + currentFlipSided = flipSided; - if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); } + } - // cube textures can't reuse the same canvas + } - var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; + function setCullFace( cullFace ) { - canvas.width = width; - canvas.height = height; + if ( cullFace !== CullFaceNone ) { - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, width, height ); + enable( 2884 ); - console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); + if ( cullFace !== currentCullFace ) { - return canvas; + if ( cullFace === CullFaceBack ) { - } else { + gl.cullFace( 1029 ); - if ( 'data' in image ) { + } else if ( cullFace === CullFaceFront ) { - console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + gl.cullFace( 1028 ); - } + } else { - return image; + gl.cullFace( 1032 ); } } - return image; + } else { + + disable( 2884 ); } - function isPowerOfTwo( image ) { + currentCullFace = cullFace; - return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height ); + } - } + function setLineWidth( width ) { - function textureNeedsPowerOfTwo( texture ) { + if ( width !== currentLineWidth ) { - if ( isWebGL2 ) { return false; } + if ( lineWidthAvailable ) gl.lineWidth( width ); - return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || - ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + currentLineWidth = width; } - function textureNeedsGenerateMipmaps( texture, supportsMips ) { + } - return texture.generateMipmaps && supportsMips && - texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + function setPolygonOffset( polygonOffset, factor, units ) { - } + if ( polygonOffset ) { - function generateMipmap( target, texture, width, height ) { + enable( 32823 ); - _gl.generateMipmap( target ); + if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { - var textureProperties = properties.get( texture ); + gl.polygonOffset( factor, units ); - // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 - textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E; + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; - } + } - function getInternalFormat( glFormat, glType ) { + } else { - if ( isWebGL2 === false ) { return glFormat; } + disable( 32823 ); - var internalFormat = glFormat; + } - if ( glFormat === 6403 ) { + } - if ( glType === 5126 ) { internalFormat = 33326; } - if ( glType === 5131 ) { internalFormat = 33325; } - if ( glType === 5121 ) { internalFormat = 33321; } + function setScissorTest( scissorTest ) { - } + if ( scissorTest ) { - if ( glFormat === 6407 ) { + enable( 3089 ); - if ( glType === 5126 ) { internalFormat = 34837; } - if ( glType === 5131 ) { internalFormat = 34843; } - if ( glType === 5121 ) { internalFormat = 32849; } + } else { - } + disable( 3089 ); - if ( glFormat === 6408 ) { + } - if ( glType === 5126 ) { internalFormat = 34836; } - if ( glType === 5131 ) { internalFormat = 34842; } - if ( glType === 5121 ) { internalFormat = 32856; } + } - } + // texture - if ( internalFormat === 33325 || internalFormat === 33326 || - internalFormat === 34842 || internalFormat === 34836 ) { + function activeTexture( webglSlot ) { - extensions.get( 'EXT_color_buffer_float' ); + if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1; - } else if ( internalFormat === 34843 || internalFormat === 34837 ) { + if ( currentTextureSlot !== webglSlot ) { - console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' ); + gl.activeTexture( webglSlot ); + currentTextureSlot = webglSlot; - } + } - return internalFormat; + } - } + function bindTexture( webglType, webglTexture ) { - // Fallback filters for non-power-of-2 textures + if ( currentTextureSlot === null ) { - function filterFallback( f ) { + activeTexture(); - if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { + } - return 9728; + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - } + if ( boundTexture === undefined ) { - return 9729; + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[ currentTextureSlot ] = boundTexture; } - // + if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { - function onTextureDispose( event ) { + gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); - var texture = event.target; + boundTexture.type = webglType; + boundTexture.texture = webglTexture; - texture.removeEventListener( 'dispose', onTextureDispose ); + } + + } - deallocateTexture( texture ); + function unbindTexture() { - if ( texture.isVideoTexture ) { + var boundTexture = currentBoundTextures[ currentTextureSlot ]; - _videoTextures.delete( texture ); + if ( boundTexture !== undefined && boundTexture.type !== undefined ) { - } + gl.bindTexture( boundTexture.type, null ); - info.memory.textures --; + boundTexture.type = undefined; + boundTexture.texture = undefined; } - function onRenderTargetDispose( event ) { + } + + function compressedTexImage2D() { - var renderTarget = event.target; + try { - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + gl.compressedTexImage2D.apply( gl, arguments ); - deallocateRenderTarget( renderTarget ); + } catch ( error ) { - info.memory.textures --; + console.error( 'THREE.WebGLState:', error ); } - // + } - function deallocateTexture( texture ) { + function texImage2D() { - var textureProperties = properties.get( texture ); + try { - if ( textureProperties.__webglInit === undefined ) { return; } + gl.texImage2D.apply( gl, arguments ); - _gl.deleteTexture( textureProperties.__webglTexture ); + } catch ( error ) { - properties.remove( texture ); + console.error( 'THREE.WebGLState:', error ); } - function deallocateRenderTarget( renderTarget ) { + } + + function texImage3D() { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + try { - if ( ! renderTarget ) { return; } + gl.texImage3D.apply( gl, arguments ); - if ( textureProperties.__webglTexture !== undefined ) { + } catch ( error ) { - _gl.deleteTexture( textureProperties.__webglTexture ); + console.error( 'THREE.WebGLState:', error ); - } + } - if ( renderTarget.depthTexture ) { + } - renderTarget.depthTexture.dispose(); + // - } + function scissor( scissor ) { - if ( renderTarget.isWebGLRenderTargetCube ) { + if ( currentScissor.equals( scissor ) === false ) { - for ( var i = 0; i < 6; i ++ ) { + gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); + currentScissor.copy( scissor ); - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); } + } - } + } - } else { + function viewport( viewport ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); } + if ( currentViewport.equals( viewport ) === false ) { - } + gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); + currentViewport.copy( viewport ); + + } - if ( renderTarget.isWebGLMultiviewRenderTarget ) { + } - _gl.deleteTexture( renderTargetProperties.__webglColorTexture ); - _gl.deleteTexture( renderTargetProperties.__webglDepthStencilTexture ); + // - info.memory.textures -= 2; + function reset() { - for ( var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i ++ ) { + for ( var i = 0; i < enabledAttributes.length; i ++ ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglViewFramebuffers[ i ] ); + if ( enabledAttributes[ i ] === 1 ) { - } + gl.disableVertexAttribArray( i ); + enabledAttributes[ i ] = 0; } - properties.remove( renderTarget.texture ); - properties.remove( renderTarget ); - } - // + enabledCapabilities = {}; - var textureUnits = 0; + currentTextureSlot = null; + currentBoundTextures = {}; - function resetTextureUnits() { + currentProgram = null; - textureUnits = 0; + currentBlending = null; - } + currentFlipSided = null; + currentCullFace = null; - function allocateTextureUnit() { + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); - var textureUnit = textureUnits; + } - if ( textureUnit >= maxTextures ) { + return { - console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, - } + initAttributes: initAttributes, + enableAttribute: enableAttribute, + enableAttributeAndDivisor: enableAttributeAndDivisor, + disableUnusedAttributes: disableUnusedAttributes, + vertexAttribPointer: vertexAttribPointer, + enable: enable, + disable: disable, - textureUnits += 1; + useProgram: useProgram, - return textureUnit; + setBlending: setBlending, + setMaterial: setMaterial, - } + setFlipSided: setFlipSided, + setCullFace: setCullFace, - // + setLineWidth: setLineWidth, + setPolygonOffset: setPolygonOffset, - function setTexture2D( texture, slot ) { + setScissorTest: setScissorTest, - var textureProperties = properties.get( texture ); + activeTexture: activeTexture, + bindTexture: bindTexture, + unbindTexture: unbindTexture, + compressedTexImage2D: compressedTexImage2D, + texImage2D: texImage2D, + texImage3D: texImage3D, - if ( texture.isVideoTexture ) { updateVideoTexture( texture ); } + scissor: scissor, + viewport: viewport, - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + reset: reset - var image = texture.image; + }; - if ( image === undefined ) { +} - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - } else if ( image.complete === false ) { +function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); + var isWebGL2 = capabilities.isWebGL2; + var maxTextures = capabilities.maxTextures; + var maxCubemapSize = capabilities.maxCubemapSize; + var maxTextureSize = capabilities.maxTextureSize; + var maxSamples = capabilities.maxSamples; - } else { + var _videoTextures = new WeakMap(); + var _canvas; - uploadTexture( textureProperties, texture, slot ); - return; + // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, + // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! + // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). - } + var useOffscreenCanvas = false; - } + try { - state.activeTexture( 33984 + slot ); - state.bindTexture( 3553, textureProperties.__webglTexture ); - - } - - function setTexture2DArray( texture, slot ) { + useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' + && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null; - var textureProperties = properties.get( texture ); + } catch ( err ) { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + // Ignore any errors - uploadTexture( textureProperties, texture, slot ); - return; + } - } + function createCanvas( width, height ) { - state.activeTexture( 33984 + slot ); - state.bindTexture( 35866, textureProperties.__webglTexture ); + // Use OffscreenCanvas when available. Specially needed in web workers - } + return useOffscreenCanvas ? + new OffscreenCanvas( width, height ) : + document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - function setTexture3D( texture, slot ) { + } - var textureProperties = properties.get( texture ); + function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + var scale = 1; - uploadTexture( textureProperties, texture, slot ); - return; + // handle case if texture exceeds max size - } + if ( image.width > maxSize || image.height > maxSize ) { - state.activeTexture( 33984 + slot ); - state.bindTexture( 32879, textureProperties.__webglTexture ); + scale = maxSize / Math.max( image.width, image.height ); } - function setTextureCube( texture, slot ) { - - if ( texture.image.length !== 6 ) { return; } - - var textureProperties = properties.get( texture ); - - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - - initTexture( textureProperties, texture ); - - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); - - _gl.pixelStorei( 37440, texture.flipY ); - - var isCompressed = ( texture && texture.isCompressedTexture ); - var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + // only perform resize if necessary - var cubeImage = []; + if ( scale < 1 || needsPowerOfTwo === true ) { - for ( var i = 0; i < 6; i ++ ) { - - if ( ! isCompressed && ! isDataTexture ) { - - cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); - - } else { - - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + // only perform resize for certain image types - } + if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || + ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || + ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { - } + var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor; - var image = cubeImage[ 0 ], - supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ), - glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( glFormat, glType ); + var width = floor( scale * image.width ); + var height = floor( scale * image.height ); - setTextureParameters( 34067, texture, supportsMips ); + if ( _canvas === undefined ) _canvas = createCanvas( width, height ); - var mipmaps; + // cube textures can't reuse the same canvas - if ( isCompressed ) { + var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; - for ( var i = 0; i < 6; i ++ ) { + canvas.width = width; + canvas.height = height; - mipmaps = cubeImage[ i ].mipmaps; + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, width, height ); - for ( var j = 0; j < mipmaps.length; j ++ ) { + console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); - var mipmap = mipmaps[ j ]; + return canvas; - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + } else { - if ( glFormat !== null ) { + if ( 'data' in image ) { - state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); - } else { + } - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); + return image; - } + } - } else { + } - state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + return image; - } + } - } + function isPowerOfTwo( image ) { - } + return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height ); - textureProperties.__maxMipLevel = mipmaps.length - 1; + } - } else { + function textureNeedsPowerOfTwo( texture ) { - mipmaps = texture.mipmaps; + if ( isWebGL2 ) return false; - for ( var i = 0; i < 6; i ++ ) { + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - if ( isDataTexture ) { + } - state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + function textureNeedsGenerateMipmaps( texture, supportsMips ) { - for ( var j = 0; j < mipmaps.length; j ++ ) { + return texture.generateMipmaps && supportsMips && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - var mipmap = mipmaps[ j ]; - var mipmapImage = mipmap.image[ i ].image; + } - state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); + function generateMipmap( target, texture, width, height ) { - } + _gl.generateMipmap( target ); - } else { + var textureProperties = properties.get( texture ); - state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); + // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 + textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E; - for ( var j = 0; j < mipmaps.length; j ++ ) { + } - var mipmap = mipmaps[ j ]; + function getInternalFormat( internalFormatName, glFormat, glType ) { - state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); + if ( isWebGL2 === false ) return glFormat; - } + if ( internalFormatName !== null ) { - } + if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; - } + console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); - textureProperties.__maxMipLevel = mipmaps.length; + } - } + var internalFormat = glFormat; - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + if ( glFormat === 6403 ) { - // We assume images for cube map have the same size. - generateMipmap( 34067, texture, image.width, image.height ); + if ( glType === 5126 ) internalFormat = 33326; + if ( glType === 5131 ) internalFormat = 33325; + if ( glType === 5121 ) internalFormat = 33321; - } + } - textureProperties.__version = texture.version; + if ( glFormat === 6407 ) { - if ( texture.onUpdate ) { texture.onUpdate( texture ); } + if ( glType === 5126 ) internalFormat = 34837; + if ( glType === 5131 ) internalFormat = 34843; + if ( glType === 5121 ) internalFormat = 32849; - } else { + } - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, textureProperties.__webglTexture ); + if ( glFormat === 6408 ) { - } + if ( glType === 5126 ) internalFormat = 34836; + if ( glType === 5131 ) internalFormat = 34842; + if ( glType === 5121 ) internalFormat = 32856; } - function setTextureCubeDynamic( texture, slot ) { + if ( internalFormat === 33325 || internalFormat === 33326 || + internalFormat === 34842 || internalFormat === 34836 ) { - state.activeTexture( 33984 + slot ); - state.bindTexture( 34067, properties.get( texture ).__webglTexture ); + extensions.get( 'EXT_color_buffer_float' ); } - var wrappingToGL = {}; - wrappingToGL[ RepeatWrapping ] = 10497; - wrappingToGL[ ClampToEdgeWrapping ] = 33071; - wrappingToGL[ MirroredRepeatWrapping ] = 33648; + return internalFormat; - var filterToGL = {}; - filterToGL[ NearestFilter ] = 9728; - filterToGL[ NearestMipmapNearestFilter ] = 9984; - filterToGL[ NearestMipmapLinearFilter ] = 9986; - filterToGL[ LinearFilter ] = 9729; - filterToGL[ LinearMipmapNearestFilter ] = 9985; - filterToGL[ LinearMipmapLinearFilter ] = 9987; + } - function setTextureParameters( textureType, texture, supportsMips ) { + // Fallback filters for non-power-of-2 textures - if ( supportsMips ) { + function filterFallback( f ) { - _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); - _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); + if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { - if ( textureType === 32879 || textureType === 35866 ) { + return 9728; - _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); + } - } + return 9729; - _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); - _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); + } - } else { + // - _gl.texParameteri( textureType, 10242, 33071 ); - _gl.texParameteri( textureType, 10243, 33071 ); + function onTextureDispose( event ) { - if ( textureType === 32879 || textureType === 35866 ) { + var texture = event.target; - _gl.texParameteri( textureType, 32882, 33071 ); + texture.removeEventListener( 'dispose', onTextureDispose ); - } + deallocateTexture( texture ); - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { + if ( texture.isVideoTexture ) { - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); + _videoTextures.delete( texture ); - } + } - _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); + info.memory.textures --; - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + } - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); + function onRenderTargetDispose( event ) { - } + var renderTarget = event.target; - } + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + deallocateRenderTarget( renderTarget ); - if ( extension ) { + info.memory.textures --; - if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; } - if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; } + } - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + // - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + function deallocateTexture( texture ) { - } + var textureProperties = properties.get( texture ); - } + if ( textureProperties.__webglInit === undefined ) return; - } + _gl.deleteTexture( textureProperties.__webglTexture ); - function initTexture( textureProperties, texture ) { + properties.remove( texture ); - if ( textureProperties.__webglInit === undefined ) { + } - textureProperties.__webglInit = true; + function deallocateRenderTarget( renderTarget ) { - texture.addEventListener( 'dispose', onTextureDispose ); + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - textureProperties.__webglTexture = _gl.createTexture(); + if ( ! renderTarget ) return; - info.memory.textures ++; + if ( textureProperties.__webglTexture !== undefined ) { - } + _gl.deleteTexture( textureProperties.__webglTexture ); } - function uploadTexture( textureProperties, texture, slot ) { - - var textureType = 3553; + if ( renderTarget.depthTexture ) { - if ( texture.isDataTexture2DArray ) { textureType = 35866; } - if ( texture.isDataTexture3D ) { textureType = 32879; } + renderTarget.depthTexture.dispose(); - initTexture( textureProperties, texture ); + } - state.activeTexture( 33984 + slot ); - state.bindTexture( textureType, textureProperties.__webglTexture ); + if ( renderTarget.isWebGLCubeRenderTarget ) { - _gl.pixelStorei( 37440, texture.flipY ); - _gl.pixelStorei( 37441, texture.premultiplyAlpha ); - _gl.pixelStorei( 3317, texture.unpackAlignment ); + for ( var i = 0; i < 6; i ++ ) { - var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; - var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - var supportsMips = isPowerOfTwo( image ) || isWebGL2, - glFormat = utils.convert( texture.format ), - glType = utils.convert( texture.type ), - glInternalFormat = getInternalFormat( glFormat, glType ); + } - setTextureParameters( textureType, texture, supportsMips ); + } else { - var mipmap, mipmaps = texture.mipmaps; + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); + if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); + if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); - if ( texture.isDepthTexture ) { + } - // populate depth texture with dummy data + properties.remove( renderTarget.texture ); + properties.remove( renderTarget ); - glInternalFormat = 6402; + } - if ( texture.type === FloatType ) { + // - if ( isWebGL2 === false ) { throw new Error( 'Float Depth Texture only supported in WebGL2.0' ); } - glInternalFormat = 36012; + var textureUnits = 0; - } else if ( isWebGL2 ) { + function resetTextureUnits() { - // WebGL 2.0 requires signed internalformat for glTexImage2D - glInternalFormat = 33189; + textureUnits = 0; - } + } - if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { + function allocateTextureUnit() { - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + var textureUnit = textureUnits; - console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + if ( textureUnit >= maxTextures ) { - texture.type = UnsignedShortType; - glType = utils.convert( texture.type ); + console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); - } + } - } + textureUnits += 1; - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.format === DepthStencilFormat ) { + return textureUnit; - glInternalFormat = 34041; + } - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedInt248Type ) { + // - console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + function setTexture2D( texture, slot ) { - texture.type = UnsignedInt248Type; - glType = utils.convert( texture.type ); + var textureProperties = properties.get( texture ); - } + if ( texture.isVideoTexture ) updateVideoTexture( texture ); - } + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); + var image = texture.image; - } else if ( texture.isDataTexture ) { + if ( image === undefined ) { - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); - if ( mipmaps.length > 0 && supportsMips ) { + } else if ( image.complete === false ) { - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + } else { - } + uploadTexture( textureProperties, texture, slot ); + return; - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + } - } else { + } - state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + state.activeTexture( 33984 + slot ); + state.bindTexture( 3553, textureProperties.__webglTexture ); - } + } - } else if ( texture.isCompressedTexture ) { + function setTexture2DArray( texture, slot ) { - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var textureProperties = properties.get( texture ); - mipmap = mipmaps[ i ]; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + uploadTexture( textureProperties, texture, slot ); + return; - if ( glFormat !== null ) { + } - state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + state.activeTexture( 33984 + slot ); + state.bindTexture( 35866, textureProperties.__webglTexture ); - } else { + } - console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + function setTexture3D( texture, slot ) { - } + var textureProperties = properties.get( texture ); - } else { + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + uploadTexture( textureProperties, texture, slot ); + return; - } + } - } + state.activeTexture( 33984 + slot ); + state.bindTexture( 32879, textureProperties.__webglTexture ); - textureProperties.__maxMipLevel = mipmaps.length - 1; + } - } else if ( texture.isDataTexture2DArray ) { + function setTextureCube( texture, slot ) { - state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + if ( texture.image.length !== 6 ) return; - } else if ( texture.isDataTexture3D ) { + var textureProperties = properties.get( texture ); - state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); - textureProperties.__maxMipLevel = 0; + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - } else { + initTexture( textureProperties, texture ); - // regular Texture (image, video, canvas) + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + _gl.pixelStorei( 37440, texture.flipY ); - if ( mipmaps.length > 0 && supportsMips ) { + var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) ); + var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + var cubeImage = []; - mipmap = mipmaps[ i ]; - state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); + for ( var i = 0; i < 6; i ++ ) { - } + if ( ! isCompressed && ! isDataTexture ) { - texture.generateMipmaps = false; - textureProperties.__maxMipLevel = mipmaps.length - 1; + cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); } else { - state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); - textureProperties.__maxMipLevel = 0; + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; } } - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + var image = cubeImage[ 0 ], + supportsMips = isPowerOfTwo( image ) || isWebGL2, + glFormat = utils.convert( texture.format ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); - generateMipmap( 3553, texture, image.width, image.height ); + setTextureParameters( 34067, texture, supportsMips ); - } + var mipmaps; - textureProperties.__version = texture.version; + if ( isCompressed ) { - if ( texture.onUpdate ) { texture.onUpdate( texture ); } + for ( var i = 0; i < 6; i ++ ) { - } + mipmaps = cubeImage[ i ].mipmaps; - // Render targets + for ( var j = 0; j < mipmaps.length; j ++ ) { - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + var mipmap = mipmaps[ j ]; - var glFormat = utils.convert( renderTarget.texture.format ); - var glType = utils.convert( renderTarget.texture.type ); - var glInternalFormat = getInternalFormat( glFormat, glType ); - state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - _gl.bindFramebuffer( 36160, framebuffer ); - _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( 36160, null ); + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - } + if ( glFormat !== null ) { - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { + state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - _gl.bindRenderbuffer( 36161, renderbuffer ); + } else { - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); - if ( isMultisample ) { + } - var samples = getRenderTargetSamples( renderTarget ); + } else { - _gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height ); + state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } else { + } - _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height ); + } } - _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); + textureProperties.__maxMipLevel = mipmaps.length - 1; - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + } else { - if ( isMultisample ) { + mipmaps = texture.mipmaps; - var samples = getRenderTargetSamples( renderTarget ); + for ( var i = 0; i < 6; i ++ ) { - _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); + if ( isDataTexture ) { - } else { + state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); + for ( var j = 0; j < mipmaps.length; j ++ ) { - } + var mipmap = mipmaps[ j ]; + var mipmapImage = mipmap.image[ i ].image; + state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); - _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); + } - } else { + } else { - var glFormat = utils.convert( renderTarget.texture.format ); - var glType = utils.convert( renderTarget.texture.type ); - var glInternalFormat = getInternalFormat( glFormat, glType ); + state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); - if ( isMultisample ) { + for ( var j = 0; j < mipmaps.length; j ++ ) { - var samples = getRenderTargetSamples( renderTarget ); + var mipmap = mipmaps[ j ]; - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); - } else { + } - _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); + } } + textureProperties.__maxMipLevel = mipmaps.length; + } - _gl.bindRenderbuffer( 36161, null ); + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + + // We assume images for cube map have the same size. + generateMipmap( 34067, texture, image.width, image.height ); - } + } - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + textureProperties.__version = texture.version; - var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); - if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); } + if ( texture.onUpdate ) texture.onUpdate( texture ); - _gl.bindFramebuffer( 36160, framebuffer ); + } else { - if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, textureProperties.__webglTexture ); - throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); + } - } + } - // upload an empty depth texture with framebuffer size - if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || - renderTarget.depthTexture.image.width !== renderTarget.width || - renderTarget.depthTexture.image.height !== renderTarget.height ) { + function setTextureCubeDynamic( texture, slot ) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; + state.activeTexture( 33984 + slot ); + state.bindTexture( 34067, properties.get( texture ).__webglTexture ); - } + } - setTexture2D( renderTarget.depthTexture, 0 ); + var wrappingToGL = { + [ RepeatWrapping ]: 10497, + [ ClampToEdgeWrapping ]: 33071, + [ MirroredRepeatWrapping ]: 33648 + }; - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + var filterToGL = { + [ NearestFilter ]: 9728, + [ NearestMipmapNearestFilter ]: 9984, + [ NearestMipmapLinearFilter ]: 9986, - if ( renderTarget.depthTexture.format === DepthFormat ) { + [ LinearFilter ]: 9729, + [ LinearMipmapNearestFilter ]: 9985, + [ LinearMipmapLinearFilter ]: 9987 + }; - _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); + function setTextureParameters( textureType, texture, supportsMips ) { - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + if ( supportsMips ) { - _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); + _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); + _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); - } else { + if ( textureType === 32879 || textureType === 35866 ) { - throw new Error( 'Unknown depthTexture format' ); + _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); } - } + _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); + _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + } else { - var renderTargetProperties = properties.get( renderTarget ); + _gl.texParameteri( textureType, 10242, 33071 ); + _gl.texParameteri( textureType, 10243, 33071 ); - var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); + if ( textureType === 32879 || textureType === 35866 ) { - if ( renderTarget.depthTexture ) { + _gl.texParameteri( textureType, 32882, 33071 ); - if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); } + } - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - } else { + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); - if ( isCube ) { + } - renderTargetProperties.__webglDepthbuffer = []; + _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); - for ( var i = 0; i < 6; i ++ ) { + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); - } + } - } else { + } - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - } + if ( extension ) { - } + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return; + + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - _gl.bindFramebuffer( 36160, null ); + } } - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + } + + function initTexture( textureProperties, texture ) { - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + if ( textureProperties.__webglInit === undefined ) { - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + textureProperties.__webglInit = true; + + texture.addEventListener( 'dispose', onTextureDispose ); textureProperties.__webglTexture = _gl.createTexture(); info.memory.textures ++; - var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); - var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); - var isMultiview = ( renderTarget.isWebGLMultiviewRenderTarget === true ); - var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + } - // Setup framebuffer + } - if ( isCube ) { + function uploadTexture( textureProperties, texture, slot ) { - renderTargetProperties.__webglFramebuffer = []; + var textureType = 3553; - for ( var i = 0; i < 6; i ++ ) { + if ( texture.isDataTexture2DArray ) textureType = 35866; + if ( texture.isDataTexture3D ) textureType = 32879; - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + initTexture( textureProperties, texture ); - } + state.activeTexture( 33984 + slot ); + state.bindTexture( textureType, textureProperties.__webglTexture ); - } else { + _gl.pixelStorei( 37440, texture.flipY ); + _gl.pixelStorei( 37441, texture.premultiplyAlpha ); + _gl.pixelStorei( 3317, texture.unpackAlignment ); + + var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; + var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + var supportsMips = isPowerOfTwo( image ) || isWebGL2, + glFormat = utils.convert( texture.format ), + glType = utils.convert( texture.type ), + glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); - if ( isMultisample ) { + setTextureParameters( textureType, texture, supportsMips ); - if ( isWebGL2 ) { + var mipmap, mipmaps = texture.mipmaps; - renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); - renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); + if ( texture.isDepthTexture ) { - _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); - var glFormat = utils.convert( renderTarget.texture.format ); - var glType = utils.convert( renderTarget.texture.type ); - var glInternalFormat = getInternalFormat( glFormat, glType ); - var samples = getRenderTargetSamples( renderTarget ); - _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); + // populate depth texture with dummy data - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); - _gl.bindRenderbuffer( 36161, null ); + glInternalFormat = 6402; - if ( renderTarget.depthBuffer ) { + if ( isWebGL2 ) { - renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); + if ( texture.type === FloatType ) { - } + glInternalFormat = 36012; - _gl.bindFramebuffer( 36160, null ); + } else if ( texture.type === UnsignedIntType ) { + glInternalFormat = 33190; - } else { + } else if ( texture.type === UnsignedInt248Type ) { - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + glInternalFormat = 35056; - } + } else { - } else if ( isMultiview ) { + glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D - var width = renderTarget.width; - var height = renderTarget.height; - var numViews = renderTarget.numViews; + } - _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + } else { - var ext = extensions.get( 'OVR_multiview2' ); + if ( texture.type === FloatType ) { - info.memory.textures += 2; + console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); - var colorTexture = _gl.createTexture(); - _gl.bindTexture( 35866, colorTexture ); - _gl.texParameteri( 35866, 10240, 9728 ); - _gl.texParameteri( 35866, 10241, 9728 ); - _gl.texImage3D( 35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null ); - ext.framebufferTextureMultiviewOVR( 36160, 36064, colorTexture, 0, 0, numViews ); + } - var depthStencilTexture = _gl.createTexture(); - _gl.bindTexture( 35866, depthStencilTexture ); - _gl.texParameteri( 35866, 10240, 9728 ); - _gl.texParameteri( 35866, 10241, 9728 ); - _gl.texImage3D( 35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null ); - ext.framebufferTextureMultiviewOVR( 36160, 33306, depthStencilTexture, 0, 0, numViews ); + } - var viewFramebuffers = new Array( numViews ); - for ( var i = 0; i < numViews; ++ i ) { + // validation checks for WebGL 1 - viewFramebuffers[ i ] = _gl.createFramebuffer(); - _gl.bindFramebuffer( 36160, viewFramebuffers[ i ] ); - _gl.framebufferTextureLayer( 36160, 36064, colorTexture, 0, i ); + if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { - } + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { - renderTargetProperties.__webglColorTexture = colorTexture; - renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture; - renderTargetProperties.__webglViewFramebuffers = viewFramebuffers; + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - _gl.bindFramebuffer( 36160, null ); - _gl.bindTexture( 35866, null ); + texture.type = UnsignedShortType; + glType = utils.convert( texture.type ); } } - // Setup color buffer + if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) { - if ( isCube ) { + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + glInternalFormat = 34041; - state.bindTexture( 34067, textureProperties.__webglTexture ); - setTextureParameters( 34067, renderTarget.texture, supportsMips ); + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { - for ( var i = 0; i < 6; i ++ ) { + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i ); + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); } - if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { + } - generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height ); + // - } + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); - state.bindTexture( 34067, null ); + } else if ( texture.isDataTexture ) { - } else if ( ! isMultiview ) { + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - state.bindTexture( 3553, textureProperties.__webglTexture ); - setTextureParameters( 3553, renderTarget.texture, supportsMips ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 ); + if ( mipmaps.length > 0 && supportsMips ) { - if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height ); + mipmap = mipmaps[ i ]; + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } - state.bindTexture( 3553, null ); + texture.generateMipmaps = false; + textureProperties.__maxMipLevel = mipmaps.length - 1; + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); + textureProperties.__maxMipLevel = 0; } - // Setup depth and stencil buffers + } else if ( texture.isCompressedTexture ) { - if ( renderTarget.depthBuffer ) { + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - setupDepthRenderbuffer( renderTarget ); + mipmap = mipmaps[ i ]; - } + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - } + if ( glFormat !== null ) { - function updateRenderTargetMipmap( renderTarget ) { + state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - var texture = renderTarget.texture; - var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; + } else { - if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); + + } - var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553; - var webglTexture = properties.get( texture ).__webglTexture; + } else { + + state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - state.bindTexture( target, webglTexture ); - generateMipmap( target, texture, renderTarget.width, renderTarget.height ); - state.bindTexture( target, null ); + } } - } + textureProperties.__maxMipLevel = mipmaps.length - 1; - function updateMultisampleRenderTarget( renderTarget ) { + } else if ( texture.isDataTexture2DArray ) { - if ( renderTarget.isWebGLMultisampleRenderTarget ) { + state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + textureProperties.__maxMipLevel = 0; - if ( isWebGL2 ) { + } else if ( texture.isDataTexture3D ) { - var renderTargetProperties = properties.get( renderTarget ); + state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); + textureProperties.__maxMipLevel = 0; - _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); - _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); + } else { - var width = renderTarget.width; - var height = renderTarget.height; - var mask = 16384; + // regular Texture (image, video, canvas) - if ( renderTarget.depthBuffer ) { mask |= 256; } - if ( renderTarget.stencilBuffer ) { mask |= 1024; } + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); + if ( mipmaps.length > 0 && supportsMips ) { - } else { + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); + mipmap = mipmaps[ i ]; + state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); } + texture.generateMipmaps = false; + textureProperties.__maxMipLevel = mipmaps.length - 1; + + } else { + + state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); + textureProperties.__maxMipLevel = 0; + } } - function getRenderTargetSamples( renderTarget ) { + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? - Math.min( maxSamples, renderTarget.samples ) : 0; + generateMipmap( textureType, texture, image.width, image.height ); } - function updateVideoTexture( texture ) { + textureProperties.__version = texture.version; - var frame = info.render.frame; + if ( texture.onUpdate ) texture.onUpdate( texture ); - // Check the last frame we updated the VideoTexture + } - if ( _videoTextures.get( texture ) !== frame ) { + // Render targets - _videoTextures.set( texture, frame ); - texture.update(); + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { - } + var glFormat = utils.convert( renderTarget.texture.format ); + var glType = utils.convert( renderTarget.texture.type ); + var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); + state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + _gl.bindFramebuffer( 36160, framebuffer ); + _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); + _gl.bindFramebuffer( 36160, null ); - } + } - // backwards compatibility + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { - var warnedTexture2D = false; - var warnedTextureCube = false; + _gl.bindRenderbuffer( 36161, renderbuffer ); - function safeSetTexture2D( texture, slot ) { + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - if ( texture && texture.isWebGLRenderTarget ) { + var glInternalFormat = 33189; - if ( warnedTexture2D === false ) { + if ( isMultisample ) { - console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warnedTexture2D = true; + var depthTexture = renderTarget.depthTexture; - } + if ( depthTexture && depthTexture.isDepthTexture ) { - texture = texture.texture; + if ( depthTexture.type === FloatType ) { - } + glInternalFormat = 36012; - setTexture2D( texture, slot ); + } else if ( depthTexture.type === UnsignedIntType ) { - } + glInternalFormat = 33190; - function safeSetTextureCube( texture, slot ) { + } - if ( texture && texture.isWebGLRenderTargetCube ) { + } - if ( warnedTextureCube === false ) { + var samples = getRenderTargetSamples( renderTarget ); - console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warnedTextureCube = true; + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - } + } else { - texture = texture.texture; + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); } - // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture - // TODO: unify these code paths - if ( ( texture && texture.isCubeTexture ) || - ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { + _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); - // CompressedTexture can have Array in image :/ + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - // this function alone should take care of cube textures - setTextureCube( texture, slot ); + if ( isMultisample ) { - } else { + var samples = getRenderTargetSamples( renderTarget ); - // assumed: texture property of THREE.WebGLRenderTargetCube - setTextureCubeDynamic( texture, slot ); + _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); - } + } else { - } + _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); - // + } - this.allocateTextureUnit = allocateTextureUnit; - this.resetTextureUnits = resetTextureUnits; - this.setTexture2D = setTexture2D; - this.setTexture2DArray = setTexture2DArray; - this.setTexture3D = setTexture3D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); - this.safeSetTexture2D = safeSetTexture2D; - this.safeSetTextureCube = safeSetTextureCube; + } else { - } + var glFormat = utils.convert( renderTarget.texture.format ); + var glType = utils.convert( renderTarget.texture.type ); + var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); - /** - * @author thespite / http://www.twitter.com/thespite - */ + if ( isMultisample ) { - function WebGLUtils( gl, extensions, capabilities ) { + var samples = getRenderTargetSamples( renderTarget ); - var isWebGL2 = capabilities.isWebGL2; + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - function convert( p ) { + } else { - var extension; + _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); - if ( p === UnsignedByteType ) { return 5121; } - if ( p === UnsignedShort4444Type ) { return 32819; } - if ( p === UnsignedShort5551Type ) { return 32820; } - if ( p === UnsignedShort565Type ) { return 33635; } + } - if ( p === ByteType ) { return 5120; } - if ( p === ShortType ) { return 5122; } - if ( p === UnsignedShortType ) { return 5123; } - if ( p === IntType ) { return 5124; } - if ( p === UnsignedIntType ) { return 5125; } - if ( p === FloatType ) { return 5126; } + } - if ( p === HalfFloatType ) { + _gl.bindRenderbuffer( 36161, null ); - if ( isWebGL2 ) { return 5131; } + } - extension = extensions.get( 'OES_texture_half_float' ); + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - if ( extension !== null ) { + var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); - return extension.HALF_FLOAT_OES; + _gl.bindFramebuffer( 36160, framebuffer ); - } else { + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { - return null; + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); - } + } - } + // upload an empty depth texture with framebuffer size + if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { - if ( p === AlphaFormat ) { return 6406; } - if ( p === RGBFormat ) { return 6407; } - if ( p === RGBAFormat ) { return 6408; } - if ( p === LuminanceFormat ) { return 6409; } - if ( p === LuminanceAlphaFormat ) { return 6410; } - if ( p === DepthFormat ) { return 6402; } - if ( p === DepthStencilFormat ) { return 34041; } - if ( p === RedFormat ) { return 6403; } + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; - if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || - p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + } - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + setTexture2D( renderTarget.depthTexture, 0 ); - if ( extension !== null ) { + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; } - if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; } - if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; } - if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; } + if ( renderTarget.depthTexture.format === DepthFormat ) { - } else { + _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); - return null; + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - } + _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); - } + } else { - if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || - p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { + throw new Error( 'Unknown depthTexture format' ); - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + } - if ( extension !== null ) { + } - if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; } - if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; } - if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; } - if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - } else { + var renderTargetProperties = properties.get( renderTarget ); - return null; + var isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); - } + if ( renderTarget.depthTexture ) { - } + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); - if ( p === RGB_ETC1_Format ) { + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + } else { - if ( extension !== null ) { + if ( isCube ) { - return extension.COMPRESSED_RGB_ETC1_WEBGL; + renderTargetProperties.__webglDepthbuffer = []; - } else { + for ( var i = 0; i < 6; i ++ ) { - return null; + _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); } - } + } else { - if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || - p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || - p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || - p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || - p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { + _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); - extension = extensions.get( 'WEBGL_compressed_texture_astc' ); + } - if ( extension !== null ) { + } - // TODO Complete? + _gl.bindFramebuffer( 36160, null ); - return p; + } - } else { + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { - return null; + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - } + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - } + textureProperties.__webglTexture = _gl.createTexture(); - if ( p === UnsignedInt248Type ) { + info.memory.textures ++; - if ( isWebGL2 ) { return 34042; } + var isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); + var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); + var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; - extension = extensions.get( 'WEBGL_depth_texture' ); + // Handles WebGL2 RGBFormat fallback - #18858 - if ( extension !== null ) { + if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) { - return extension.UNSIGNED_INT_24_8_WEBGL; + renderTarget.texture.format = RGBAFormat; - } else { + console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' ); - return null; + } - } + // Setup framebuffer - } + if ( isCube ) { - } + renderTargetProperties.__webglFramebuffer = []; - return { convert: convert }; + for ( var i = 0; i < 6; i ++ ) { - } + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - /** - * @author fernandojsg / http://fernandojsg.com - * @author Takahiro https://github.com/takahirox - */ + } - function WebGLMultiviewRenderTarget( width, height, numViews, options ) { + } else { - WebGLRenderTarget.call( this, width, height, options ); + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - this.depthBuffer = false; - this.stencilBuffer = false; + if ( isMultisample ) { - this.numViews = numViews; + if ( isWebGL2 ) { - } + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); - WebGLMultiviewRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), { + _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); - constructor: WebGLMultiviewRenderTarget, + var glFormat = utils.convert( renderTarget.texture.format ); + var glType = utils.convert( renderTarget.texture.type ); + var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); + var samples = getRenderTargetSamples( renderTarget ); + _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); - isWebGLMultiviewRenderTarget: true, + _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); + _gl.bindRenderbuffer( 36161, null ); - copy: function ( source ) { + if ( renderTarget.depthBuffer ) { - WebGLRenderTarget.prototype.copy.call( this, source ); + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); - this.numViews = source.numViews; + } - return this; + _gl.bindFramebuffer( 36160, null ); - }, - setNumViews: function ( numViews ) { + } else { - if ( this.numViews !== numViews ) { + console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); - this.numViews = numViews; - this.dispose(); + } } - return this; - } - } ); - - /** - * @author fernandojsg / http://fernandojsg.com - * @author Takahiro https://github.com/takahirox - */ + // Setup color buffer - function WebGLMultiview( renderer, gl ) { + if ( isCube ) { - var DEFAULT_NUMVIEWS = 2; + state.bindTexture( 34067, textureProperties.__webglTexture ); + setTextureParameters( 34067, renderTarget.texture, supportsMips ); - var extensions = renderer.extensions; - var properties = renderer.properties; + for ( var i = 0; i < 6; i ++ ) { - var renderTarget, currentRenderTarget; - var mat3, mat4, cameraArray, renderSize; + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i ); - var available; - var maxNumViews = 0; + } - // + if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { - function isAvailable() { + generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height ); - if ( available === undefined ) { + } - var extension = extensions.get( 'OVR_multiview2' ); + state.bindTexture( 34067, null ); - available = extension !== null && gl.getContextAttributes().antialias === false; + } else { - if ( available ) { + state.bindTexture( 3553, textureProperties.__webglTexture ); + setTextureParameters( 3553, renderTarget.texture, supportsMips ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 ); - maxNumViews = gl.getParameter( extension.MAX_VIEWS_OVR ); - renderTarget = new WebGLMultiviewRenderTarget( 0, 0, DEFAULT_NUMVIEWS ); + if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { - renderSize = new Vector2(); - mat4 = []; - mat3 = []; - cameraArray = []; + generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height ); - for ( var i = 0; i < maxNumViews; i ++ ) { + } - mat4[ i ] = new Matrix4(); - mat3[ i ] = new Matrix3(); + state.bindTexture( 3553, null ); - } + } - } + // Setup depth and stencil buffers - } + if ( renderTarget.depthBuffer ) { - return available; + setupDepthRenderbuffer( renderTarget ); } - function getCameraArray( camera ) { + } + + function updateRenderTargetMipmap( renderTarget ) { - if ( camera.isArrayCamera ) { return camera.cameras; } + var texture = renderTarget.texture; + var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; - cameraArray[ 0 ] = camera; + if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { - return cameraArray; + var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; + var webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target, texture, renderTarget.width, renderTarget.height ); + state.bindTexture( target, null ); } - function updateCameraProjectionMatricesUniform( camera, uniforms ) { + } - var cameras = getCameraArray( camera ); + function updateMultisampleRenderTarget( renderTarget ) { - for ( var i = 0; i < cameras.length; i ++ ) { + if ( renderTarget.isWebGLMultisampleRenderTarget ) { - mat4[ i ].copy( cameras[ i ].projectionMatrix ); + if ( isWebGL2 ) { - } + var renderTargetProperties = properties.get( renderTarget ); - uniforms.setValue( gl, 'projectionMatrices', mat4 ); + _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); + _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); - } + var width = renderTarget.width; + var height = renderTarget.height; + var mask = 16384; + + if ( renderTarget.depthBuffer ) mask |= 256; + if ( renderTarget.stencilBuffer ) mask |= 1024; - function updateCameraViewMatricesUniform( camera, uniforms ) { + _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); - var cameras = getCameraArray( camera ); + _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905 - for ( var i = 0; i < cameras.length; i ++ ) { + } else { - mat4[ i ].copy( cameras[ i ].matrixWorldInverse ); + console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); } - uniforms.setValue( gl, 'viewMatrices', mat4 ); - } - function updateObjectMatricesUniforms( object, camera, uniforms ) { + } + + function getRenderTargetSamples( renderTarget ) { - var cameras = getCameraArray( camera ); + return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? + Math.min( maxSamples, renderTarget.samples ) : 0; - for ( var i = 0; i < cameras.length; i ++ ) { + } - mat4[ i ].multiplyMatrices( cameras[ i ].matrixWorldInverse, object.matrixWorld ); - mat3[ i ].getNormalMatrix( mat4[ i ] ); + function updateVideoTexture( texture ) { - } + var frame = info.render.frame; - uniforms.setValue( gl, 'modelViewMatrices', mat4 ); - uniforms.setValue( gl, 'normalMatrices', mat3 ); + // Check the last frame we updated the VideoTexture + + if ( _videoTextures.get( texture ) !== frame ) { + + _videoTextures.set( texture, frame ); + texture.update(); } - function isMultiviewCompatible( camera ) { + } + + // backwards compatibility - if ( camera.isArrayCamera === undefined ) { return true; } + var warnedTexture2D = false; + var warnedTextureCube = false; - var cameras = camera.cameras; + function safeSetTexture2D( texture, slot ) { - if ( cameras.length > maxNumViews ) { return false; } + if ( texture && texture.isWebGLRenderTarget ) { - for ( var i = 1, il = cameras.length; i < il; i ++ ) { + if ( warnedTexture2D === false ) { - if ( cameras[ 0 ].viewport.z !== cameras[ i ].viewport.z || - cameras[ 0 ].viewport.w !== cameras[ i ].viewport.w ) { return false; } + console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warnedTexture2D = true; } - return true; + texture = texture.texture; } - function resizeRenderTarget( camera ) { + setTexture2D( texture, slot ); + + } - if ( currentRenderTarget ) { + function safeSetTextureCube( texture, slot ) { - renderSize.set( currentRenderTarget.width, currentRenderTarget.height ); + if ( texture && texture.isWebGLCubeRenderTarget ) { - } else { + if ( warnedTextureCube === false ) { - renderer.getDrawingBufferSize( renderSize ); + console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warnedTextureCube = true; } - if ( camera.isArrayCamera ) { + texture = texture.texture; - var viewport = camera.cameras[ 0 ].viewport; + } - renderTarget.setSize( viewport.z, viewport.w ); - renderTarget.setNumViews( camera.cameras.length ); + // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture + // TODO: unify these code paths + if ( ( texture && texture.isCubeTexture ) || + ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - } else { + // CompressedTexture can have Array in image :/ - renderTarget.setSize( renderSize.x, renderSize.y ); - renderTarget.setNumViews( DEFAULT_NUMVIEWS ); + // this function alone should take care of cube textures + setTextureCube( texture, slot ); - } + } else { - } + // assumed: texture property of THREE.WebGLCubeRenderTarget + setTextureCubeDynamic( texture, slot ); - function attachCamera( camera ) { + } - if ( isMultiviewCompatible( camera ) === false ) { return; } + } - currentRenderTarget = renderer.getRenderTarget(); - resizeRenderTarget( camera ); - renderer.setRenderTarget( renderTarget ); + // - } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; - function detachCamera( camera ) { + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; - if ( renderTarget !== renderer.getRenderTarget() ) { return; } + this.safeSetTexture2D = safeSetTexture2D; + this.safeSetTextureCube = safeSetTextureCube; - renderer.setRenderTarget( currentRenderTarget ); +} - flush( camera ); +/** + * @author thespite / http://www.twitter.com/thespite + */ - } +function WebGLUtils( gl, extensions, capabilities ) { - function flush( camera ) { + var isWebGL2 = capabilities.isWebGL2; - var srcRenderTarget = renderTarget; - var numViews = srcRenderTarget.numViews; + function convert( p ) { - var srcFramebuffers = properties.get( srcRenderTarget ).__webglViewFramebuffers; + var extension; - var viewWidth = srcRenderTarget.width; - var viewHeight = srcRenderTarget.height; + if ( p === UnsignedByteType ) return 5121; + if ( p === UnsignedShort4444Type ) return 32819; + if ( p === UnsignedShort5551Type ) return 32820; + if ( p === UnsignedShort565Type ) return 33635; - if ( camera.isArrayCamera ) { + if ( p === ByteType ) return 5120; + if ( p === ShortType ) return 5122; + if ( p === UnsignedShortType ) return 5123; + if ( p === IntType ) return 5124; + if ( p === UnsignedIntType ) return 5125; + if ( p === FloatType ) return 5126; - for ( var i = 0; i < numViews; i ++ ) { + if ( p === HalfFloatType ) { - var viewport = camera.cameras[ i ].viewport; + if ( isWebGL2 ) return 5131; - var x1 = viewport.x; - var y1 = viewport.y; - var x2 = x1 + viewport.z; - var y2 = y1 + viewport.w; + extension = extensions.get( 'OES_texture_half_float' ); - gl.bindFramebuffer( 36008, srcFramebuffers[ i ] ); - gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728 ); + if ( extension !== null ) { - } + return extension.HALF_FLOAT_OES; } else { - gl.bindFramebuffer( 36008, srcFramebuffers[ 0 ] ); - gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728 ); + return null; } } - this.isAvailable = isAvailable; - this.attachCamera = attachCamera; - this.detachCamera = detachCamera; - this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform; - this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform; - this.updateObjectMatricesUniforms = updateObjectMatricesUniforms; - - } - - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( p === AlphaFormat ) return 6406; + if ( p === RGBFormat ) return 6407; + if ( p === RGBAFormat ) return 6408; + if ( p === LuminanceFormat ) return 6409; + if ( p === LuminanceAlphaFormat ) return 6410; + if ( p === DepthFormat ) return 6402; + if ( p === DepthStencilFormat ) return 34041; + if ( p === RedFormat ) return 6403; - function Group() { + // WebGL2 formats. - Object3D.call( this ); + if ( p === RedIntegerFormat ) return 36244; + if ( p === RGFormat ) return 33319; + if ( p === RGIntegerFormat ) return 33320; + if ( p === RGBIntegerFormat ) return 36248; + if ( p === RGBAIntegerFormat ) return 36249; - this.type = 'Group'; + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || + p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { - } + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - Group.prototype = Object.assign( Object.create( Object3D.prototype ), { + if ( extension !== null ) { - constructor: Group, + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - isGroup: true + } else { - } ); + return null; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function ArrayCamera( array ) { + } - PerspectiveCamera.call( this ); + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || + p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { - this.cameras = array || []; + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - } + if ( extension !== null ) { - ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - constructor: ArrayCamera, + } else { - isArrayCamera: true + return null; - } ); + } - /** - * @author jsantell / https://www.jsantell.com/ - * @author mrdoob / http://mrdoob.com/ - */ + } - var cameraLPos = new Vector3(); - var cameraRPos = new Vector3(); + if ( p === RGB_ETC1_Format ) { - /** - * Assumes 2 cameras that are parallel and share an X-axis, and that - * the cameras' projection and world matrices have already been set. - * And that near and far planes are identical for both cameras. - * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 - */ - function setProjectionFromUnion( camera, cameraL, cameraR ) { + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); - cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); + if ( extension !== null ) { - var ipd = cameraLPos.distanceTo( cameraRPos ); + return extension.COMPRESSED_RGB_ETC1_WEBGL; - var projL = cameraL.projectionMatrix.elements; - var projR = cameraR.projectionMatrix.elements; + } else { - // VR systems will have identical far and near planes, and - // most likely identical top and bottom frustum extents. - // Use the left camera for these values. - var near = projL[ 14 ] / ( projL[ 10 ] - 1 ); - var far = projL[ 14 ] / ( projL[ 10 ] + 1 ); - var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; - var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; + return null; - var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; - var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; - var left = near * leftFov; - var right = near * rightFov; + } - // Calculate the new camera's position offset from the - // left camera. xOffset should be roughly half `ipd`. - var zOffset = ipd / ( - leftFov + rightFov ); - var xOffset = zOffset * - leftFov; + } - // TODO: Better way to apply this offset? - cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); - camera.translateX( xOffset ); - camera.translateZ( zOffset ); - camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) { - // Find the union of the frustum values of the cameras and scale - // the values so that the near plane's position does not change in world space, - // although must now be relative to the new union camera. - var near2 = near + zOffset; - var far2 = far + zOffset; - var left2 = left - xOffset; - var right2 = right + ( ipd - xOffset ); - var top2 = topFov * far / far2 * near2; - var bottom2 = bottomFov * far / far2 * near2; + extension = extensions.get( 'WEBGL_compressed_texture_etc' ); - camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); + if ( extension !== null ) { - } + if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2; + if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebVRManager( renderer ) { + } - var renderWidth, renderHeight; - var scope = this; + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || + p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || + p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || + p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || + p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || + p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) { - var device = null; - var frameData = null; + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); - var poseTarget = null; + if ( extension !== null ) { - var controllers = []; - var standingMatrix = new Matrix4(); - var standingMatrixInverse = new Matrix4(); + // TODO Complete? - var framebufferScaleFactor = 1.0; + return p; - var referenceSpaceType = 'local-floor'; + } else { - if ( typeof window !== 'undefined' && 'VRFrameData' in window ) { + return null; - frameData = new window.VRFrameData(); - window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false ); + } } - var matrixWorldInverse = new Matrix4(); - var tempQuaternion = new Quaternion(); - var tempPosition = new Vector3(); + if ( p === RGBA_BPTC_Format ) { - var cameraL = new PerspectiveCamera(); - cameraL.viewport = new Vector4(); - cameraL.layers.enable( 1 ); + extension = extensions.get( 'EXT_texture_compression_bptc' ); - var cameraR = new PerspectiveCamera(); - cameraR.viewport = new Vector4(); - cameraR.layers.enable( 2 ); + if ( extension !== null ) { - var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); - cameraVR.layers.enable( 1 ); - cameraVR.layers.enable( 2 ); + // TODO Complete? - // + return p; + + } else { - function isPresenting() { + return null; - return device !== null && device.isPresenting === true; + } } - var currentSize = new Vector2(), currentPixelRatio; + if ( p === UnsignedInt248Type ) { - function onVRDisplayPresentChange() { + if ( isWebGL2 ) return 34042; - if ( isPresenting() ) { + extension = extensions.get( 'WEBGL_depth_texture' ); - var eyeParameters = device.getEyeParameters( 'left' ); - renderWidth = 2 * eyeParameters.renderWidth * framebufferScaleFactor; - renderHeight = eyeParameters.renderHeight * framebufferScaleFactor; + if ( extension !== null ) { - currentPixelRatio = renderer.getPixelRatio(); - renderer.getSize( currentSize ); + return extension.UNSIGNED_INT_24_8_WEBGL; - renderer.setDrawingBufferSize( renderWidth, renderHeight, 1 ); + } else { - cameraL.viewport.set( 0, 0, renderWidth / 2, renderHeight ); - cameraR.viewport.set( renderWidth / 2, 0, renderWidth / 2, renderHeight ); + return null; - animation.start(); + } - scope.dispatchEvent( { type: 'sessionstart' } ); + } - } else { + } - if ( scope.enabled ) { + return { convert: convert }; - renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio ); +} - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - animation.stop(); +function ArrayCamera( array ) { - scope.dispatchEvent( { type: 'sessionend' } ); + PerspectiveCamera.call( this ); - } + this.cameras = array || []; - } +} - // +ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { - var triggers = []; + constructor: ArrayCamera, - function findGamepad( id ) { + isArrayCamera: true - var gamepads = navigator.getGamepads && navigator.getGamepads(); +} ); - for ( var i = 0, l = gamepads.length; i < l; i ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var gamepad = gamepads[ i ]; +function Group() { - if ( gamepad && ( gamepad.id === 'Daydream Controller' || - gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' || - gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) || - gamepad.id.startsWith( 'HTC Vive Focus' ) || - gamepad.id.startsWith( 'Spatial Controller' ) ) ) { + Object3D.call( this ); - var hand = gamepad.hand; + this.type = 'Group'; - if ( id === 0 && ( hand === '' || hand === 'right' ) ) { return gamepad; } - if ( id === 1 && ( hand === 'left' ) ) { return gamepad; } +} - } +Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Group, - } + isGroup: true - function updateControllers() { +} ); - for ( var i = 0; i < controllers.length; i ++ ) { +/** + * @author Mugen87 / https://github.com/Mugen87 + */ - var controller = controllers[ i ]; +function WebXRController() { - var gamepad = findGamepad( i ); + this._targetRay = null; + this._grip = null; - if ( gamepad !== undefined && gamepad.pose !== undefined ) { +} - if ( gamepad.pose === null ) { return; } +Object.assign( WebXRController.prototype, { - // Pose + constructor: WebXRController, - var pose = gamepad.pose; + getTargetRaySpace: function () { - if ( pose.hasPosition === false ) { controller.position.set( 0.2, - 0.6, - 0.05 ); } + if ( this._targetRay === null ) { - if ( pose.position !== null ) { controller.position.fromArray( pose.position ); } - if ( pose.orientation !== null ) { controller.quaternion.fromArray( pose.orientation ); } - controller.matrix.compose( controller.position, controller.quaternion, controller.scale ); - controller.matrix.premultiply( standingMatrix ); - controller.matrix.decompose( controller.position, controller.quaternion, controller.scale ); - controller.matrixWorldNeedsUpdate = true; - controller.visible = true; + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; - // Trigger + } - var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1; + return this._targetRay; - if ( triggers[ i ] === undefined ) { triggers[ i ] = false; } + }, - if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) { + getGripSpace: function () { - triggers[ i ] = gamepad.buttons[ buttonId ].pressed; + if ( this._grip === null ) { - if ( triggers[ i ] === true ) { + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; - controller.dispatchEvent( { type: 'selectstart' } ); + } - } else { + return this._grip; - controller.dispatchEvent( { type: 'selectend' } ); - controller.dispatchEvent( { type: 'select' } ); + }, - } + dispatchEvent: function ( event ) { - } + if ( this._targetRay !== null ) { - } else { + this._targetRay.dispatchEvent( event ); - controller.visible = false; + } - } + if ( this._grip !== null ) { - } + this._grip.dispatchEvent( event ); } - function updateViewportFromBounds( viewport, bounds ) { + return this; - if ( bounds !== null && bounds.length === 4 ) { + }, - viewport.set( bounds[ 0 ] * renderWidth, bounds[ 1 ] * renderHeight, bounds[ 2 ] * renderWidth, bounds[ 3 ] * renderHeight ); + disconnect: function ( inputSource ) { - } + this.dispatchEvent( { type: 'disconnected', data: inputSource } ); - } + if ( this._targetRay !== null ) { - // + this._targetRay.visible = false; - this.enabled = false; + } - this.getController = function ( id ) { + if ( this._grip !== null ) { - var controller = controllers[ id ]; + this._grip.visible = false; - if ( controller === undefined ) { + } - controller = new Group(); - controller.matrixAutoUpdate = false; - controller.visible = false; + return this; - controllers[ id ] = controller; + }, - } + update: function ( inputSource, frame, referenceSpace ) { - return controller; + var inputPose = null; + var gripPose = null; - }; + var targetRay = this._targetRay; + var grip = this._grip; - this.getDevice = function () { + if ( inputSource ) { - return device; + if ( targetRay !== null ) { - }; + inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); - this.setDevice = function ( value ) { + if ( inputPose !== null ) { - if ( value !== undefined ) { device = value; } + targetRay.matrix.fromArray( inputPose.transform.matrix ); + targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale ); - animation.setContext( value ); + } - }; + } - this.setFramebufferScaleFactor = function ( value ) { + if ( grip !== null && inputSource.gripSpace ) { - framebufferScaleFactor = value; + gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); - }; + if ( gripPose !== null ) { - this.setReferenceSpaceType = function ( value ) { + grip.matrix.fromArray( gripPose.transform.matrix ); + grip.matrix.decompose( grip.position, grip.rotation, grip.scale ); - referenceSpaceType = value; + } - }; + } - this.setPoseTarget = function ( object ) { + } - if ( object !== undefined ) { poseTarget = object; } + if ( targetRay !== null ) { - }; + targetRay.visible = ( inputPose !== null ); - this.getCamera = function ( camera ) { + } - var userHeight = referenceSpaceType === 'local-floor' ? 1.6 : 0; + if ( grip !== null ) { - if ( isPresenting() === false ) { + grip.visible = ( gripPose !== null ); - camera.position.set( 0, userHeight, 0 ); - camera.rotation.set( 0, 0, 0 ); + } - return camera; + return this; - } + } - device.depthNear = camera.near; - device.depthFar = camera.far; +} ); - device.getFrameData( frameData ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - // +function WebXRManager( renderer, gl ) { - if ( referenceSpaceType === 'local-floor' ) { + var scope = this; - var stageParameters = device.stageParameters; + var session = null; - if ( stageParameters ) { + var framebufferScaleFactor = 1.0; - standingMatrix.fromArray( stageParameters.sittingToStandingTransform ); + var referenceSpace = null; + var referenceSpaceType = 'local-floor'; - } else { + var pose = null; - standingMatrix.makeTranslation( 0, userHeight, 0 ); + var controllers = []; + var inputSourcesMap = new Map(); - } + // - } + var cameraL = new PerspectiveCamera(); + cameraL.layers.enable( 1 ); + cameraL.viewport = new Vector4(); + var cameraR = new PerspectiveCamera(); + cameraR.layers.enable( 2 ); + cameraR.viewport = new Vector4(); - var pose = frameData.pose; - var poseObject = poseTarget !== null ? poseTarget : camera; + var cameras = [ cameraL, cameraR ]; - // We want to manipulate poseObject by its position and quaternion components since users may rely on them. - poseObject.matrix.copy( standingMatrix ); - poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale ); + var cameraVR = new ArrayCamera(); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); - if ( pose.orientation !== null ) { + var _currentDepthNear = null; + var _currentDepthFar = null; - tempQuaternion.fromArray( pose.orientation ); - poseObject.quaternion.multiply( tempQuaternion ); + // - } + this.enabled = false; - if ( pose.position !== null ) { + this.isPresenting = false; - tempQuaternion.setFromRotationMatrix( standingMatrix ); - tempPosition.fromArray( pose.position ); - tempPosition.applyQuaternion( tempQuaternion ); - poseObject.position.add( tempPosition ); + this.getController = function ( index ) { - } + var controller = controllers[ index ]; - poseObject.updateMatrixWorld(); + if ( controller === undefined ) { - // + controller = new WebXRController(); + controllers[ index ] = controller; - cameraL.near = camera.near; - cameraR.near = camera.near; + } - cameraL.far = camera.far; - cameraR.far = camera.far; + return controller.getTargetRaySpace(); - cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix ); - cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix ); + }; - // TODO (mrdoob) Double check this code + this.getControllerGrip = function ( index ) { - standingMatrixInverse.getInverse( standingMatrix ); + var controller = controllers[ index ]; - if ( referenceSpaceType === 'local-floor' ) { + if ( controller === undefined ) { - cameraL.matrixWorldInverse.multiply( standingMatrixInverse ); - cameraR.matrixWorldInverse.multiply( standingMatrixInverse ); + controller = new WebXRController(); + controllers[ index ] = controller; - } + } - var parent = poseObject.parent; + return controller.getGripSpace(); - if ( parent !== null ) { + }; - matrixWorldInverse.getInverse( parent.matrixWorld ); + // - cameraL.matrixWorldInverse.multiply( matrixWorldInverse ); - cameraR.matrixWorldInverse.multiply( matrixWorldInverse ); + function onSessionEvent( event ) { - } + var controller = inputSourcesMap.get( event.inputSource ); - // envMap and Mirror needs camera.matrixWorld + if ( controller ) { - cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse ); - cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse ); + controller.dispatchEvent( { type: event.type } ); - cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix ); - cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix ); + } - setProjectionFromUnion( cameraVR, cameraL, cameraR ); + } - // + function onSessionEnd() { - var layers = device.getLayers(); + inputSourcesMap.forEach( function ( controller, inputSource ) { - if ( layers.length ) { + controller.disconnect( inputSource ); - var layer = layers[ 0 ]; + } ); - updateViewportFromBounds( cameraL.viewport, layer.leftBounds ); - updateViewportFromBounds( cameraR.viewport, layer.rightBounds ); + inputSourcesMap.clear(); - } + // - updateControllers(); + renderer.setFramebuffer( null ); + renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830 + animation.stop(); - return cameraVR; + scope.isPresenting = false; - }; + scope.dispatchEvent( { type: 'sessionend' } ); - this.getStandingMatrix = function () { + } - return standingMatrix; + function onRequestReferenceSpace( value ) { - }; + referenceSpace = value; - this.isPresenting = isPresenting; + animation.setContext( session ); + animation.start(); - // Animation Loop + scope.isPresenting = true; - var animation = new WebGLAnimation(); + scope.dispatchEvent( { type: 'sessionstart' } ); - this.setAnimationLoop = function ( callback ) { + } - animation.setAnimationLoop( callback ); + this.setFramebufferScaleFactor = function ( value ) { - if ( isPresenting() ) { animation.start(); } + framebufferScaleFactor = value; - }; + if ( scope.isPresenting === true ) { - this.submitFrame = function () { + console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' ); - if ( isPresenting() ) { device.submitFrame(); } + } - }; + }; - this.dispose = function () { + this.setReferenceSpaceType = function ( value ) { - if ( typeof window !== 'undefined' ) { + referenceSpaceType = value; - window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange ); + if ( scope.isPresenting === true ) { - } + console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' ); - }; + } - // DEPRECATED + }; - this.setFrameOfReferenceType = function () { + this.getReferenceSpace = function () { - console.warn( 'THREE.WebVRManager: setFrameOfReferenceType() has been deprecated.' ); + return referenceSpace; - }; + }; - } + this.getSession = function () { - Object.assign( WebVRManager.prototype, EventDispatcher.prototype ); + return session; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function WebXRManager( renderer, gl ) { + this.setSession = function ( value ) { - var scope = this; + session = value; - var session = null; + if ( session !== null ) { - // var framebufferScaleFactor = 1.0; + session.addEventListener( 'select', onSessionEvent ); + session.addEventListener( 'selectstart', onSessionEvent ); + session.addEventListener( 'selectend', onSessionEvent ); + session.addEventListener( 'squeeze', onSessionEvent ); + session.addEventListener( 'squeezestart', onSessionEvent ); + session.addEventListener( 'squeezeend', onSessionEvent ); + session.addEventListener( 'end', onSessionEnd ); - var referenceSpace = null; - var referenceSpaceType = 'local-floor'; + var attributes = gl.getContextAttributes(); - var pose = null; + if ( attributes.xrCompatible !== true ) { - var controllers = []; - var sortedInputSources = []; + gl.makeXRCompatible(); - function isPresenting() { + } - return session !== null && referenceSpace !== null; + var layerInit = { + antialias: attributes.antialias, + alpha: attributes.alpha, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor: framebufferScaleFactor + }; - } + // eslint-disable-next-line no-undef + var baseLayer = new XRWebGLLayer( session, gl, layerInit ); - // + session.updateRenderState( { baseLayer: baseLayer } ); - var cameraL = new PerspectiveCamera(); - cameraL.layers.enable( 1 ); - cameraL.viewport = new Vector4(); + session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace ); - var cameraR = new PerspectiveCamera(); - cameraR.layers.enable( 2 ); - cameraR.viewport = new Vector4(); + // - var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); - cameraVR.layers.enable( 1 ); - cameraVR.layers.enable( 2 ); + session.addEventListener( 'inputsourceschange', updateInputSources ); - // + } - this.enabled = false; + }; - this.getController = function ( id ) { + function updateInputSources( event ) { - var controller = controllers[ id ]; + var inputSources = session.inputSources; - if ( controller === undefined ) { + // Assign inputSources to available controllers - controller = new Group(); - controller.matrixAutoUpdate = false; - controller.visible = false; + for ( var i = 0; i < controllers.length; i ++ ) { - controllers[ id ] = controller; + inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); - } + } - return controller; + // Notify disconnected - }; + for ( var i = 0; i < event.removed.length; i ++ ) { - // + var inputSource = event.removed[ i ]; + var controller = inputSourcesMap.get( inputSource ); - function onSessionEvent( event ) { + if ( controller ) { - for ( var i = 0; i < controllers.length; i ++ ) { + controller.dispatchEvent( { type: 'disconnected', data: inputSource } ); + inputSourcesMap.delete( inputSource ); - if ( sortedInputSources[ i ] === event.inputSource ) { + } - controllers[ i ].dispatchEvent( { type: event.type } ); + } - } + // Notify connected - } + for ( var i = 0; i < event.added.length; i ++ ) { - } + var inputSource = event.added[ i ]; + var controller = inputSourcesMap.get( inputSource ); - function onSessionEnd() { + if ( controller ) { - renderer.setFramebuffer( null ); - renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830 - animation.stop(); + controller.dispatchEvent( { type: 'connected', data: inputSource } ); - scope.dispatchEvent( { type: 'sessionend' } ); + } } - function onRequestReferenceSpace( value ) { - - referenceSpace = value; + } - animation.setContext( session ); - animation.start(); + // - scope.dispatchEvent( { type: 'sessionstart' } ); + var cameraLPos = new Vector3(); + var cameraRPos = new Vector3(); - } + /** + * @author jsantell / https://www.jsantell.com/ + * + * Assumes 2 cameras that are parallel and share an X-axis, and that + * the cameras' projection and world matrices have already been set. + * And that near and far planes are identical for both cameras. + * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 + */ + function setProjectionFromUnion( camera, cameraL, cameraR ) { - this.setFramebufferScaleFactor = function ( /* value */ ) { + cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); + cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); - // framebufferScaleFactor = value; + var ipd = cameraLPos.distanceTo( cameraRPos ); - }; + var projL = cameraL.projectionMatrix.elements; + var projR = cameraR.projectionMatrix.elements; - this.setReferenceSpaceType = function ( value ) { + // VR systems will have identical far and near planes, and + // most likely identical top and bottom frustum extents. + // Use the left camera for these values. + var near = projL[ 14 ] / ( projL[ 10 ] - 1 ); + var far = projL[ 14 ] / ( projL[ 10 ] + 1 ); + var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; + var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; - referenceSpaceType = value; + var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; + var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; + var left = near * leftFov; + var right = near * rightFov; - }; + // Calculate the new camera's position offset from the + // left camera. xOffset should be roughly half `ipd`. + var zOffset = ipd / ( - leftFov + rightFov ); + var xOffset = zOffset * - leftFov; - this.getSession = function () { + // TODO: Better way to apply this offset? + cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); + camera.translateX( xOffset ); + camera.translateZ( zOffset ); + camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - return session; + // Find the union of the frustum values of the cameras and scale + // the values so that the near plane's position does not change in world space, + // although must now be relative to the new union camera. + var near2 = near + zOffset; + var far2 = far + zOffset; + var left2 = left - xOffset; + var right2 = right + ( ipd - xOffset ); + var top2 = topFov * far / far2 * near2; + var bottom2 = bottomFov * far / far2 * near2; - }; + camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); - this.setSession = function ( value ) { + } - session = value; + function updateCamera( camera, parent ) { - if ( session !== null ) { + if ( parent === null ) { - session.addEventListener( 'select', onSessionEvent ); - session.addEventListener( 'selectstart', onSessionEvent ); - session.addEventListener( 'selectend', onSessionEvent ); - session.addEventListener( 'end', onSessionEnd ); + camera.matrixWorld.copy( camera.matrix ); - // eslint-disable-next-line no-undef - session.updateRenderState( { baseLayer: new XRWebGLLayer( session, gl ) } ); + } else { - session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace ); + camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); - // + } - session.addEventListener( 'inputsourceschange', updateInputSources ); + camera.matrixWorldInverse.getInverse( camera.matrixWorld ); - updateInputSources(); + } - } + this.getCamera = function ( camera ) { - }; + cameraVR.near = cameraR.near = cameraL.near = camera.near; + cameraVR.far = cameraR.far = cameraL.far = camera.far; - function updateInputSources() { + if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { - for ( var i = 0; i < controllers.length; i ++ ) { + // Note that the new renderState won't apply until the next frame. See #18320 - sortedInputSources[ i ] = findInputSource( i ); + session.updateRenderState( { + depthNear: cameraVR.near, + depthFar: cameraVR.far + } ); - } + _currentDepthNear = cameraVR.near; + _currentDepthFar = cameraVR.far; } - function findInputSource( id ) { + var parent = camera.parent; + var cameras = cameraVR.cameras; - var inputSources = session.inputSources; + updateCamera( cameraVR, parent ); - for ( var i = 0; i < inputSources.length; i ++ ) { + for ( var i = 0; i < cameras.length; i ++ ) { - var inputSource = inputSources[ i ]; - var handedness = inputSource.handedness; + updateCamera( cameras[ i ], parent ); - if ( id === 0 && ( handedness === 'none' || handedness === 'right' ) ) { return inputSource; } - if ( id === 1 && ( handedness === 'left' ) ) { return inputSource; } + } - } + // update camera and its children - } + camera.matrixWorld.copy( cameraVR.matrixWorld ); - // + var children = camera.children; - function updateCamera( camera, parent ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - if ( parent === null ) { + children[ i ].updateMatrixWorld( true ); - camera.matrixWorld.copy( camera.matrix ); + } - } else { + // update projection matrix for proper view frustum culling - camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); + if ( cameras.length === 2 ) { - } + setProjectionFromUnion( cameraVR, cameraL, cameraR ); - camera.matrixWorldInverse.getInverse( camera.matrixWorld ); + } else { - } + // assume single camera setup (AR) - this.getCamera = function ( camera ) { + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); - if ( isPresenting() ) { + } - var parent = camera.parent; - var cameras = cameraVR.cameras; + return cameraVR; - updateCamera( cameraVR, parent ); + }; - for ( var i = 0; i < cameras.length; i ++ ) { + // Animation Loop - updateCamera( cameras[ i ], parent ); + var onAnimationFrameCallback = null; - } + function onAnimationFrame( time, frame ) { - // update camera and its children + pose = frame.getViewerPose( referenceSpace ); - camera.matrixWorld.copy( cameraVR.matrixWorld ); + if ( pose !== null ) { - var children = camera.children; + var views = pose.views; + var baseLayer = session.renderState.baseLayer; - for ( var i = 0, l = children.length; i < l; i ++ ) { + renderer.setFramebuffer( baseLayer.framebuffer ); - children[ i ].updateMatrixWorld( true ); + var cameraVRNeedsUpdate = false; - } + // check if it's necessary to rebuild cameraVR's camera list - setProjectionFromUnion( cameraVR, cameraL, cameraR ); + if ( views.length !== cameraVR.cameras.length ) { - return cameraVR; + cameraVR.cameras.length = 0; + cameraVRNeedsUpdate = true; } - return camera; + for ( var i = 0; i < views.length; i ++ ) { - }; + var view = views[ i ]; + var viewport = baseLayer.getViewport( view ); - this.isPresenting = isPresenting; + var camera = cameras[ i ]; + camera.matrix.fromArray( view.transform.matrix ); + camera.projectionMatrix.fromArray( view.projectionMatrix ); + camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); - // Animation Loop + if ( i === 0 ) { - var onAnimationFrameCallback = null; + cameraVR.matrix.copy( camera.matrix ); - function onAnimationFrame( time, frame ) { + } - pose = frame.getViewerPose( referenceSpace ); + if ( cameraVRNeedsUpdate === true ) { - if ( pose !== null ) { + cameraVR.cameras.push( camera ); - var views = pose.views; - var baseLayer = session.renderState.baseLayer; + } - renderer.setFramebuffer( baseLayer.framebuffer ); + } - for ( var i = 0; i < views.length; i ++ ) { + } - var view = views[ i ]; - var viewport = baseLayer.getViewport( view ); - var viewMatrix = view.transform.inverse.matrix; + // - var camera = cameraVR.cameras[ i ]; - camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix ); - camera.projectionMatrix.fromArray( view.projectionMatrix ); - camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); + var inputSources = session.inputSources; - if ( i === 0 ) { + for ( var i = 0; i < controllers.length; i ++ ) { - cameraVR.matrix.copy( camera.matrix ); + var controller = controllers[ i ]; + var inputSource = inputSources[ i ]; - } + controller.update( inputSource, frame, referenceSpace ); - } + } - } + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame ); - // + } - for ( var i = 0; i < controllers.length; i ++ ) { + var animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); - var controller = controllers[ i ]; + this.setAnimationLoop = function ( callback ) { - var inputSource = sortedInputSources[ i ]; + onAnimationFrameCallback = callback; - if ( inputSource ) { + }; - var inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); + this.dispose = function () {}; - if ( inputPose !== null ) { +} - controller.matrix.fromArray( inputPose.transform.matrix ); - controller.matrix.decompose( controller.position, controller.rotation, controller.scale ); - controller.visible = true; +Object.assign( WebXRManager.prototype, EventDispatcher.prototype ); - continue; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function WebGLMaterials( properties ) { - } + function refreshFogUniforms( uniforms, fog ) { - controller.visible = false; + uniforms.fogColor.value.copy( fog.color ); - } + if ( fog.isFog ) { - if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame, referenceSpace ); } + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - } + } else if ( fog.isFogExp2 ) { - var animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + uniforms.fogDensity.value = fog.density; - this.setAnimationLoop = function ( callback ) { + } - onAnimationFrameCallback = callback; + } - }; + function refreshMaterialUniforms( uniforms, material, environment, pixelRatio, height ) { - this.dispose = function () {}; + if ( material.isMeshBasicMaterial ) { - // DEPRECATED + refreshUniformsCommon( uniforms, material ); - this.getStandingMatrix = function () { + } else if ( material.isMeshLambertMaterial ) { - console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' ); - return new Matrix4(); + refreshUniformsCommon( uniforms, material ); + refreshUniformsLambert( uniforms, material ); - }; + } else if ( material.isMeshToonMaterial ) { - this.getDevice = function () { + refreshUniformsCommon( uniforms, material ); + refreshUniformsToon( uniforms, material ); - console.warn( 'THREE.WebXRManager: getDevice() has been deprecated.' ); + } else if ( material.isMeshPhongMaterial ) { - }; + refreshUniformsCommon( uniforms, material ); + refreshUniformsPhong( uniforms, material ); - this.setDevice = function () { + } else if ( material.isMeshStandardMaterial ) { - console.warn( 'THREE.WebXRManager: setDevice() has been deprecated.' ); + refreshUniformsCommon( uniforms, material, environment ); - }; + if ( material.isMeshPhysicalMaterial ) { - this.setFrameOfReferenceType = function () { + refreshUniformsPhysical( uniforms, material, environment ); - console.warn( 'THREE.WebXRManager: setFrameOfReferenceType() has been deprecated.' ); + } else { - }; + refreshUniformsStandard( uniforms, material, environment ); - this.submitFrame = function () {}; + } - } + } else if ( material.isMeshMatcapMaterial ) { - Object.assign( WebXRManager.prototype, EventDispatcher.prototype ); + refreshUniformsCommon( uniforms, material ); + refreshUniformsMatcap( uniforms, material ); - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author tschw - */ + } else if ( material.isMeshDepthMaterial ) { - function WebGLRenderer( parameters ) { + refreshUniformsCommon( uniforms, material ); + refreshUniformsDepth( uniforms, material ); - parameters = parameters || {}; + } else if ( material.isMeshDistanceMaterial ) { - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + refreshUniformsCommon( uniforms, material ); + refreshUniformsDistance( uniforms, material ); - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, - _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', - _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; + } else if ( material.isMeshNormalMaterial ) { - var currentRenderList = null; - var currentRenderState = null; + refreshUniformsCommon( uniforms, material ); + refreshUniformsNormal( uniforms, material ); - // public properties + } else if ( material.isLineBasicMaterial ) { - this.domElement = _canvas; + refreshUniformsLine( uniforms, material ); - // Debug configuration container - this.debug = { + if ( material.isLineDashedMaterial ) { - /** - * Enables error checking and reporting when shader programs are being compiled - * @type {boolean} - */ - checkShaderErrors: true - }; + refreshUniformsDash( uniforms, material ); - // clearing + } - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + } else if ( material.isPointsMaterial ) { - // scene graph + refreshUniformsPoints( uniforms, material, pixelRatio, height ); - this.sortObjects = true; + } else if ( material.isSpriteMaterial ) { - // user-defined clipping + refreshUniformsSprites( uniforms, material ); - this.clippingPlanes = []; - this.localClippingEnabled = false; + } else if ( material.isShadowMaterial ) { - // physically based shading + uniforms.color.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + } else if ( material.isShaderMaterial ) { - // physical lights + material.uniformsNeedUpdate = false; // #15581 - this.physicallyCorrectLights = false; + } - // tone mapping + } - this.toneMapping = LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + function refreshUniformsCommon( uniforms, material, environment ) { - // morphs + uniforms.opacity.value = material.opacity; - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + if ( material.color ) { - // internal properties + uniforms.diffuse.value.copy( material.color ); - var _this = this, + } - _isContextLost = false, + if ( material.emissive ) { - // internal state cache + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - _framebuffer = null, + } - _currentActiveCubeFace = 0, - _currentActiveMipmapLevel = 0, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, + if ( material.map ) { - // geometry and program caching + uniforms.map.value = material.map; - _currentGeometryProgram = { - geometry: null, - program: null, - wireframe: false - }, + } - _currentCamera = null, - _currentArrayCamera = null, + if ( material.alphaMap ) { - _currentViewport = new Vector4(), - _currentScissor = new Vector4(), - _currentScissorTest = null, + uniforms.alphaMap.value = material.alphaMap; - // + } - _width = _canvas.width, - _height = _canvas.height, + if ( material.specularMap ) { - _pixelRatio = 1, + uniforms.specularMap.value = material.specularMap; - _viewport = new Vector4( 0, 0, _width, _height ), - _scissor = new Vector4( 0, 0, _width, _height ), - _scissorTest = false, + } - // frustum + var envMap = material.envMap || environment; - _frustum = new Frustum(), + if ( envMap ) { - // clipping + uniforms.envMap.value = envMap; - _clipping = new WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1; - // camera matrices cache + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; - _projScreenMatrix = new Matrix4(), + uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel; - _vector3 = new Vector3(); + } - function getTargetPixelRatio() { + if ( material.lightMap ) { - return _currentRenderTarget === null ? _pixelRatio : 1; + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; } - // initialize - - var _gl; + if ( material.aoMap ) { - try { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; - var contextAttributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer, - powerPreference: _powerPreference, - failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat, - xrCompatible: true - }; + } - // event listeners must be registered before WebGL context is created, see #12753 + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + var uvScaleMap; - _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); + if ( material.map ) { - if ( _gl === null ) { + uvScaleMap = material.map; - if ( _canvas.getContext( 'webgl' ) !== null ) { + } else if ( material.specularMap ) { - throw new Error( 'Error creating WebGL context with your selected attributes.' ); + uvScaleMap = material.specularMap; - } else { + } else if ( material.displacementMap ) { - throw new Error( 'Error creating WebGL context.' ); + uvScaleMap = material.displacementMap; - } + } else if ( material.normalMap ) { - } + uvScaleMap = material.normalMap; - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + } else if ( material.bumpMap ) { - if ( _gl.getShaderPrecisionFormat === undefined ) { + uvScaleMap = material.bumpMap; - _gl.getShaderPrecisionFormat = function () { + } else if ( material.roughnessMap ) { - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + uvScaleMap = material.roughnessMap; - }; + } else if ( material.metalnessMap ) { - } + uvScaleMap = material.metalnessMap; - } catch ( error ) { + } else if ( material.alphaMap ) { - console.error( 'THREE.WebGLRenderer: ' + error.message ); - throw error; + uvScaleMap = material.alphaMap; - } + } else if ( material.emissiveMap ) { - var extensions, capabilities, state, info; - var properties, textures, attributes, geometries, objects; - var programCache, renderLists, renderStates; + uvScaleMap = material.emissiveMap; - var background, morphtargets, bufferRenderer, indexedBufferRenderer; + } - var utils; + if ( uvScaleMap !== undefined ) { - function initGLContext() { + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { - extensions = new WebGLExtensions( _gl ); + uvScaleMap = uvScaleMap.texture; - capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + } - if ( capabilities.isWebGL2 === false ) { + if ( uvScaleMap.matrixAutoUpdate === true ) { - extensions.get( 'WEBGL_depth_texture' ); - extensions.get( 'OES_texture_float' ); - extensions.get( 'OES_texture_half_float' ); - extensions.get( 'OES_texture_half_float_linear' ); - extensions.get( 'OES_standard_derivatives' ); - extensions.get( 'OES_element_index_uint' ); - extensions.get( 'ANGLE_instanced_arrays' ); + uvScaleMap.updateMatrix(); } - extensions.get( 'OES_texture_float_linear' ); + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - utils = new WebGLUtils( _gl, extensions, capabilities ); + } - state = new WebGLState( _gl, extensions, capabilities ); - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map - info = new WebGLInfo( _gl ); - properties = new WebGLProperties(); - textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); - attributes = new WebGLAttributes( _gl ); - geometries = new WebGLGeometries( _gl, attributes, info ); - objects = new WebGLObjects( _gl, geometries, attributes, info ); - morphtargets = new WebGLMorphtargets( _gl ); - programCache = new WebGLPrograms( _this, extensions, capabilities ); - renderLists = new WebGLRenderLists(); - renderStates = new WebGLRenderStates(); + var uv2ScaleMap; - background = new WebGLBackground( _this, state, objects, _premultipliedAlpha ); + if ( material.aoMap ) { - bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); - indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); + uv2ScaleMap = material.aoMap; - info.programs = programCache.programs; + } else if ( material.lightMap ) { - _this.capabilities = capabilities; - _this.extensions = extensions; - _this.properties = properties; - _this.renderLists = renderLists; - _this.state = state; - _this.info = info; + uv2ScaleMap = material.lightMap; } - initGLContext(); + if ( uv2ScaleMap !== undefined ) { - // vr + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { - var vr = ( typeof navigator !== 'undefined' && 'xr' in navigator ) ? new WebXRManager( _this, _gl ) : new WebVRManager( _this ); + uv2ScaleMap = uv2ScaleMap.texture; - this.vr = vr; + } - // Multiview + if ( uv2ScaleMap.matrixAutoUpdate === true ) { - var multiview = new WebGLMultiview( _this, _gl ); + uv2ScaleMap.updateMatrix(); - // shadow map + } - var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); - this.shadowMap = shadowMap; + } - // API + } - this.getContext = function () { + function refreshUniformsLine( uniforms, material ) { - return _gl; + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; - }; + } - this.getContextAttributes = function () { + function refreshUniformsDash( uniforms, material ) { - return _gl.getContextAttributes(); + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - }; + } - this.forceContextLoss = function () { + function refreshUniformsPoints( uniforms, material, pixelRatio, height ) { - var extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) { extension.loseContext(); } + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; - }; + if ( material.map ) { - this.forceContextRestore = function () { + uniforms.map.value = material.map; - var extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) { extension.restoreContext(); } + } - }; + if ( material.alphaMap ) { - this.getPixelRatio = function () { + uniforms.alphaMap.value = material.alphaMap; - return _pixelRatio; + } - }; + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - this.setPixelRatio = function ( value ) { + var uvScaleMap; - if ( value === undefined ) { return; } + if ( material.map ) { - _pixelRatio = value; + uvScaleMap = material.map; - this.setSize( _width, _height, false ); + } else if ( material.alphaMap ) { - }; + uvScaleMap = material.alphaMap; - this.getSize = function ( target ) { + } - if ( target === undefined ) { + if ( uvScaleMap !== undefined ) { - console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' ); + if ( uvScaleMap.matrixAutoUpdate === true ) { - target = new Vector2(); + uvScaleMap.updateMatrix(); } - return target.set( _width, _height ); + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - }; + } - this.setSize = function ( width, height, updateStyle ) { + } - if ( vr.isPresenting() ) { + function refreshUniformsSprites( uniforms, material ) { - console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); - return; + uniforms.diffuse.value.copy( material.color ); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; - } + if ( material.map ) { - _width = width; - _height = height; + uniforms.map.value = material.map; - _canvas.width = Math.floor( width * _pixelRatio ); - _canvas.height = Math.floor( height * _pixelRatio ); + } - if ( updateStyle !== false ) { + if ( material.alphaMap ) { - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + uniforms.alphaMap.value = material.alphaMap; - } + } - this.setViewport( 0, 0, width, height ); + // uv repeat and offset setting priorities + // 1. color map + // 2. alpha map - }; + var uvScaleMap; - this.getDrawingBufferSize = function ( target ) { + if ( material.map ) { - if ( target === undefined ) { + uvScaleMap = material.map; - console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' ); + } else if ( material.alphaMap ) { - target = new Vector2(); + uvScaleMap = material.alphaMap; - } + } - return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); + if ( uvScaleMap !== undefined ) { - }; + if ( uvScaleMap.matrixAutoUpdate === true ) { - this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + uvScaleMap.updateMatrix(); - _width = width; - _height = height; + } - _pixelRatio = pixelRatio; + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - _canvas.width = Math.floor( width * pixelRatio ); - _canvas.height = Math.floor( height * pixelRatio ); + } - this.setViewport( 0, 0, width, height ); + } - }; + function refreshUniformsLambert( uniforms, material ) { - this.getCurrentViewport = function ( target ) { + if ( material.emissiveMap ) { - if ( target === undefined ) { + uniforms.emissiveMap.value = material.emissiveMap; - console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' ); + } - target = new Vector4(); + } - } + function refreshUniformsPhong( uniforms, material ) { - return target.copy( _currentViewport ); + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - }; + if ( material.emissiveMap ) { - this.getViewport = function ( target ) { + uniforms.emissiveMap.value = material.emissiveMap; - return target.copy( _viewport ); + } - }; + if ( material.bumpMap ) { - this.setViewport = function ( x, y, width, height ) { + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - if ( x.isVector4 ) { + } - _viewport.set( x.x, x.y, x.z, x.w ); + if ( material.normalMap ) { - } else { + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); - _viewport.set( x, y, width, height ); + } - } + if ( material.displacementMap ) { - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - }; + } - this.getScissor = function ( target ) { + } - return target.copy( _scissor ); + function refreshUniformsToon( uniforms, material ) { - }; + uniforms.specular.value.copy( material.specular ); + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - this.setScissor = function ( x, y, width, height ) { + if ( material.gradientMap ) { - if ( x.isVector4 ) { + uniforms.gradientMap.value = material.gradientMap; - _scissor.set( x.x, x.y, x.z, x.w ); + } - } else { + if ( material.emissiveMap ) { - _scissor.set( x, y, width, height ); + uniforms.emissiveMap.value = material.emissiveMap; - } + } - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + if ( material.bumpMap ) { - }; + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - this.getScissorTest = function () { + } - return _scissorTest; + if ( material.normalMap ) { - }; + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); - this.setScissorTest = function ( boolean ) { + } - state.setScissorTest( _scissorTest = boolean ); + if ( material.displacementMap ) { - }; + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - // Clearing + } - this.getClearColor = function () { + } - return background.getClearColor(); + function refreshUniformsStandard( uniforms, material, environment ) { - }; + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - this.setClearColor = function () { + if ( material.roughnessMap ) { - background.setClearColor.apply( background, arguments ); + uniforms.roughnessMap.value = material.roughnessMap; - }; + } - this.getClearAlpha = function () { + if ( material.metalnessMap ) { - return background.getClearAlpha(); + uniforms.metalnessMap.value = material.metalnessMap; - }; + } - this.setClearAlpha = function () { + if ( material.emissiveMap ) { - background.setClearAlpha.apply( background, arguments ); + uniforms.emissiveMap.value = material.emissiveMap; - }; + } + + if ( material.bumpMap ) { - this.clear = function ( color, depth, stencil ) { + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - var bits = 0; + } - if ( color === undefined || color ) { bits |= 16384; } - if ( depth === undefined || depth ) { bits |= 256; } - if ( stencil === undefined || stencil ) { bits |= 1024; } + if ( material.normalMap ) { - _gl.clear( bits ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); - }; + } - this.clearColor = function () { + if ( material.displacementMap ) { - this.clear( true, false, false ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - }; + } - this.clearDepth = function () { + if ( material.envMap || environment ) { - this.clear( false, true, false ); + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - }; + } - this.clearStencil = function () { + } - this.clear( false, false, true ); + function refreshUniformsPhysical( uniforms, material, environment ) { - }; + refreshUniformsStandard( uniforms, material, environment ); - // + uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common - this.dispose = function () { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if ( material.sheen ) uniforms.sheen.value.copy( material.sheen ); - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); - _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); + if ( material.clearcoatMap ) { - renderLists.dispose(); - renderStates.dispose(); - properties.dispose(); - objects.dispose(); + uniforms.clearcoatMap.value = material.clearcoatMap; - vr.dispose(); + } - animation.stop(); + if ( material.clearcoatRoughnessMap ) { - }; + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + + } - // Events + if ( material.clearcoatNormalMap ) { - function onContextLost( event ) { + uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; - event.preventDefault(); + if ( material.side === BackSide ) { - console.log( 'THREE.WebGLRenderer: Context Lost.' ); + uniforms.clearcoatNormalScale.value.negate(); - _isContextLost = true; + } } - function onContextRestore( /* event */ ) { + uniforms.transparency.value = material.transparency; + + } - console.log( 'THREE.WebGLRenderer: Context Restored.' ); + function refreshUniformsMatcap( uniforms, material ) { - _isContextLost = false; + if ( material.matcap ) { - initGLContext(); + uniforms.matcap.value = material.matcap; } - function onMaterialDispose( event ) { + if ( material.bumpMap ) { + + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; - var material = event.target; + } - material.removeEventListener( 'dispose', onMaterialDispose ); + if ( material.normalMap ) { - deallocateMaterial( material ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); } - // Buffer deallocation + if ( material.displacementMap ) { - function deallocateMaterial( material ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - releaseMaterialProgramReference( material ); + } - properties.remove( material ); + } - } + function refreshUniformsDepth( uniforms, material ) { + if ( material.displacementMap ) { - function releaseMaterialProgramReference( material ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - var programInfo = properties.get( material ).program; + } - material.program = undefined; + } - if ( programInfo !== undefined ) { + function refreshUniformsDistance( uniforms, material ) { - programCache.releaseProgram( programInfo ); + if ( material.displacementMap ) { - } + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; } - // Buffer rendering + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; - function renderObjectImmediate( object, program ) { + } - object.render( function ( object ) { + function refreshUniformsNormal( uniforms, material ) { - _this.renderBufferImmediate( object, program ); + if ( material.bumpMap ) { - } ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; + if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1; } - this.renderBufferImmediate = function ( object, program ) { + if ( material.normalMap ) { - state.initAttributes(); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); + if ( material.side === BackSide ) uniforms.normalScale.value.negate(); - var buffers = properties.get( object ); - - if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); } - if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); } - if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); } - if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); } + } - var programAttributes = program.getAttributes(); + if ( material.displacementMap ) { - if ( object.hasPositions ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - _gl.bindBuffer( 34962, buffers.position ); - _gl.bufferData( 34962, object.positionArray, 35048 ); + } - state.enableAttribute( programAttributes.position ); - _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 ); + } - } + return { + refreshFogUniforms: refreshFogUniforms, + refreshMaterialUniforms: refreshMaterialUniforms + }; - if ( object.hasNormals ) { +} - _gl.bindBuffer( 34962, buffers.normal ); - _gl.bufferData( 34962, object.normalArray, 35048 ); +/** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author tschw + */ - state.enableAttribute( programAttributes.normal ); - _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 ); +function WebGLRenderer( parameters ) { - } + parameters = parameters || {}; - if ( object.hasUvs ) { + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - _gl.bindBuffer( 34962, buffers.uv ); - _gl.bufferData( 34962, object.uvArray, 35048 ); + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', + _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; - state.enableAttribute( programAttributes.uv ); - _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 ); + var currentRenderList = null; + var currentRenderState = null; - } + // public properties - if ( object.hasColors ) { + this.domElement = _canvas; - _gl.bindBuffer( 34962, buffers.color ); - _gl.bufferData( 34962, object.colorArray, 35048 ); + // Debug configuration container + this.debug = { - state.enableAttribute( programAttributes.color ); - _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 ); + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true + }; - } + // clearing - state.disableUnusedAttributes(); + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - _gl.drawArrays( 4, 0, object.count ); + // scene graph - object.count = 0; + this.sortObjects = true; - }; + // user-defined clipping - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + this.clippingPlanes = []; + this.localClippingEnabled = false; - var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); + // physically based shading - state.setMaterial( material, frontFaceCW ); + this.gammaFactor = 2.0; // for backwards compatibility + this.outputEncoding = LinearEncoding; - var program = setProgram( camera, fog, material, object ); + // physical lights - var updateBuffers = false; + this.physicallyCorrectLights = false; - if ( _currentGeometryProgram.geometry !== geometry.id || - _currentGeometryProgram.program !== program.id || - _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) { + // tone mapping - _currentGeometryProgram.geometry = geometry.id; - _currentGeometryProgram.program = program.id; - _currentGeometryProgram.wireframe = material.wireframe === true; - updateBuffers = true; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - } + // morphs - if ( object.morphTargetInfluences ) { + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - morphtargets.update( object, geometry, material, program ); + // internal properties - updateBuffers = true; + var _this = this, - } + _isContextLost = false, - // + // internal state cache - var index = geometry.index; - var position = geometry.attributes.position; - var rangeFactor = 1; + _framebuffer = null, - if ( material.wireframe === true ) { + _currentActiveCubeFace = 0, + _currentActiveMipmapLevel = 0, + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, - index = geometries.getWireframeAttribute( geometry ); - rangeFactor = 2; + // geometry and program caching - } + _currentGeometryProgram = { + geometry: null, + program: null, + wireframe: false + }, - var attribute; - var renderer = bufferRenderer; + _currentCamera = null, + _currentArrayCamera = null, - if ( index !== null ) { + _currentViewport = new Vector4(), + _currentScissor = new Vector4(), + _currentScissorTest = null, - attribute = attributes.get( index ); + // - renderer = indexedBufferRenderer; - renderer.setIndex( attribute ); + _width = _canvas.width, + _height = _canvas.height, - } + _pixelRatio = 1, + _opaqueSort = null, + _transparentSort = null, - if ( updateBuffers ) { + _viewport = new Vector4( 0, 0, _width, _height ), + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - setupVertexAttributes( object, geometry, material, program ); + // frustum - if ( index !== null ) { + _frustum = new Frustum(), - _gl.bindBuffer( 34963, attribute.buffer ); + // clipping - } + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - } + // camera matrices cache - // + _projScreenMatrix = new Matrix4(), - var dataCount = Infinity; + _vector3 = new Vector3(); - if ( index !== null ) { + function getTargetPixelRatio() { - dataCount = index.count; + return _currentRenderTarget === null ? _pixelRatio : 1; - } else if ( position !== undefined ) { + } - dataCount = position.count; + // initialize - } + var _gl; - var rangeStart = geometry.drawRange.start * rangeFactor; - var rangeCount = geometry.drawRange.count * rangeFactor; + try { - var groupStart = group !== null ? group.start * rangeFactor : 0; - var groupCount = group !== null ? group.count * rangeFactor : Infinity; + var contextAttributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference, + failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat + }; - var drawStart = Math.max( rangeStart, groupStart ); - var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + // event listeners must be registered before WebGL context is created, see #12753 - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); - if ( drawCount === 0 ) { return; } + _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); - // + if ( _gl === null ) { - if ( object.isMesh ) { + if ( _canvas.getContext( 'webgl' ) !== null ) { - if ( material.wireframe === true ) { + throw new Error( 'Error creating WebGL context with your selected attributes.' ); - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( 1 ); + } else { - } else { + throw new Error( 'Error creating WebGL context.' ); - switch ( object.drawMode ) { + } - case TrianglesDrawMode: - renderer.setMode( 4 ); - break; + } - case TriangleStripDrawMode: - renderer.setMode( 5 ); - break; + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - case TriangleFanDrawMode: - renderer.setMode( 6 ); - break; + if ( _gl.getShaderPrecisionFormat === undefined ) { - } + _gl.getShaderPrecisionFormat = function () { - } + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - } else if ( object.isLine ) { + }; - var lineWidth = material.linewidth; + } - if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material + } catch ( error ) { - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + console.error( 'THREE.WebGLRenderer: ' + error.message ); + throw error; - if ( object.isLineSegments ) { + } - renderer.setMode( 1 ); + var extensions, capabilities, state, info; + var properties, textures, attributes, geometries, objects; + var programCache, materials, renderLists, renderStates; - } else if ( object.isLineLoop ) { + var background, morphtargets, bufferRenderer, indexedBufferRenderer; - renderer.setMode( 2 ); + var utils; - } else { + function initGLContext() { - renderer.setMode( 3 ); + extensions = new WebGLExtensions( _gl ); - } + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - } else if ( object.isPoints ) { + if ( capabilities.isWebGL2 === false ) { - renderer.setMode( 0 ); + extensions.get( 'WEBGL_depth_texture' ); + extensions.get( 'OES_texture_float' ); + extensions.get( 'OES_texture_half_float' ); + extensions.get( 'OES_texture_half_float_linear' ); + extensions.get( 'OES_standard_derivatives' ); + extensions.get( 'OES_element_index_uint' ); + extensions.get( 'ANGLE_instanced_arrays' ); - } else if ( object.isSprite ) { + } - renderer.setMode( 4 ); + extensions.get( 'OES_texture_float_linear' ); - } + utils = new WebGLUtils( _gl, extensions, capabilities ); - if ( object.isInstancedMesh ) { + state = new WebGLState( _gl, extensions, capabilities ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - renderer.renderInstances( geometry, drawStart, drawCount, object.count ); + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + attributes = new WebGLAttributes( _gl, capabilities ); + geometries = new WebGLGeometries( _gl, attributes, info ); + objects = new WebGLObjects( _gl, geometries, attributes, info ); + morphtargets = new WebGLMorphtargets( _gl ); + programCache = new WebGLPrograms( _this, extensions, capabilities ); + materials = new WebGLMaterials( properties ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates(); - } else if ( geometry.isInstancedBufferGeometry ) { + background = new WebGLBackground( _this, state, objects, _premultipliedAlpha ); - renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount ); + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); - } else { + info.programs = programCache.programs; - renderer.render( drawStart, drawCount ); + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.state = state; + _this.info = info; - } + } - }; + initGLContext(); - function setupVertexAttributes( object, geometry, material, program ) { + // xr - if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { + var xr = new WebXRManager( _this, _gl ); - if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { return; } + this.xr = xr; - } + // shadow map - state.initAttributes(); + var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); - var geometryAttributes = geometry.attributes; + this.shadowMap = shadowMap; - var programAttributes = program.getAttributes(); + // API - var materialDefaultAttributeValues = material.defaultAttributeValues; + this.getContext = function () { - for ( var name in programAttributes ) { + return _gl; - var programAttribute = programAttributes[ name ]; + }; - if ( programAttribute >= 0 ) { + this.getContextAttributes = function () { - var geometryAttribute = geometryAttributes[ name ]; + return _gl.getContextAttributes(); - if ( geometryAttribute !== undefined ) { + }; - var normalized = geometryAttribute.normalized; - var size = geometryAttribute.itemSize; + this.forceContextLoss = function () { - var attribute = attributes.get( geometryAttribute ); + var extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); - // TODO Attribute may not be available on context restore + }; - if ( attribute === undefined ) { continue; } + this.forceContextRestore = function () { - var buffer = attribute.buffer; - var type = attribute.type; - var bytesPerElement = attribute.bytesPerElement; + var extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); - if ( geometryAttribute.isInterleavedBufferAttribute ) { + }; - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + this.getPixelRatio = function () { - if ( data && data.isInstancedInterleavedBuffer ) { + return _pixelRatio; - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); + }; - if ( geometry.maxInstancedCount === undefined ) { + this.setPixelRatio = function ( value ) { - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + if ( value === undefined ) return; - } + _pixelRatio = value; - } else { + this.setSize( _width, _height, false ); - state.enableAttribute( programAttribute ); + }; - } + this.getSize = function ( target ) { - _gl.bindBuffer( 34962, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); + if ( target === undefined ) { - } else { + console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' ); - if ( geometryAttribute.isInstancedBufferAttribute ) { + target = new Vector2(); - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); + } - if ( geometry.maxInstancedCount === undefined ) { + return target.set( _width, _height ); - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + }; - } + this.setSize = function ( width, height, updateStyle ) { - } else { + if ( xr.isPresenting ) { - state.enableAttribute( programAttribute ); + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; - } + } - _gl.bindBuffer( 34962, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); + _width = width; + _height = height; - } + _canvas.width = Math.floor( width * _pixelRatio ); + _canvas.height = Math.floor( height * _pixelRatio ); - } else if ( name === 'instanceMatrix' ) { + if ( updateStyle !== false ) { - var attribute = attributes.get( object.instanceMatrix ); + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; - // TODO Attribute may not be available on context restore + } - if ( attribute === undefined ) { continue; } + this.setViewport( 0, 0, width, height ); - var buffer = attribute.buffer; - var type = attribute.type; + }; - state.enableAttributeAndDivisor( programAttribute + 0, 1 ); - state.enableAttributeAndDivisor( programAttribute + 1, 1 ); - state.enableAttributeAndDivisor( programAttribute + 2, 1 ); - state.enableAttributeAndDivisor( programAttribute + 3, 1 ); + this.getDrawingBufferSize = function ( target ) { - _gl.bindBuffer( 34962, buffer ); + if ( target === undefined ) { - _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 ); - _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 ); - _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 ); - _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 ); + console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' ); - } else if ( materialDefaultAttributeValues !== undefined ) { + target = new Vector2(); - var value = materialDefaultAttributeValues[ name ]; + } - if ( value !== undefined ) { + return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); - switch ( value.length ) { + }; - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + _width = width; + _height = height; - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + _pixelRatio = pixelRatio; - default: - _gl.vertexAttrib1fv( programAttribute, value ); + _canvas.width = Math.floor( width * pixelRatio ); + _canvas.height = Math.floor( height * pixelRatio ); - } + this.setViewport( 0, 0, width, height ); - } + }; - } + this.getCurrentViewport = function ( target ) { - } + if ( target === undefined ) { - } + console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' ); - state.disableUnusedAttributes(); + target = new Vector4(); } - // Compile + return target.copy( _currentViewport ); - this.compile = function ( scene, camera ) { + }; - currentRenderState = renderStates.get( scene, camera ); - currentRenderState.init(); + this.getViewport = function ( target ) { - scene.traverse( function ( object ) { + return target.copy( _viewport ); - if ( object.isLight ) { + }; - currentRenderState.pushLight( object ); + this.setViewport = function ( x, y, width, height ) { - if ( object.castShadow ) { + if ( x.isVector4 ) { - currentRenderState.pushShadow( object ); + _viewport.set( x.x, x.y, x.z, x.w ); - } + } else { - } + _viewport.set( x, y, width, height ); - } ); + } - currentRenderState.setupLights( camera ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); - scene.traverse( function ( object ) { + }; - if ( object.material ) { + this.getScissor = function ( target ) { - if ( Array.isArray( object.material ) ) { + return target.copy( _scissor ); - for ( var i = 0; i < object.material.length; i ++ ) { + }; - initMaterial( object.material[ i ], scene.fog, object ); + this.setScissor = function ( x, y, width, height ) { - } + if ( x.isVector4 ) { - } else { + _scissor.set( x.x, x.y, x.z, x.w ); - initMaterial( object.material, scene.fog, object ); + } else { - } + _scissor.set( x, y, width, height ); - } + } - } ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); - }; + }; - // Animation Loop + this.getScissorTest = function () { - var onAnimationFrameCallback = null; + return _scissorTest; - function onAnimationFrame( time ) { + }; - if ( vr.isPresenting() ) { return; } - if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); } + this.setScissorTest = function ( boolean ) { - } + state.setScissorTest( _scissorTest = boolean ); - var animation = new WebGLAnimation(); - animation.setAnimationLoop( onAnimationFrame ); + }; - if ( typeof window !== 'undefined' ) { animation.setContext( window ); } + this.setOpaqueSort = function ( method ) { - this.setAnimationLoop = function ( callback ) { + _opaqueSort = method; - onAnimationFrameCallback = callback; - vr.setAnimationLoop( callback ); + }; - animation.start(); + this.setTransparentSort = function ( method ) { - }; + _transparentSort = method; - // Rendering + }; - this.render = function ( scene, camera ) { + // Clearing - var renderTarget, forceClear; + this.getClearColor = function () { - if ( arguments[ 2 ] !== undefined ) { + return background.getClearColor(); - console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' ); - renderTarget = arguments[ 2 ]; + }; - } + this.setClearColor = function () { - if ( arguments[ 3 ] !== undefined ) { + background.setClearColor.apply( background, arguments ); - console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' ); - forceClear = arguments[ 3 ]; + }; - } + this.getClearAlpha = function () { - if ( ! ( camera && camera.isCamera ) ) { + return background.getClearAlpha(); - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + }; - } + this.setClearAlpha = function () { - if ( _isContextLost ) { return; } + background.setClearAlpha.apply( background, arguments ); - // reset caching for this frame + }; - _currentGeometryProgram.geometry = null; - _currentGeometryProgram.program = null; - _currentGeometryProgram.wireframe = false; - _currentMaterialId = - 1; - _currentCamera = null; + this.clear = function ( color, depth, stencil ) { - // update scene graph + var bits = 0; - if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); } + if ( color === undefined || color ) bits |= 16384; + if ( depth === undefined || depth ) bits |= 256; + if ( stencil === undefined || stencil ) bits |= 1024; - // update camera matrices and frustum + _gl.clear( bits ); - if ( camera.parent === null ) { camera.updateMatrixWorld(); } + }; - if ( vr.enabled ) { + this.clearColor = function () { - camera = vr.getCamera( camera ); + this.clear( true, false, false ); - } + }; - // + this.clearDepth = function () { - currentRenderState = renderStates.get( scene, camera ); - currentRenderState.init(); + this.clear( false, true, false ); - scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); + }; - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + this.clearStencil = function () { - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + this.clear( false, false, true ); - currentRenderList = renderLists.get( scene, camera ); - currentRenderList.init(); + }; - projectObject( scene, camera, 0, _this.sortObjects ); + // - if ( _this.sortObjects === true ) { + this.dispose = function () { - currentRenderList.sort(); + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); - } + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + objects.dispose(); - // + xr.dispose(); + + animation.stop(); - if ( _clippingEnabled ) { _clipping.beginShadows(); } + }; - var shadowsArray = currentRenderState.state.shadowsArray; + // Events - shadowMap.render( shadowsArray, scene, camera ); + function onContextLost( event ) { - currentRenderState.setupLights( camera ); + event.preventDefault(); - if ( _clippingEnabled ) { _clipping.endShadows(); } + console.log( 'THREE.WebGLRenderer: Context Lost.' ); - // + _isContextLost = true; - if ( this.info.autoReset ) { this.info.reset(); } + } - if ( renderTarget !== undefined ) { + function onContextRestore( /* event */ ) { - this.setRenderTarget( renderTarget ); + console.log( 'THREE.WebGLRenderer: Context Restored.' ); - } + _isContextLost = false; - if ( vr.enabled && multiview.isAvailable() ) { + initGLContext(); - multiview.attachCamera( camera ); + } - } + function onMaterialDispose( event ) { - // + var material = event.target; - background.render( currentRenderList, scene, camera, forceClear ); + material.removeEventListener( 'dispose', onMaterialDispose ); - // render scene + deallocateMaterial( material ); - var opaqueObjects = currentRenderList.opaque; - var transparentObjects = currentRenderList.transparent; + } - if ( scene.overrideMaterial ) { + // Buffer deallocation - var overrideMaterial = scene.overrideMaterial; + function deallocateMaterial( material ) { - if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera, overrideMaterial ); } - if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera, overrideMaterial ); } + releaseMaterialProgramReference( material ); - } else { + properties.remove( material ); - // opaque pass (front-to-back order) + } - if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera ); } - // transparent pass (back-to-front order) + function releaseMaterialProgramReference( material ) { - if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera ); } + var programInfo = properties.get( material ).program; - } + material.program = undefined; - // + if ( programInfo !== undefined ) { - scene.onAfterRender( _this, scene, camera ); + programCache.releaseProgram( programInfo ); - // + } - if ( _currentRenderTarget !== null ) { + } - // Generate mipmap if we're using any kind of mipmap filtering + // Buffer rendering - textures.updateRenderTargetMipmap( _currentRenderTarget ); + function renderObjectImmediate( object, program ) { - // resolve multisample renderbuffers to a single-sample texture if necessary + object.render( function ( object ) { - textures.updateMultisampleRenderTarget( _currentRenderTarget ); + _this.renderBufferImmediate( object, program ); - } + } ); - // Ensure depth buffer writing is enabled so it can be cleared on next render + } - state.buffers.depth.setTest( true ); - state.buffers.depth.setMask( true ); - state.buffers.color.setMask( true ); + this.renderBufferImmediate = function ( object, program ) { - state.setPolygonOffset( false ); + state.initAttributes(); - if ( vr.enabled ) { + var buffers = properties.get( object ); - if ( multiview.isAvailable() ) { + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - multiview.detachCamera( camera ); + var programAttributes = program.getAttributes(); - } + if ( object.hasPositions ) { - vr.submitFrame(); + _gl.bindBuffer( 34962, buffers.position ); + _gl.bufferData( 34962, object.positionArray, 35048 ); - } + state.enableAttribute( programAttributes.position ); + _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 ); - // _gl.finish(); + } - currentRenderList = null; - currentRenderState = null; + if ( object.hasNormals ) { - }; + _gl.bindBuffer( 34962, buffers.normal ); + _gl.bufferData( 34962, object.normalArray, 35048 ); - function projectObject( object, camera, groupOrder, sortObjects ) { + state.enableAttribute( programAttributes.normal ); + _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 ); - if ( object.visible === false ) { return; } + } - var visible = object.layers.test( camera.layers ); + if ( object.hasUvs ) { - if ( visible ) { + _gl.bindBuffer( 34962, buffers.uv ); + _gl.bufferData( 34962, object.uvArray, 35048 ); - if ( object.isGroup ) { + state.enableAttribute( programAttributes.uv ); + _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 ); - groupOrder = object.renderOrder; + } - } else if ( object.isLOD ) { + if ( object.hasColors ) { - if ( object.autoUpdate === true ) { object.update( camera ); } + _gl.bindBuffer( 34962, buffers.color ); + _gl.bufferData( 34962, object.colorArray, 35048 ); - } else if ( object.isLight ) { + state.enableAttribute( programAttributes.color ); + _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 ); - currentRenderState.pushLight( object ); + } - if ( object.castShadow ) { + state.disableUnusedAttributes(); - currentRenderState.pushShadow( object ); + _gl.drawArrays( 4, 0, object.count ); - } + object.count = 0; - } else if ( object.isSprite ) { + }; - if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + var tempScene = new Scene(); - if ( sortObjects ) { + this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + if ( scene === null ) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null) - } + var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); - var geometry = objects.update( object ); - var material = object.material; + var program = setProgram( camera, scene, material, object ); - if ( material.visible ) { + state.setMaterial( material, frontFaceCW ); - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + var updateBuffers = false; - } + if ( _currentGeometryProgram.geometry !== geometry.id || + _currentGeometryProgram.program !== program.id || + _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) { - } + _currentGeometryProgram.geometry = geometry.id; + _currentGeometryProgram.program = program.id; + _currentGeometryProgram.wireframe = material.wireframe === true; + updateBuffers = true; - } else if ( object.isImmediateRenderObject ) { + } - if ( sortObjects ) { + if ( material.morphTargets || material.morphNormals ) { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + morphtargets.update( object, geometry, material, program ); - } + updateBuffers = true; - currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); + } - } else if ( object.isMesh || object.isLine || object.isPoints ) { + if ( object.isInstancedMesh === true ) { - if ( object.isSkinnedMesh ) { + updateBuffers = true; - // update skeleton only once in a frame + } - if ( object.skeleton.frame !== info.render.frame ) { + // - object.skeleton.update(); - object.skeleton.frame = info.render.frame; + var index = geometry.index; + var position = geometry.attributes.position; - } + // - } + if ( index === null ) { - if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + if ( position === undefined || position.count === 0 ) return; - if ( sortObjects ) { + } else if ( index.count === 0 ) { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + return; - } + } - var geometry = objects.update( object ); - var material = object.material; + // - if ( Array.isArray( material ) ) { + var rangeFactor = 1; - var groups = geometry.groups; + if ( material.wireframe === true ) { - for ( var i = 0, l = groups.length; i < l; i ++ ) { + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; - var group = groups[ i ]; - var groupMaterial = material[ group.materialIndex ]; + } - if ( groupMaterial && groupMaterial.visible ) { + var attribute; + var renderer = bufferRenderer; - currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); + if ( index !== null ) { - } + attribute = attributes.get( index ); - } + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); - } else if ( material.visible ) { + } - currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); + if ( updateBuffers ) { - } + setupVertexAttributes( object, geometry, material, program ); - } + if ( index !== null ) { - } + _gl.bindBuffer( 34963, attribute.buffer ); } - var children = object.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + // - projectObject( children[ i ], camera, groupOrder, sortObjects ); + var dataCount = ( index !== null ) ? index.count : position.count; - } + var rangeStart = geometry.drawRange.start * rangeFactor; + var rangeCount = geometry.drawRange.count * rangeFactor; - } + var groupStart = group !== null ? group.start * rangeFactor : 0; + var groupCount = group !== null ? group.count * rangeFactor : Infinity; - function renderObjects( renderList, scene, camera, overrideMaterial ) { + var drawStart = Math.max( rangeStart, groupStart ); + var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - var renderItem = renderList[ i ]; + if ( drawCount === 0 ) return; - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + // - if ( camera.isArrayCamera ) { + if ( object.isMesh ) { - _currentArrayCamera = camera; + if ( material.wireframe === true ) { - if ( vr.enabled && multiview.isAvailable() ) { + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( 1 ); - renderObject( object, scene, camera, geometry, material, group ); + } else { - } else { + renderer.setMode( 4 ); - var cameras = camera.cameras; + } - for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { + } else if ( object.isLine ) { - var camera2 = cameras[ j ]; + var lineWidth = material.linewidth; - if ( object.layers.test( camera2.layers ) ) { + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - state.viewport( _currentViewport.copy( camera2.viewport ) ); + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - currentRenderState.setupLights( camera2 ); + if ( object.isLineSegments ) { - renderObject( object, scene, camera2, geometry, material, group ); + renderer.setMode( 1 ); - } + } else if ( object.isLineLoop ) { - } + renderer.setMode( 2 ); - } + } else { - } else { + renderer.setMode( 3 ); + + } - _currentArrayCamera = null; + } else if ( object.isPoints ) { - renderObject( object, scene, camera, geometry, material, group ); + renderer.setMode( 0 ); - } + } else if ( object.isSprite ) { - } + renderer.setMode( 4 ); } - function renderObject( object, scene, camera, geometry, material, group ) { + if ( object.isInstancedMesh ) { - object.onBeforeRender( _this, scene, camera, geometry, material, group ); - currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); + renderer.renderInstances( geometry, drawStart, drawCount, object.count ); - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + } else if ( geometry.isInstancedBufferGeometry ) { - if ( object.isImmediateRenderObject ) { + var instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount ); - state.setMaterial( material ); + renderer.renderInstances( geometry, drawStart, drawCount, instanceCount ); - var program = setProgram( camera, scene.fog, material, object ); + } else { - _currentGeometryProgram.geometry = null; - _currentGeometryProgram.program = null; - _currentGeometryProgram.wireframe = false; + renderer.render( drawStart, drawCount ); - renderObjectImmediate( object, program ); + } - } else { + }; - _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group ); + function setupVertexAttributes( object, geometry, material, program ) { - } + if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { - object.onAfterRender( _this, scene, camera, geometry, material, group ); - currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return; } - function initMaterial( material, fog, object ) { + state.initAttributes(); - var materialProperties = properties.get( material ); + var geometryAttributes = geometry.attributes; - var lights = currentRenderState.state.lights; - var shadowsArray = currentRenderState.state.shadowsArray; + var programAttributes = program.getAttributes(); - var lightsStateVersion = lights.state.version; + var materialDefaultAttributeValues = material.defaultAttributeValues; - var parameters = programCache.getParameters( - material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object ); + for ( var name in programAttributes ) { - var programCacheKey = programCache.getProgramCacheKey( material, parameters ); + var programAttribute = programAttributes[ name ]; - var program = materialProperties.program; - var programChange = true; + if ( programAttribute >= 0 ) { - if ( program === undefined ) { + var geometryAttribute = geometryAttributes[ name ]; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + if ( geometryAttribute !== undefined ) { - } else if ( program.cacheKey !== programCacheKey ) { + var normalized = geometryAttribute.normalized; + var size = geometryAttribute.itemSize; - // changed glsl or parameters - releaseMaterialProgramReference( material ); + var attribute = attributes.get( geometryAttribute ); - } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) { + // TODO Attribute may not be available on context restore - materialProperties.lightsStateVersion = lightsStateVersion; + if ( attribute === undefined ) continue; - programChange = false; + var buffer = attribute.buffer; + var type = attribute.type; + var bytesPerElement = attribute.bytesPerElement; - } else if ( parameters.shaderID !== undefined ) { - - // same glsl and uniform list - return; - - } else { + if ( geometryAttribute.isInterleavedBufferAttribute ) { - // only rebuild uniform list - programChange = false; + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - } + if ( data && data.isInstancedInterleavedBuffer ) { - if ( programChange ) { + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); - if ( parameters.shaderID ) { + if ( geometry._maxInstanceCount === undefined ) { - var shader = ShaderLib[ parameters.shaderID ]; + geometry._maxInstanceCount = data.meshPerAttribute * data.count; - materialProperties.shader = { - name: material.type, - uniforms: cloneUniforms( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + } - } else { + } else { - materialProperties.shader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + state.enableAttribute( programAttribute ); - } + } - material.onBeforeCompile( materialProperties.shader, _this ); + _gl.bindBuffer( 34962, buffer ); + state.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); - // Computing cache key again as onBeforeCompile may have changed the shaders - programCacheKey = programCache.getProgramCacheKey( material, parameters ); + } else { - program = programCache.acquireProgram( material, materialProperties.shader, parameters, programCacheKey ); + if ( geometryAttribute.isInstancedBufferAttribute ) { - materialProperties.program = program; - material.program = program; + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); - } + if ( geometry._maxInstanceCount === undefined ) { - var programAttributes = program.getAttributes(); + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - if ( material.morphTargets ) { + } - material.numSupportedMorphTargets = 0; + } else { - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + state.enableAttribute( programAttribute ); - if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { + } - material.numSupportedMorphTargets ++; + _gl.bindBuffer( 34962, buffer ); + state.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); } - } - - } - - if ( material.morphNormals ) { + } else if ( name === 'instanceMatrix' ) { - material.numSupportedMorphNormals = 0; + var attribute = attributes.get( object.instanceMatrix ); - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { + // TODO Attribute may not be available on context restore - if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { + if ( attribute === undefined ) continue; - material.numSupportedMorphNormals ++; + var buffer = attribute.buffer; + var type = attribute.type; - } + state.enableAttributeAndDivisor( programAttribute + 0, 1 ); + state.enableAttributeAndDivisor( programAttribute + 1, 1 ); + state.enableAttributeAndDivisor( programAttribute + 2, 1 ); + state.enableAttributeAndDivisor( programAttribute + 3, 1 ); - } + _gl.bindBuffer( 34962, buffer ); - } + _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 ); + _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 ); + _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 ); + _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 ); - var uniforms = materialProperties.shader.uniforms; + } else if ( materialDefaultAttributeValues !== undefined ) { - if ( ! material.isShaderMaterial && - ! material.isRawShaderMaterial || - material.clipping === true ) { + var value = materialDefaultAttributeValues[ name ]; - materialProperties.numClippingPlanes = _clipping.numPlanes; - materialProperties.numIntersection = _clipping.numIntersection; - uniforms.clippingPlanes = _clipping.uniform; + if ( value !== undefined ) { - } + switch ( value.length ) { - materialProperties.fog = fog; + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - // store the light setup it was created for + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - materialProperties.needsLights = materialNeedsLights( material ); - materialProperties.lightsStateVersion = lightsStateVersion; + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - if ( materialProperties.needsLights ) { + default: + _gl.vertexAttrib1fv( programAttribute, value ); - // wire up the material to this renderer's lighting state + } - uniforms.ambientLightColor.value = lights.state.ambient; - uniforms.lightProbe.value = lights.state.probe; - uniforms.directionalLights.value = lights.state.directional; - uniforms.spotLights.value = lights.state.spot; - uniforms.rectAreaLights.value = lights.state.rectArea; - uniforms.pointLights.value = lights.state.point; - uniforms.hemisphereLights.value = lights.state.hemi; + } - uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; - uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; - uniforms.spotShadowMap.value = lights.state.spotShadowMap; - uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; - uniforms.pointShadowMap.value = lights.state.pointShadowMap; - uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; - // TODO (abelnation): add area lights shadow info to uniforms + } } - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); + } - materialProperties.uniformsList = uniformsList; + state.disableUnusedAttributes(); - } + } - function setProgram( camera, fog, material, object ) { + // Compile - textures.resetTextureUnits(); + this.compile = function ( scene, camera ) { - var materialProperties = properties.get( material ); - var lights = currentRenderState.state.lights; + currentRenderState = renderStates.get( scene, camera ); + currentRenderState.init(); - if ( _clippingEnabled ) { + scene.traverse( function ( object ) { - if ( _localClippingEnabled || camera !== _currentCamera ) { + if ( object.isLight ) { - var useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + currentRenderState.pushLight( object ); - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - _clipping.setState( - material.clippingPlanes, material.clipIntersection, material.clipShadows, - camera, materialProperties, useCache ); + if ( object.castShadow ) { + + currentRenderState.pushShadow( object ); } } - if ( material.needsUpdate === false ) { - - if ( materialProperties.program === undefined ) { - - material.needsUpdate = true; + } ); - } else if ( material.fog && materialProperties.fog !== fog ) { + currentRenderState.setupLights( camera ); - material.needsUpdate = true; + const compiled = {}; - } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + scene.traverse( function ( object ) { - material.needsUpdate = true; + let material = object.material; - } else if ( materialProperties.numClippingPlanes !== undefined && - ( materialProperties.numClippingPlanes !== _clipping.numPlanes || - materialProperties.numIntersection !== _clipping.numIntersection ) ) { + if ( material ) { - material.needsUpdate = true; + if ( Array.isArray( material ) ) { - } + for ( let i = 0; i < material.length; i ++ ) { - } + let material2 = material[ i ]; - if ( material.needsUpdate ) { + if ( material2.uuid in compiled === false ) { - initMaterial( material, fog, object ); - material.needsUpdate = false; + initMaterial( material2, scene, object ); + compiled[ material2.uuid ] = true; - } + } - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + } - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.shader.uniforms; + } else if ( material.uuid in compiled === false ) { - if ( state.useProgram( program.program ) ) { + initMaterial( material, scene, object ); + compiled[ material.uuid ] = true; - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + } } - if ( material.id !== _currentMaterialId ) { - - _currentMaterialId = material.id; + } ); - refreshMaterial = true; + }; - } + // Animation Loop - if ( refreshProgram || _currentCamera !== camera ) { + var onAnimationFrameCallback = null; - if ( program.numMultiviewViews > 0 ) { + function onAnimationFrame( time ) { - multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms ); + if ( xr.isPresenting ) return; + if ( onAnimationFrameCallback ) onAnimationFrameCallback( time ); - } else { + } - p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + var animation = new WebGLAnimation(); + animation.setAnimationLoop( onAnimationFrame ); - } + if ( typeof window !== 'undefined' ) animation.setContext( window ); - if ( capabilities.logarithmicDepthBuffer ) { + this.setAnimationLoop = function ( callback ) { - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + onAnimationFrameCallback = callback; + xr.setAnimationLoop( callback ); - } + animation.start(); - if ( _currentCamera !== camera ) { + }; - _currentCamera = camera; + // Rendering - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + this.render = function ( scene, camera ) { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + var renderTarget, forceClear; - } + if ( arguments[ 2 ] !== undefined ) { - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' ); + renderTarget = arguments[ 2 ]; - if ( material.isShaderMaterial || - material.isMeshPhongMaterial || - material.isMeshStandardMaterial || - material.envMap ) { + } - var uCamPos = p_uniforms.map.cameraPosition; + if ( arguments[ 3 ] !== undefined ) { - if ( uCamPos !== undefined ) { + console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' ); + forceClear = arguments[ 3 ]; - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + } - } + if ( ! ( camera && camera.isCamera ) ) { - } + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - if ( material.isMeshPhongMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial ) { + } - p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); + if ( _isContextLost ) return; - } + // reset caching for this frame - if ( material.isMeshPhongMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial || - material.skinning ) { + _currentGeometryProgram.geometry = null; + _currentGeometryProgram.program = null; + _currentGeometryProgram.wireframe = false; + _currentMaterialId = - 1; + _currentCamera = null; - if ( program.numMultiviewViews > 0 ) { + // update scene graph - multiview.updateCameraViewMatricesUniform( camera, p_uniforms ); + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - } else { + // update camera matrices and frustum - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + if ( camera.parent === null ) camera.updateMatrixWorld(); - } + if ( xr.enabled && xr.isPresenting ) { - } + camera = xr.getCamera( camera ); - } + } - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen + // + scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); - if ( material.skinning ) { + currentRenderState = renderStates.get( scene, camera ); + currentRenderState.init(); - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromProjectionMatrix( _projScreenMatrix ); - var skeleton = object.skeleton; + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - if ( skeleton ) { + currentRenderList = renderLists.get( scene, camera ); + currentRenderList.init(); - var bones = skeleton.bones; + projectObject( scene, camera, 0, _this.sortObjects ); - if ( capabilities.floatVertexTextures ) { + currentRenderList.finish(); - if ( skeleton.boneTexture === undefined ) { + if ( _this.sortObjects === true ) { - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + currentRenderList.sort( _opaqueSort, _transparentSort ); + } - var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix - size = _Math.ceilPowerOfTwo( size ); - size = Math.max( size, 4 ); + // - var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel - boneMatrices.set( skeleton.boneMatrices ); // copy current values + if ( _clippingEnabled ) _clipping.beginShadows(); - var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + var shadowsArray = currentRenderState.state.shadowsArray; - skeleton.boneMatrices = boneMatrices; - skeleton.boneTexture = boneTexture; - skeleton.boneTextureSize = size; + shadowMap.render( shadowsArray, scene, camera ); - } + currentRenderState.setupLights( camera ); - p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); - p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + if ( _clippingEnabled ) _clipping.endShadows(); - } else { + // - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + if ( this.info.autoReset ) this.info.reset(); - } + if ( renderTarget !== undefined ) { - } + this.setRenderTarget( renderTarget ); - } + } - if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { + // - materialProperties.receiveShadow = object.receiveShadow; - p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); + background.render( currentRenderList, scene, camera, forceClear ); - } + // render scene - if ( refreshMaterial ) { + var opaqueObjects = currentRenderList.opaque; + var transparentObjects = currentRenderList.transparent; - p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); - p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); + if ( scene.overrideMaterial ) { - if ( materialProperties.needsLights ) { + var overrideMaterial = scene.overrideMaterial; - // the current material requires lighting info + if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial ); + if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial ); - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + } else { - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + // opaque pass (front-to-back order) - } + if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera ); - // refresh uniforms common to several materials + // transparent pass (back-to-front order) - if ( fog && material.fog ) { + if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera ); - refreshUniformsFog( m_uniforms, fog ); + } - } + // - if ( material.isMeshBasicMaterial ) { + scene.onAfterRender( _this, scene, camera ); - refreshUniformsCommon( m_uniforms, material ); + // - } else if ( material.isMeshLambertMaterial ) { + if ( _currentRenderTarget !== null ) { - refreshUniformsCommon( m_uniforms, material ); - refreshUniformsLambert( m_uniforms, material ); + // Generate mipmap if we're using any kind of mipmap filtering - } else if ( material.isMeshPhongMaterial ) { + textures.updateRenderTargetMipmap( _currentRenderTarget ); - refreshUniformsCommon( m_uniforms, material ); + // resolve multisample renderbuffers to a single-sample texture if necessary - if ( material.isMeshToonMaterial ) { + textures.updateMultisampleRenderTarget( _currentRenderTarget ); - refreshUniformsToon( m_uniforms, material ); + } - } else { + // Ensure depth buffer writing is enabled so it can be cleared on next render - refreshUniformsPhong( m_uniforms, material ); + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); - } + state.setPolygonOffset( false ); - } else if ( material.isMeshStandardMaterial ) { + // _gl.finish(); - refreshUniformsCommon( m_uniforms, material ); + currentRenderList = null; + currentRenderState = null; - if ( material.isMeshPhysicalMaterial ) { + }; - refreshUniformsPhysical( m_uniforms, material ); + function projectObject( object, camera, groupOrder, sortObjects ) { - } else { + if ( object.visible === false ) return; - refreshUniformsStandard( m_uniforms, material ); + var visible = object.layers.test( camera.layers ); - } + if ( visible ) { - } else if ( material.isMeshMatcapMaterial ) { + if ( object.isGroup ) { - refreshUniformsCommon( m_uniforms, material ); + groupOrder = object.renderOrder; - refreshUniformsMatcap( m_uniforms, material ); + } else if ( object.isLOD ) { - } else if ( material.isMeshDepthMaterial ) { + if ( object.autoUpdate === true ) object.update( camera ); - refreshUniformsCommon( m_uniforms, material ); - refreshUniformsDepth( m_uniforms, material ); + } else if ( object.isLight ) { - } else if ( material.isMeshDistanceMaterial ) { + currentRenderState.pushLight( object ); - refreshUniformsCommon( m_uniforms, material ); - refreshUniformsDistance( m_uniforms, material ); + if ( object.castShadow ) { - } else if ( material.isMeshNormalMaterial ) { + currentRenderState.pushShadow( object ); - refreshUniformsCommon( m_uniforms, material ); - refreshUniformsNormal( m_uniforms, material ); + } - } else if ( material.isLineBasicMaterial ) { + } else if ( object.isSprite ) { - refreshUniformsLine( m_uniforms, material ); + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { - if ( material.isLineDashedMaterial ) { + if ( sortObjects ) { - refreshUniformsDash( m_uniforms, material ); + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); } - } else if ( material.isPointsMaterial ) { + var geometry = objects.update( object ); + var material = object.material; - refreshUniformsPoints( m_uniforms, material ); + if ( material.visible ) { - } else if ( material.isSpriteMaterial ) { + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); - refreshUniformsSprites( m_uniforms, material ); + } - } else if ( material.isShadowMaterial ) { + } - m_uniforms.color.value.copy( material.color ); - m_uniforms.opacity.value = material.opacity; + } else if ( object.isImmediateRenderObject ) { - } + if ( sortObjects ) { - // RectAreaLight Texture - // TODO (mrdoob): Find a nicer implementation + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; } - if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; } + } - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); - if ( material.isShaderMaterial ) { + } else if ( object.isMesh || object.isLine || object.isPoints ) { - material.uniformsNeedUpdate = false; // #15581 + if ( object.isSkinnedMesh ) { - } + // update skeleton only once in a frame - } + if ( object.skeleton.frame !== info.render.frame ) { - if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { + object.skeleton.update(); + object.skeleton.frame = info.render.frame; - WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); - material.uniformsNeedUpdate = false; + } - } + } - if ( material.isSpriteMaterial ) { + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { - p_uniforms.setValue( _gl, 'center', object.center ); + if ( sortObjects ) { - } + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - // common matrices + } - if ( program.numMultiviewViews > 0 ) { + var geometry = objects.update( object ); + var material = object.material; - multiview.updateObjectMatricesUniforms( object, camera, p_uniforms ); + if ( Array.isArray( material ) ) { - } else { + var groups = geometry.groups; - p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); - p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + for ( var i = 0, l = groups.length; i < l; i ++ ) { - } + var group = groups[ i ]; + var groupMaterial = material[ group.materialIndex ]; - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + if ( groupMaterial && groupMaterial.visible ) { - return program; + currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); - } + } - // Uniforms (refresh uniforms objects) + } - function refreshUniformsCommon( uniforms, material ) { + } else if ( material.visible ) { - uniforms.opacity.value = material.opacity; + currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); - if ( material.color ) { + } - uniforms.diffuse.value.copy( material.color ); + } } - if ( material.emissive ) { + } + + var children = object.children; - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + projectObject( children[ i ], camera, groupOrder, sortObjects ); - if ( material.map ) { + } - uniforms.map.value = material.map; + } - } + function renderObjects( renderList, scene, camera, overrideMaterial ) { - if ( material.alphaMap ) { + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - uniforms.alphaMap.value = material.alphaMap; + var renderItem = renderList[ i ]; - } + var object = renderItem.object; + var geometry = renderItem.geometry; + var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; + var group = renderItem.group; - if ( material.specularMap ) { + if ( camera.isArrayCamera ) { - uniforms.specularMap.value = material.specularMap; + _currentArrayCamera = camera; - } + var cameras = camera.cameras; - if ( material.envMap ) { + for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { - uniforms.envMap.value = material.envMap; + var camera2 = cameras[ j ]; - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1; + if ( object.layers.test( camera2.layers ) ) { - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + state.viewport( _currentViewport.copy( camera2.viewport ) ); - uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel; + currentRenderState.setupLights( camera2 ); - } + renderObject( object, scene, camera2, geometry, material, group ); - if ( material.lightMap ) { + } - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + } - } + } else { - if ( material.aoMap ) { + _currentArrayCamera = null; - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + renderObject( object, scene, camera, geometry, material, group ); } - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map - - var uvScaleMap; + } - if ( material.map ) { + } - uvScaleMap = material.map; + function renderObject( object, scene, camera, geometry, material, group ) { - } else if ( material.specularMap ) { + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); - uvScaleMap = material.specularMap; + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - } else if ( material.displacementMap ) { + if ( object.isImmediateRenderObject ) { - uvScaleMap = material.displacementMap; + var program = setProgram( camera, scene, material, object ); - } else if ( material.normalMap ) { + state.setMaterial( material ); - uvScaleMap = material.normalMap; + _currentGeometryProgram.geometry = null; + _currentGeometryProgram.program = null; + _currentGeometryProgram.wireframe = false; - } else if ( material.bumpMap ) { + renderObjectImmediate( object, program ); - uvScaleMap = material.bumpMap; + } else { - } else if ( material.roughnessMap ) { + _this.renderBufferDirect( camera, scene, geometry, material, object, group ); - uvScaleMap = material.roughnessMap; + } - } else if ( material.metalnessMap ) { + object.onAfterRender( _this, scene, camera, geometry, material, group ); + currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); - uvScaleMap = material.metalnessMap; + } - } else if ( material.alphaMap ) { + function initMaterial( material, scene, object ) { - uvScaleMap = material.alphaMap; + var materialProperties = properties.get( material ); - } else if ( material.emissiveMap ) { + var lights = currentRenderState.state.lights; + var shadowsArray = currentRenderState.state.shadowsArray; - uvScaleMap = material.emissiveMap; + var lightsStateVersion = lights.state.version; - } + var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object ); + var programCacheKey = programCache.getProgramCacheKey( parameters ); - if ( uvScaleMap !== undefined ) { + var program = materialProperties.program; + var programChange = true; - // backwards compatibility - if ( uvScaleMap.isWebGLRenderTarget ) { + if ( program === undefined ) { - uvScaleMap = uvScaleMap.texture; + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - } + } else if ( program.cacheKey !== programCacheKey ) { - if ( uvScaleMap.matrixAutoUpdate === true ) { + // changed glsl or parameters + releaseMaterialProgramReference( material ); - uvScaleMap.updateMatrix(); + } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) { - } + materialProperties.lightsStateVersion = lightsStateVersion; - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + programChange = false; - } + } else if ( parameters.shaderID !== undefined ) { - } + // same glsl and uniform list + return; - function refreshUniformsLine( uniforms, material ) { + } else { - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; + // only rebuild uniform list + programChange = false; } - function refreshUniformsDash( uniforms, material ) { + if ( programChange ) { + + program = programCache.acquireProgram( parameters, programCacheKey ); - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + materialProperties.program = program; + materialProperties.uniforms = parameters.uniforms; + materialProperties.outputEncoding = parameters.outputEncoding; + material.program = program; } - function refreshUniformsPoints( uniforms, material ) { + var programAttributes = program.getAttributes(); - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _height * 0.5; + if ( material.morphTargets ) { - if ( material.map ) { + material.numSupportedMorphTargets = 0; - uniforms.map.value = material.map; + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - } + if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { - if ( material.alphaMap ) { + material.numSupportedMorphTargets ++; - uniforms.alphaMap.value = material.alphaMap; + } } - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map - - var uvScaleMap; + } - if ( material.map ) { + if ( material.morphNormals ) { - uvScaleMap = material.map; + material.numSupportedMorphNormals = 0; - } else if ( material.alphaMap ) { + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - uvScaleMap = material.alphaMap; + if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { - } + material.numSupportedMorphNormals ++; - if ( uvScaleMap !== undefined ) { + } - if ( uvScaleMap.matrixAutoUpdate === true ) { + } - uvScaleMap.updateMatrix(); + } - } + var uniforms = materialProperties.uniforms; - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + if ( ! material.isShaderMaterial && + ! material.isRawShaderMaterial || + material.clipping === true ) { - } + materialProperties.numClippingPlanes = _clipping.numPlanes; + materialProperties.numIntersection = _clipping.numIntersection; + uniforms.clippingPlanes = _clipping.uniform; } - function refreshUniformsSprites( uniforms, material ) { - - uniforms.diffuse.value.copy( material.color ); - uniforms.opacity.value = material.opacity; - uniforms.rotation.value = material.rotation; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; - if ( material.map ) { + // store the light setup it was created for - uniforms.map.value = material.map; + materialProperties.needsLights = materialNeedsLights( material ); + materialProperties.lightsStateVersion = lightsStateVersion; - } + if ( materialProperties.needsLights ) { - if ( material.alphaMap ) { + // wire up the material to this renderer's lighting state - uniforms.alphaMap.value = material.alphaMap; + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; - } + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms - // uv repeat and offset setting priorities - // 1. color map - // 2. alpha map + } - var uvScaleMap; + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - if ( material.map ) { + materialProperties.uniformsList = uniformsList; - uvScaleMap = material.map; + } - } else if ( material.alphaMap ) { + function setProgram( camera, scene, material, object ) { - uvScaleMap = material.alphaMap; + textures.resetTextureUnits(); - } + var fog = scene.fog; + var environment = material.isMeshStandardMaterial ? scene.environment : null; + var encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding; - if ( uvScaleMap !== undefined ) { + var materialProperties = properties.get( material ); + var lights = currentRenderState.state.lights; - if ( uvScaleMap.matrixAutoUpdate === true ) { + if ( _clippingEnabled ) { - uvScaleMap.updateMatrix(); + if ( _localClippingEnabled || camera !== _currentCamera ) { - } + var useCache = + camera === _currentCamera && + material.id === _currentMaterialId; - uniforms.uvTransform.value.copy( uvScaleMap.matrix ); + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + _clipping.setState( + material.clippingPlanes, material.clipIntersection, material.clipShadows, + camera, materialProperties, useCache ); } } - function refreshUniformsFog( uniforms, fog ) { + if ( material.version === materialProperties.__version ) { - uniforms.fogColor.value.copy( fog.color ); + if ( materialProperties.program === undefined ) { - if ( fog.isFog ) { + initMaterial( material, scene, object ); - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + } else if ( material.fog && materialProperties.fog !== fog ) { - } else if ( fog.isFogExp2 ) { + initMaterial( material, scene, object ); - uniforms.fogDensity.value = fog.density; + } else if ( materialProperties.environment !== environment ) { - } + initMaterial( material, scene, object ); - } + } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { + + initMaterial( material, scene, object ); - function refreshUniformsLambert( uniforms, material ) { + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== _clipping.numPlanes || + materialProperties.numIntersection !== _clipping.numIntersection ) ) { - if ( material.emissiveMap ) { + initMaterial( material, scene, object ); - uniforms.emissiveMap.value = material.emissiveMap; + } else if ( materialProperties.outputEncoding !== encoding ) { + + initMaterial( material, scene, object ); } + } else { + + initMaterial( material, scene, object ); + materialProperties.__version = material.version; + } - function refreshUniformsPhong( uniforms, material ) { + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - uniforms.specular.value.copy( material.specular ); - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.uniforms; - if ( material.emissiveMap ) { + if ( state.useProgram( program.program ) ) { - uniforms.emissiveMap.value = material.emissiveMap; + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; - } + } - if ( material.bumpMap ) { + if ( material.id !== _currentMaterialId ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } + _currentMaterialId = material.id; - } + refreshMaterial = true; - if ( material.normalMap ) { + } - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } + if ( refreshProgram || _currentCamera !== camera ) { - } + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); - if ( material.displacementMap ) { + if ( capabilities.logarithmicDepthBuffer ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); } - } - - function refreshUniformsToon( uniforms, material ) { + if ( _currentCamera !== camera ) { - refreshUniformsPhong( uniforms, material ); + _currentCamera = camera; - if ( material.gradientMap ) { + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: - uniforms.gradientMap.value = material.gradientMap; + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done } - } - - function refreshUniformsStandard( uniforms, material ) { + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshStandardMaterial || + material.envMap ) { - if ( material.roughnessMap ) { + var uCamPos = p_uniforms.map.cameraPosition; - uniforms.roughnessMap.value = material.roughnessMap; + if ( uCamPos !== undefined ) { - } - - if ( material.metalnessMap ) { + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); - uniforms.metalnessMap.value = material.metalnessMap; + } } - if ( material.emissiveMap ) { + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial ) { - uniforms.emissiveMap.value = material.emissiveMap; + p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); } - if ( material.bumpMap ) { + if ( material.isMeshPhongMaterial || + material.isMeshToonMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.skinning ) { - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); } - if ( material.normalMap ) { + } - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // otherwise textures used for skinning can take over texture units reserved for other material textures - } + if ( material.skinning ) { - if ( material.displacementMap ) { + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + var skeleton = object.skeleton; - } + if ( skeleton ) { - if ( material.envMap ) { + var bones = skeleton.bones; - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + if ( capabilities.floatVertexTextures ) { - } + if ( skeleton.boneTexture === undefined ) { + + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) - } - function refreshUniformsPhysical( uniforms, material ) { + var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix + size = MathUtils.ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); - refreshUniformsStandard( uniforms, material ); + var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( skeleton.boneMatrices ); // copy current values - uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common + var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); - uniforms.clearcoat.value = material.clearcoat; - uniforms.clearcoatRoughness.value = material.clearcoatRoughness; - if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); } + skeleton.boneMatrices = boneMatrices; + skeleton.boneTexture = boneTexture; + skeleton.boneTextureSize = size; - if ( material.clearcoatNormalMap ) { + } - uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); - uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); - if ( material.side === BackSide ) { + } else { - uniforms.clearcoatNormalScale.value.negate(); + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); } } - uniforms.transparency.value = material.transparency; - } - function refreshUniformsMatcap( uniforms, material ) { + if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { - if ( material.matcap ) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); - uniforms.matcap.value = material.matcap; + } - } + if ( refreshMaterial ) { - if ( material.bumpMap ) { + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } + if ( materialProperties.needsLights ) { - } + // the current material requires lighting info - if ( material.normalMap ) { + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); } - if ( material.displacementMap ) { + // refresh uniforms common to several materials - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( fog && material.fog ) { - } + materials.refreshFogUniforms( m_uniforms, fog ); - } + } - function refreshUniformsDepth( uniforms, material ) { + materials.refreshMaterialUniforms( m_uniforms, material, environment, _pixelRatio, _height ); - if ( material.displacementMap ) { + // RectAreaLight Texture + // TODO (mrdoob): Find a nicer implementation - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1; + if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2; - } + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); } - function refreshUniformsDistance( uniforms, material ) { + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { - if ( material.displacementMap ) { + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); + material.uniformsNeedUpdate = false; - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + } - } + if ( material.isSpriteMaterial ) { - uniforms.referencePosition.value.copy( material.referencePosition ); - uniforms.nearDistance.value = material.nearDistance; - uniforms.farDistance.value = material.farDistance; + p_uniforms.setValue( _gl, 'center', object.center ); } - function refreshUniformsNormal( uniforms, material ) { + // common matrices - if ( material.bumpMap ) { + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; - if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } + return program; - } + } - if ( material.normalMap ) { + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); - if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } + function markUniformsLightsNeedsUpdate( uniforms, value ) { - } + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; - if ( material.displacementMap ) { + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + } - } + function materialNeedsLights( material ) { - } + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || + material.isMeshStandardMaterial || material.isShadowMaterial || + ( material.isShaderMaterial && material.lights === true ); - // If uniforms are marked as clean, they don't need to be loaded to the GPU. + } - function markUniformsLightsNeedsUpdate( uniforms, value ) { + // + this.setFramebuffer = function ( value ) { - uniforms.ambientLightColor.needsUpdate = value; - uniforms.lightProbe.needsUpdate = value; + if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value ); - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.rectAreaLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + _framebuffer = value; - } + }; - function materialNeedsLights( material ) { + this.getActiveCubeFace = function () { - return material.isMeshLambertMaterial || material.isMeshPhongMaterial || - material.isMeshStandardMaterial || material.isShadowMaterial || - ( material.isShaderMaterial && material.lights === true ); + return _currentActiveCubeFace; - } + }; - // - this.setFramebuffer = function ( value ) { + this.getActiveMipmapLevel = function () { - if ( _framebuffer !== value && _currentRenderTarget === null ) { _gl.bindFramebuffer( 36160, value ); } + return _currentActiveMipmapLevel; - _framebuffer = value; + }; - }; + this.getRenderTarget = function () { - this.getActiveCubeFace = function () { + return _currentRenderTarget; - return _currentActiveCubeFace; + }; - }; - - this.getActiveMipmapLevel = function () { + this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) { - return _currentActiveMipmapLevel; + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; - }; + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { - this.getRenderTarget = function () { + textures.setupRenderTarget( renderTarget ); - return _currentRenderTarget; + } - }; + var framebuffer = _framebuffer; + var isCube = false; - this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) { + if ( renderTarget ) { - _currentRenderTarget = renderTarget; - _currentActiveCubeFace = activeCubeFace; - _currentActiveMipmapLevel = activeMipmapLevel; + var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + if ( renderTarget.isWebGLCubeRenderTarget ) { - textures.setupRenderTarget( renderTarget ); + framebuffer = __webglFramebuffer[ activeCubeFace || 0 ]; + isCube = true; - } + } else if ( renderTarget.isWebGLMultisampleRenderTarget ) { - var framebuffer = _framebuffer; - var isCube = false; + framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; - if ( renderTarget ) { + } else { - var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; + framebuffer = __webglFramebuffer; - if ( renderTarget.isWebGLRenderTargetCube ) { + } - framebuffer = __webglFramebuffer[ activeCubeFace || 0 ]; - isCube = true; + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; - } else if ( renderTarget.isWebGLMultisampleRenderTarget ) { + } else { - framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); + _currentScissorTest = _scissorTest; - } else { + } - framebuffer = __webglFramebuffer; + if ( _currentFramebuffer !== framebuffer ) { - } + _gl.bindFramebuffer( 36160, framebuffer ); + _currentFramebuffer = framebuffer; - _currentViewport.copy( renderTarget.viewport ); - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + } - } else { + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); - _currentScissorTest = _scissorTest; + if ( isCube ) { - } + var textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 ); - if ( _currentFramebuffer !== framebuffer ) { + } - _gl.bindFramebuffer( 36160, framebuffer ); - _currentFramebuffer = framebuffer; + }; - } + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { - state.viewport( _currentViewport ); - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { - if ( isCube ) { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - var textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 ); + } - } + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - }; + if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { + framebuffer = framebuffer[ activeCubeFaceIndex ]; - if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + if ( framebuffer ) { - } + var restore = false; - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; + if ( framebuffer !== _currentFramebuffer ) { - if ( renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined ) { + _gl.bindFramebuffer( 36160, framebuffer ); - framebuffer = framebuffer[ activeCubeFaceIndex ]; + restore = true; } - if ( framebuffer ) { - - var restore = false; + try { - if ( framebuffer !== _currentFramebuffer ) { + var texture = renderTarget.texture; + var textureFormat = texture.format; + var textureType = texture.type; - _gl.bindFramebuffer( 36160, framebuffer ); + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { - restore = true; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; } - try { + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) { - var texture = renderTarget.texture; - var textureFormat = texture.format; - var textureType = texture.type; + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { + } - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) { - } + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513) - ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox - ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) { + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); } - if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) { - - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + } else { - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + } - } + } finally { - } else { + if ( restore ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + _gl.bindFramebuffer( 36160, _currentFramebuffer ); - } + } - } finally { + } - if ( restore ) { + } - _gl.bindFramebuffer( 36160, _currentFramebuffer ); + }; - } + this.copyFramebufferToTexture = function ( position, texture, level ) { - } + if ( level === undefined ) level = 0; - } + var levelScale = Math.pow( 2, - level ); + var width = Math.floor( texture.image.width * levelScale ); + var height = Math.floor( texture.image.height * levelScale ); + var glFormat = utils.convert( texture.format ); - }; + textures.setTexture2D( texture, 0 ); - this.copyFramebufferToTexture = function ( position, texture, level ) { + _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 ); - if ( level === undefined ) { level = 0; } + state.unbindTexture(); - var levelScale = Math.pow( 2, - level ); - var width = Math.floor( texture.image.width * levelScale ); - var height = Math.floor( texture.image.height * levelScale ); - var glFormat = utils.convert( texture.format ); + }; - textures.setTexture2D( texture, 0 ); + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) { - _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 ); + if ( level === undefined ) level = 0; - state.unbindTexture(); + var width = srcTexture.image.width; + var height = srcTexture.image.height; + var glFormat = utils.convert( dstTexture.format ); + var glType = utils.convert( dstTexture.type ); - }; + textures.setTexture2D( dstTexture, 0 ); - this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) { + if ( srcTexture.isDataTexture ) { - var width = srcTexture.image.width; - var height = srcTexture.image.height; - var glFormat = utils.convert( dstTexture.format ); - var glType = utils.convert( dstTexture.type ); + _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); - textures.setTexture2D( dstTexture, 0 ); + } else { - if ( srcTexture.isDataTexture ) { + if ( srcTexture.isCompressedTexture ) { - _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); + _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data ); } else { - _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image ); + _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image ); } - state.unbindTexture(); + } + + // Generate mipmaps only when copying level 0 + if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 ); - }; + state.unbindTexture(); - this.initTexture = function ( texture ) { + }; - textures.setTexture2D( texture, 0 ); + this.initTexture = function ( texture ) { - state.unbindTexture(); + textures.setTexture2D( texture, 0 ); - }; + state.unbindTexture(); - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + }; - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef + if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { - } + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef } - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ +} - function FogExp2( color, density ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.name = ''; +function FogExp2( color, density ) { - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + this.name = ''; - } + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - Object.assign( FogExp2.prototype, { +} - isFogExp2: true, +Object.assign( FogExp2.prototype, { - clone: function () { + isFogExp2: true, - return new FogExp2( this.color, this.density ); + clone: function () { - }, + return new FogExp2( this.color, this.density ); - toJSON: function ( /* meta */ ) { + }, - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + toJSON: function ( /* meta */ ) { - } + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ +} ); - function Fog( color, near, far ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.name = ''; +function Fog( color, near, far ) { - this.color = new Color( color ); + this.name = ''; - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + this.color = new Color( color ); - } + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - Object.assign( Fog.prototype, { +} - isFog: true, +Object.assign( Fog.prototype, { - clone: function () { + isFog: true, - return new Fog( this.color, this.near, this.far ); + clone: function () { - }, + return new Fog( this.color, this.near, this.far ); - toJSON: function ( /* meta */ ) { + }, - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + toJSON: function ( /* meta */ ) { - } + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - } ); + } - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ +} ); - function InterleavedBuffer( array, stride ) { +/** + * @author benaadams / https://twitter.com/ben_a_adams + */ - this.array = array; - this.stride = stride; - this.count = array !== undefined ? array.length / stride : 0; +function InterleavedBuffer( array, stride ) { - this.usage = StaticDrawUsage; - this.updateRange = { offset: 0, count: - 1 }; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; - this.version = 0; + this.usage = StaticDrawUsage; + this.updateRange = { offset: 0, count: - 1 }; - } + this.version = 0; - Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', { +} - set: function ( value ) { +Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', { - if ( value === true ) { this.version ++; } + set: function ( value ) { - } + if ( value === true ) this.version ++; - } ); + } - Object.assign( InterleavedBuffer.prototype, { +} ); - isInterleavedBuffer: true, +Object.assign( InterleavedBuffer.prototype, { - onUploadCallback: function () {}, + isInterleavedBuffer: true, - setUsage: function ( value ) { + onUploadCallback: function () {}, - this.usage = value; + setUsage: function ( value ) { - return this; + this.usage = value; - }, + return this; - copy: function ( source ) { + }, - this.array = new source.array.constructor( source.array ); - this.count = source.count; - this.stride = source.stride; - this.usage = source.usage; + copy: function ( source ) { - return this; + this.array = new source.array.constructor( source.array ); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; - }, + return this; - copyAt: function ( index1, attribute, index2 ) { + }, - index1 *= this.stride; - index2 *= attribute.stride; + copyAt: function ( index1, attribute, index2 ) { - for ( var i = 0, l = this.stride; i < l; i ++ ) { + index1 *= this.stride; + index2 *= attribute.stride; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + for ( var i = 0, l = this.stride; i < l; i ++ ) { - } + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - return this; + } - }, + return this; - set: function ( value, offset ) { + }, - if ( offset === undefined ) { offset = 0; } + set: function ( value, offset ) { - this.array.set( value, offset ); + if ( offset === undefined ) offset = 0; - return this; + this.array.set( value, offset ); - }, + return this; - clone: function () { + }, - return new this.constructor().copy( this ); + clone: function () { - }, + return new this.constructor().copy( this ); - onUpload: function ( callback ) { + }, - this.onUploadCallback = callback; + onUpload: function ( callback ) { - return this; + this.onUploadCallback = callback; - } + return this; - } ); + } - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ +} ); - function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { +/** + * @author benaadams / https://twitter.com/ben_a_adams + */ - this.data = interleavedBuffer; - this.itemSize = itemSize; - this.offset = offset; +var _vector$6 = new Vector3(); - this.normalized = normalized === true; +function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { - } + this.name = ''; - Object.defineProperties( InterleavedBufferAttribute.prototype, { + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; - count: { + this.normalized = normalized === true; - get: function () { +} - return this.data.count; +Object.defineProperties( InterleavedBufferAttribute.prototype, { - } + count: { - }, + get: function () { - array: { + return this.data.count; - get: function () { + } - return this.data.array; + }, - } + array: { - } + get: function () { - } ); + return this.data.array; - Object.assign( InterleavedBufferAttribute.prototype, { + } - isInterleavedBufferAttribute: true, + } - setX: function ( index, x ) { +} ); - this.data.array[ index * this.data.stride + this.offset ] = x; +Object.assign( InterleavedBufferAttribute.prototype, { - return this; + isInterleavedBufferAttribute: true, - }, + applyMatrix4: function ( m ) { - setY: function ( index, y ) { + for ( var i = 0, l = this.data.count; i < l; i ++ ) { - this.data.array[ index * this.data.stride + this.offset + 1 ] = y; + _vector$6.x = this.getX( i ); + _vector$6.y = this.getY( i ); + _vector$6.z = this.getZ( i ); - return this; + _vector$6.applyMatrix4( m ); - }, + this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); - setZ: function ( index, z ) { + } - this.data.array[ index * this.data.stride + this.offset + 2 ] = z; + return this; - return this; + }, - }, + setX: function ( index, x ) { - setW: function ( index, w ) { + this.data.array[ index * this.data.stride + this.offset ] = x; - this.data.array[ index * this.data.stride + this.offset + 3 ] = w; + return this; - return this; + }, - }, + setY: function ( index, y ) { - getX: function ( index ) { + this.data.array[ index * this.data.stride + this.offset + 1 ] = y; - return this.data.array[ index * this.data.stride + this.offset ]; + return this; - }, + }, - getY: function ( index ) { + setZ: function ( index, z ) { - return this.data.array[ index * this.data.stride + this.offset + 1 ]; + this.data.array[ index * this.data.stride + this.offset + 2 ] = z; - }, + return this; - getZ: function ( index ) { + }, - return this.data.array[ index * this.data.stride + this.offset + 2 ]; + setW: function ( index, w ) { - }, + this.data.array[ index * this.data.stride + this.offset + 3 ] = w; - getW: function ( index ) { + return this; - return this.data.array[ index * this.data.stride + this.offset + 3 ]; + }, - }, + getX: function ( index ) { - setXY: function ( index, x, y ) { + return this.data.array[ index * this.data.stride + this.offset ]; - index = index * this.data.stride + this.offset; + }, - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; + getY: function ( index ) { - return this; + return this.data.array[ index * this.data.stride + this.offset + 1 ]; - }, + }, - setXYZ: function ( index, x, y, z ) { + getZ: function ( index ) { - index = index * this.data.stride + this.offset; + return this.data.array[ index * this.data.stride + this.offset + 2 ]; - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; + }, - return this; + getW: function ( index ) { - }, + return this.data.array[ index * this.data.stride + this.offset + 3 ]; - setXYZW: function ( index, x, y, z, w ) { + }, - index = index * this.data.stride + this.offset; + setXY: function ( index, x, y ) { - this.data.array[ index + 0 ] = x; - this.data.array[ index + 1 ] = y; - this.data.array[ index + 2 ] = z; - this.data.array[ index + 3 ] = w; + index = index * this.data.stride + this.offset; - return this; + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; - } + return this; - } ); + }, - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * rotation: , - * sizeAttenuation: - * } - */ + setXYZ: function ( index, x, y, z ) { - function SpriteMaterial( parameters ) { + index = index * this.data.stride + this.offset; - Material.call( this ); + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; - this.type = 'SpriteMaterial'; + return this; - this.color = new Color( 0xffffff ); + }, - this.map = null; + setXYZW: function ( index, x, y, z, w ) { - this.alphaMap = null; + index = index * this.data.stride + this.offset; - this.rotation = 0; + this.data.array[ index + 0 ] = x; + this.data.array[ index + 1 ] = y; + this.data.array[ index + 2 ] = z; + this.data.array[ index + 3 ] = w; - this.sizeAttenuation = true; + return this; - this.transparent = true; + }, - this.setValues( parameters ); + clone: function () { - } + console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' ); - SpriteMaterial.prototype = Object.create( Material.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; - SpriteMaterial.prototype.isSpriteMaterial = true; + var array = []; - SpriteMaterial.prototype.copy = function ( source ) { + for ( var i = 0; i < this.count; i ++ ) { - Material.prototype.copy.call( this, source ); + var index = i * this.data.stride + this.offset; - this.color.copy( source.color ); + for ( var j = 0; j < this.itemSize; j ++ ) { - this.map = source.map; + array.push( this.data.array[ index + j ] ); - this.alphaMap = source.alphaMap; + } - this.rotation = source.rotation; + } - this.sizeAttenuation = source.sizeAttenuation; + return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized ); - return this; + }, - }; + toJSON: function () { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' ); - var _geometry; + var array = []; - var _intersectPoint = new Vector3(); - var _worldScale = new Vector3(); - var _mvPosition = new Vector3(); + for ( var i = 0; i < this.count; i ++ ) { - var _alignedPosition = new Vector2(); - var _rotatedPosition = new Vector2(); - var _viewWorldMatrix = new Matrix4(); + var index = i * this.data.stride + this.offset; - var _vA$1 = new Vector3(); - var _vB$1 = new Vector3(); - var _vC$1 = new Vector3(); + for ( var j = 0; j < this.itemSize; j ++ ) { - var _uvA$1 = new Vector2(); - var _uvB$1 = new Vector2(); - var _uvC$1 = new Vector2(); + array.push( this.data.array[ index + j ] ); - function Sprite( material ) { + } - Object3D.call( this ); + } - this.type = 'Sprite'; + // deinterleave data and save it as an ordinary buffer attribute for now - if ( _geometry === undefined ) { + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: array, + normalized: this.normalized + }; - _geometry = new BufferGeometry(); + } - var float32Array = new Float32Array( [ - - 0.5, - 0.5, 0, 0, 0, - 0.5, - 0.5, 0, 1, 0, - 0.5, 0.5, 0, 1, 1, - - 0.5, 0.5, 0, 0, 1 - ] ); +} ); - var interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * map: new THREE.Texture( ), + * alphaMap: new THREE.Texture( ), + * rotation: , + * sizeAttenuation: + * } + */ - _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); - _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); - _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); +function SpriteMaterial( parameters ) { - } + Material.call( this ); - this.geometry = _geometry; - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + this.type = 'SpriteMaterial'; - this.center = new Vector2( 0.5, 0.5 ); + this.color = new Color( 0xffffff ); - } + this.map = null; - Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.alphaMap = null; - constructor: Sprite, + this.rotation = 0; - isSprite: true, + this.sizeAttenuation = true; - raycast: function ( raycaster, intersects ) { + this.transparent = true; - if ( raycaster.camera === null ) { + this.setValues( parameters ); - console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); +} - } +SpriteMaterial.prototype = Object.create( Material.prototype ); +SpriteMaterial.prototype.constructor = SpriteMaterial; +SpriteMaterial.prototype.isSpriteMaterial = true; - _worldScale.setFromMatrixScale( this.matrixWorld ); +SpriteMaterial.prototype.copy = function ( source ) { - _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); - this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); + Material.prototype.copy.call( this, source ); - _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); + this.color.copy( source.color ); - if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { + this.map = source.map; - _worldScale.multiplyScalar( - _mvPosition.z ); + this.alphaMap = source.alphaMap; - } + this.rotation = source.rotation; - var rotation = this.material.rotation; - var sin, cos; - if ( rotation !== 0 ) { + this.sizeAttenuation = source.sizeAttenuation; - cos = Math.cos( rotation ); - sin = Math.sin( rotation ); + return this; - } +}; - var center = this.center; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ - transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); +var _geometry; - _uvA$1.set( 0, 0 ); - _uvB$1.set( 1, 0 ); - _uvC$1.set( 1, 1 ); +var _intersectPoint = new Vector3(); +var _worldScale = new Vector3(); +var _mvPosition = new Vector3(); - // check first triangle - var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); +var _alignedPosition = new Vector2(); +var _rotatedPosition = new Vector2(); +var _viewWorldMatrix = new Matrix4(); - if ( intersect === null ) { +var _vA$1 = new Vector3(); +var _vB$1 = new Vector3(); +var _vC$1 = new Vector3(); - // check second triangle - transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - _uvB$1.set( 0, 1 ); +var _uvA$1 = new Vector2(); +var _uvB$1 = new Vector2(); +var _uvC$1 = new Vector2(); - intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); - if ( intersect === null ) { +function Sprite( material ) { - return; + Object3D.call( this ); - } + this.type = 'Sprite'; - } + if ( _geometry === undefined ) { - var distance = raycaster.ray.origin.distanceTo( _intersectPoint ); + _geometry = new BufferGeometry(); - if ( distance < raycaster.near || distance > raycaster.far ) { return; } + var float32Array = new Float32Array( [ + - 0.5, - 0.5, 0, 0, 0, + 0.5, - 0.5, 0, 1, 0, + 0.5, 0.5, 0, 1, 1, + - 0.5, 0.5, 0, 0, 1 + ] ); - intersects.push( { + var interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); - distance: distance, - point: _intersectPoint.clone(), - uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ), - face: null, - object: this + _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); + _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); + _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); - } ); + } - }, + this.geometry = _geometry; + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); - clone: function () { + this.center = new Vector2( 0.5, 0.5 ); - return new this.constructor( this.material ).copy( this ); +} - }, +Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - copy: function ( source ) { + constructor: Sprite, - Object3D.prototype.copy.call( this, source ); + isSprite: true, - if ( source.center !== undefined ) { this.center.copy( source.center ); } + raycast: function ( raycaster, intersects ) { - return this; + if ( raycaster.camera === null ) { + + console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); } + _worldScale.setFromMatrixScale( this.matrixWorld ); - } ); + _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); + this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); - function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { + _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); - // compute position in camera space - _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); + if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { - // to check if rotation is not zero - if ( sin !== undefined ) { + _worldScale.multiplyScalar( - _mvPosition.z ); - _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); - _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); + } - } else { + var rotation = this.material.rotation; + var sin, cos; + if ( rotation !== 0 ) { - _rotatedPosition.copy( _alignedPosition ); + cos = Math.cos( rotation ); + sin = Math.sin( rotation ); } + var center = this.center; - vertexPosition.copy( mvPosition ); - vertexPosition.x += _rotatedPosition.x; - vertexPosition.y += _rotatedPosition.y; + transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); - // transform to world space - vertexPosition.applyMatrix4( _viewWorldMatrix ); - - } + _uvA$1.set( 0, 0 ); + _uvB$1.set( 1, 0 ); + _uvC$1.set( 1, 1 ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + // check first triangle + var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); - var _v1$4 = new Vector3(); - var _v2$2 = new Vector3(); + if ( intersect === null ) { - function LOD() { + // check second triangle + transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); + _uvB$1.set( 0, 1 ); - Object3D.call( this ); + intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); + if ( intersect === null ) { - this.type = 'LOD'; + return; - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] } - } ); - - this.autoUpdate = true; - } + } - LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { + var distance = raycaster.ray.origin.distanceTo( _intersectPoint ); - constructor: LOD, + if ( distance < raycaster.near || distance > raycaster.far ) return; - isLOD: true, + intersects.push( { - copy: function ( source ) { + distance: distance, + point: _intersectPoint.clone(), + uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ), + face: null, + object: this - Object3D.prototype.copy.call( this, source, false ); + } ); - var levels = source.levels; + }, - for ( var i = 0, l = levels.length; i < l; i ++ ) { + clone: function () { - var level = levels[ i ]; + return new this.constructor( this.material ).copy( this ); - this.addLevel( level.object.clone(), level.distance ); + }, - } + copy: function ( source ) { - this.autoUpdate = source.autoUpdate; + Object3D.prototype.copy.call( this, source ); - return this; + if ( source.center !== undefined ) this.center.copy( source.center ); - }, + return this; - addLevel: function ( object, distance ) { + } - if ( distance === undefined ) { distance = 0; } - distance = Math.abs( distance ); +} ); - var levels = this.levels; +function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { - for ( var l = 0; l < levels.length; l ++ ) { + // compute position in camera space + _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); - if ( distance < levels[ l ].distance ) { + // to check if rotation is not zero + if ( sin !== undefined ) { - break; + _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); + _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); - } + } else { - } + _rotatedPosition.copy( _alignedPosition ); - levels.splice( l, 0, { distance: distance, object: object } ); + } - this.add( object ); - return this; + vertexPosition.copy( mvPosition ); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; - }, + // transform to world space + vertexPosition.applyMatrix4( _viewWorldMatrix ); - getObjectForDistance: function ( distance ) { +} - var levels = this.levels; +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - if ( levels.length > 0 ) { +var _v1$4 = new Vector3(); +var _v2$2 = new Vector3(); - for ( var i = 1, l = levels.length; i < l; i ++ ) { +function LOD() { - if ( distance < levels[ i ].distance ) { + Object3D.call( this ); - break; + this._currentLevel = 0; - } + this.type = 'LOD'; - } + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); - return levels[ i - 1 ].object; + this.autoUpdate = true; - } +} - return null; +LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: LOD, - raycast: function ( raycaster, intersects ) { + isLOD: true, - var levels = this.levels; + copy: function ( source ) { - if ( levels.length > 0 ) { + Object3D.prototype.copy.call( this, source, false ); - _v1$4.setFromMatrixPosition( this.matrixWorld ); + var levels = source.levels; - var distance = raycaster.ray.origin.distanceTo( _v1$4 ); + for ( var i = 0, l = levels.length; i < l; i ++ ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + var level = levels[ i ]; - } + this.addLevel( level.object.clone(), level.distance ); - }, + } - update: function ( camera ) { + this.autoUpdate = source.autoUpdate; - var levels = this.levels; + return this; - if ( levels.length > 1 ) { + }, - _v1$4.setFromMatrixPosition( camera.matrixWorld ); - _v2$2.setFromMatrixPosition( this.matrixWorld ); + addLevel: function ( object, distance ) { - var distance = _v1$4.distanceTo( _v2$2 ); + if ( distance === undefined ) distance = 0; - levels[ 0 ].object.visible = true; + distance = Math.abs( distance ); - for ( var i = 1, l = levels.length; i < l; i ++ ) { + var levels = this.levels; - if ( distance >= levels[ i ].distance ) { + for ( var l = 0; l < levels.length; l ++ ) { - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + if ( distance < levels[ l ].distance ) { - } else { + break; - break; + } - } + } - } + levels.splice( l, 0, { distance: distance, object: object } ); - for ( ; i < l; i ++ ) { + this.add( object ); - levels[ i ].object.visible = false; + return this; - } + }, - } + getCurrentLevel: function () { - }, + return this._currentLevel; - toJSON: function ( meta ) { + }, - var data = Object3D.prototype.toJSON.call( this, meta ); + getObjectForDistance: function ( distance ) { - if ( this.autoUpdate === false ) { data.object.autoUpdate = false; } + var levels = this.levels; - data.object.levels = []; + if ( levels.length > 0 ) { - var levels = this.levels; + for ( var i = 1, l = levels.length; i < l; i ++ ) { - for ( var i = 0, l = levels.length; i < l; i ++ ) { + if ( distance < levels[ i ].distance ) { - var level = levels[ i ]; + break; - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + } } - return data; + return levels[ i - 1 ].object; } - } ); + return null; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + }, + + raycast: function ( raycaster, intersects ) { + + var levels = this.levels; + + if ( levels.length > 0 ) { - function SkinnedMesh( geometry, material ) { + _v1$4.setFromMatrixPosition( this.matrixWorld ); - if ( geometry && geometry.isGeometry ) { + var distance = raycaster.ray.origin.distanceTo( _v1$4 ); - console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); } - Mesh.call( this, geometry, material ); + }, - this.type = 'SkinnedMesh'; + update: function ( camera ) { - this.bindMode = 'attached'; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + var levels = this.levels; - } + if ( levels.length > 1 ) { - SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + _v1$4.setFromMatrixPosition( camera.matrixWorld ); + _v2$2.setFromMatrixPosition( this.matrixWorld ); - constructor: SkinnedMesh, + var distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom; - isSkinnedMesh: true, + levels[ 0 ].object.visible = true; - bind: function ( skeleton, bindMatrix ) { + for ( var i = 1, l = levels.length; i < l; i ++ ) { - this.skeleton = skeleton; + if ( distance >= levels[ i ].distance ) { - if ( bindMatrix === undefined ) { + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - this.updateMatrixWorld( true ); + } else { - this.skeleton.calculateInverses(); + break; - bindMatrix = this.matrixWorld; + } } - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + this._currentLevel = i - 1; - }, + for ( ; i < l; i ++ ) { - pose: function () { + levels[ i ].object.visible = false; - this.skeleton.pose(); + } - }, + } - normalizeSkinWeights: function () { + }, - var vector = new Vector4(); + toJSON: function ( meta ) { - var skinWeight = this.geometry.attributes.skinWeight; + var data = Object3D.prototype.toJSON.call( this, meta ); - for ( var i = 0, l = skinWeight.count; i < l; i ++ ) { + if ( this.autoUpdate === false ) data.object.autoUpdate = false; - vector.x = skinWeight.getX( i ); - vector.y = skinWeight.getY( i ); - vector.z = skinWeight.getZ( i ); - vector.w = skinWeight.getW( i ); + data.object.levels = []; - var scale = 1.0 / vector.manhattanLength(); + var levels = this.levels; - if ( scale !== Infinity ) { + for ( var i = 0, l = levels.length; i < l; i ++ ) { - vector.multiplyScalar( scale ); + var level = levels[ i ]; - } else { + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); - vector.set( 1, 0, 0, 0 ); // do something reasonable + } - } + return data; - skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); + } - } +} ); - }, +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - updateMatrixWorld: function ( force ) { +function SkinnedMesh( geometry, material ) { - Mesh.prototype.updateMatrixWorld.call( this, force ); + if ( geometry && geometry.isGeometry ) { - if ( this.bindMode === 'attached' ) { + console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); - this.bindMatrixInverse.getInverse( this.matrixWorld ); + } - } else if ( this.bindMode === 'detached' ) { + Mesh.call( this, geometry, material ); - this.bindMatrixInverse.getInverse( this.bindMatrix ); + this.type = 'SkinnedMesh'; - } else { + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); - console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); +} - } +SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - }, + constructor: SkinnedMesh, - clone: function () { + isSkinnedMesh: true, - return new this.constructor( this.geometry, this.material ).copy( this ); + bind: function ( skeleton, bindMatrix ) { - } + this.skeleton = skeleton; - } ); + if ( bindMatrix === undefined ) { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + this.updateMatrixWorld( true ); - var _offsetMatrix = new Matrix4(); - var _identityMatrix = new Matrix4(); + this.skeleton.calculateInverses(); - function Skeleton( bones, boneInverses ) { + bindMatrix = this.matrixWorld; - // copy the bone array + } - bones = bones || []; + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - this.bones = bones.slice( 0 ); - this.boneMatrices = new Float32Array( this.bones.length * 16 ); + }, - this.frame = - 1; + pose: function () { - // use the supplied bone inverses or calculate the inverses + this.skeleton.pose(); - if ( boneInverses === undefined ) { + }, - this.calculateInverses(); + normalizeSkinWeights: function () { - } else { + var vector = new Vector4(); - if ( this.bones.length === boneInverses.length ) { + var skinWeight = this.geometry.attributes.skinWeight; - this.boneInverses = boneInverses.slice( 0 ); + for ( var i = 0, l = skinWeight.count; i < l; i ++ ) { - } else { + vector.x = skinWeight.getX( i ); + vector.y = skinWeight.getY( i ); + vector.z = skinWeight.getZ( i ); + vector.w = skinWeight.getW( i ); - console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); + var scale = 1.0 / vector.manhattanLength(); - this.boneInverses = []; + if ( scale !== Infinity ) { - for ( var i = 0, il = this.bones.length; i < il; i ++ ) { + vector.multiplyScalar( scale ); - this.boneInverses.push( new Matrix4() ); + } else { - } + vector.set( 1, 0, 0, 0 ); // do something reasonable } - } - - } + skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); - Object.assign( Skeleton.prototype, { + } - calculateInverses: function () { + }, - this.boneInverses = []; + updateMatrixWorld: function ( force ) { - for ( var i = 0, il = this.bones.length; i < il; i ++ ) { + Mesh.prototype.updateMatrixWorld.call( this, force ); - var inverse = new Matrix4(); + if ( this.bindMode === 'attached' ) { - if ( this.bones[ i ] ) { + this.bindMatrixInverse.getInverse( this.matrixWorld ); - inverse.getInverse( this.bones[ i ].matrixWorld ); + } else if ( this.bindMode === 'detached' ) { - } + this.bindMatrixInverse.getInverse( this.bindMatrix ); - this.boneInverses.push( inverse ); + } else { - } + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); - }, + } - pose: function () { + }, - var bone, i, il; + clone: function () { - // recover the bind-time world matrices + return new this.constructor( this.geometry, this.material ).copy( this ); - for ( i = 0, il = this.bones.length; i < il; i ++ ) { + }, - bone = this.bones[ i ]; + boneTransform: ( function () { - if ( bone ) { + var basePosition = new Vector3(); - bone.matrixWorld.getInverse( this.boneInverses[ i ] ); + var skinIndex = new Vector4(); + var skinWeight = new Vector4(); - } + var vector = new Vector3(); + var matrix = new Matrix4(); - } + return function ( index, target ) { - // compute the local matrices, positions, rotations and scales + var skeleton = this.skeleton; + var geometry = this.geometry; - for ( i = 0, il = this.bones.length; i < il; i ++ ) { + skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index ); + skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index ); - bone = this.bones[ i ]; + basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix ); - if ( bone ) { + target.set( 0, 0, 0 ); - if ( bone.parent && bone.parent.isBone ) { + for ( var i = 0; i < 4; i ++ ) { - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + var weight = skinWeight.getComponent( i ); - } else { + if ( weight !== 0 ) { - bone.matrix.copy( bone.matrixWorld ); + var boneIndex = skinIndex.getComponent( i ); - } + matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] ); - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + target.addScaledVector( vector.copy( basePosition ).applyMatrix4( matrix ), weight ); } } - }, + return target.applyMatrix4( this.bindMatrixInverse ); - update: function () { + }; - var bones = this.bones; - var boneInverses = this.boneInverses; - var boneMatrices = this.boneMatrices; - var boneTexture = this.boneTexture; + }() ) - // flatten bone matrices to array +} ); - for ( var i = 0, il = bones.length; i < il; i ++ ) { +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com + */ - // compute the offset between the current and the original transform +var _offsetMatrix = new Matrix4(); +var _identityMatrix = new Matrix4(); - var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; +function Skeleton( bones, boneInverses ) { - _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); - _offsetMatrix.toArray( boneMatrices, i * 16 ); + // copy the bone array - } + bones = bones || []; - if ( boneTexture !== undefined ) { + this.bones = bones.slice( 0 ); + this.boneMatrices = new Float32Array( this.bones.length * 16 ); - boneTexture.needsUpdate = true; + this.frame = - 1; - } + // use the supplied bone inverses or calculate the inverses - }, + if ( boneInverses === undefined ) { - clone: function () { + this.calculateInverses(); - return new Skeleton( this.bones, this.boneInverses ); + } else { - }, + if ( this.bones.length === boneInverses.length ) { - getBoneByName: function ( name ) { + this.boneInverses = boneInverses.slice( 0 ); - for ( var i = 0, il = this.bones.length; i < il; i ++ ) { + } else { - var bone = this.bones[ i ]; + console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); - if ( bone.name === name ) { + this.boneInverses = []; - return bone; + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - } + this.boneInverses.push( new Matrix4() ); } - return undefined; - } - } ); - - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + } - function Bone() { +} - Object3D.call( this ); +Object.assign( Skeleton.prototype, { - this.type = 'Bone'; + calculateInverses: function () { - } + this.boneInverses = []; - Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - constructor: Bone, + var inverse = new Matrix4(); - isBone: true + if ( this.bones[ i ] ) { - } ); + inverse.getInverse( this.bones[ i ].matrixWorld ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function InstancedMesh( geometry, material, count ) { + this.boneInverses.push( inverse ); - Mesh.call( this, geometry, material ); + } - this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 ); + }, - this.count = count; + pose: function () { - } + var bone, i, il; - InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + // recover the bind-time world matrices - constructor: InstancedMesh, + for ( i = 0, il = this.bones.length; i < il; i ++ ) { - isInstancedMesh: true, + bone = this.bones[ i ]; - raycast: function () {}, + if ( bone ) { - setMatrixAt: function ( index, matrix ) { + bone.matrixWorld.getInverse( this.boneInverses[ i ] ); - matrix.toArray( this.instanceMatrix.array, index * 16 ); + } - }, + } - updateMorphTargets: function () {} + // compute the local matrices, positions, rotations and scales - } ); + for ( i = 0, il = this.bones.length; i < il; i ++ ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * linecap: "round", - * linejoin: "round" - * } - */ + bone = this.bones[ i ]; - function LineBasicMaterial( parameters ) { + if ( bone ) { - Material.call( this ); + if ( bone.parent && bone.parent.isBone ) { - this.type = 'LineBasicMaterial'; + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); - this.color = new Color( 0xffffff ); + } else { - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + bone.matrix.copy( bone.matrixWorld ); - this.setValues( parameters ); + } - } + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); - LineBasicMaterial.prototype = Object.create( Material.prototype ); - LineBasicMaterial.prototype.constructor = LineBasicMaterial; + } - LineBasicMaterial.prototype.isLineBasicMaterial = true; + } - LineBasicMaterial.prototype.copy = function ( source ) { + }, - Material.prototype.copy.call( this, source ); + update: function () { - this.color.copy( source.color ); + var bones = this.bones; + var boneInverses = this.boneInverses; + var boneMatrices = this.boneMatrices; + var boneTexture = this.boneTexture; - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + // flatten bone matrices to array - return this; + for ( var i = 0, il = bones.length; i < il; i ++ ) { - }; + // compute the offset between the current and the original transform - /** - * @author mrdoob / http://mrdoob.com/ - */ + var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; - var _start = new Vector3(); - var _end = new Vector3(); - var _inverseMatrix$1 = new Matrix4(); - var _ray$1 = new Ray(); - var _sphere$2 = new Sphere(); + _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + _offsetMatrix.toArray( boneMatrices, i * 16 ); - function Line( geometry, material, mode ) { + } - if ( mode === 1 ) { + if ( boneTexture !== undefined ) { - console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' ); + boneTexture.needsUpdate = true; } - Object3D.call( this ); + }, - this.type = 'Line'; + clone: function () { - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); + return new Skeleton( this.bones, this.boneInverses ); - } - - Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + }, - constructor: Line, + getBoneByName: function ( name ) { - isLine: true, + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - computeLineDistances: function () { + var bone = this.bones[ i ]; - var geometry = this.geometry; + if ( bone.name === name ) { - if ( geometry.isBufferGeometry ) { + return bone; - // we assume non-indexed geometry + } - if ( geometry.index === null ) { + } - var positionAttribute = geometry.attributes.position; - var lineDistances = [ 0 ]; + return undefined; - for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) { + }, - _start.fromBufferAttribute( positionAttribute, i - 1 ); - _end.fromBufferAttribute( positionAttribute, i ); + dispose: function ( ) { - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += _start.distanceTo( _end ); + if ( this.boneTexture ) { - } + this.boneTexture.dispose(); - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + this.boneTexture = undefined; - } else { + } - console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + } - } +} ); - } else if ( geometry.isGeometry ) { +/** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com + */ - var vertices = geometry.vertices; - var lineDistances = geometry.lineDistances; +function Bone() { - lineDistances[ 0 ] = 0; + Object3D.call( this ); - for ( var i = 1, l = vertices.length; i < l; i ++ ) { + this.type = 'Bone'; - lineDistances[ i ] = lineDistances[ i - 1 ]; - lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] ); +} - } +Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Bone, - return this; + isBone: true - }, +} ); - raycast: function ( raycaster, intersects ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - var precision = raycaster.linePrecision; +var _instanceLocalMatrix = new Matrix4(); +var _instanceWorldMatrix = new Matrix4(); - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; +var _instanceIntersects = []; - // Checking boundingSphere distance to ray +var _mesh = new Mesh(); - if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } +function InstancedMesh( geometry, material, count ) { - _sphere$2.copy( geometry.boundingSphere ); - _sphere$2.applyMatrix4( matrixWorld ); - _sphere$2.radius += precision; + Mesh.call( this, geometry, material ); - if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; } + this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 ); - // + this.count = count; - _inverseMatrix$1.getInverse( matrixWorld ); - _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); + this.frustumCulled = false; - var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localPrecisionSq = localPrecision * localPrecision; +} - var vStart = new Vector3(); - var vEnd = new Vector3(); - var interSegment = new Vector3(); - var interRay = new Vector3(); - var step = ( this && this.isLineSegments ) ? 2 : 1; +InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - if ( geometry.isBufferGeometry ) { + constructor: InstancedMesh, - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + isInstancedMesh: true, - if ( index !== null ) { + getMatrixAt: function ( index, matrix ) { - var indices = index.array; + matrix.fromArray( this.instanceMatrix.array, index * 16 ); - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + }, - var a = indices[ i ]; - var b = indices[ i + 1 ]; + raycast: function ( raycaster, intersects ) { - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + var matrixWorld = this.matrixWorld; + var raycastTimes = this.count; - var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + _mesh.geometry = this.geometry; + _mesh.material = this.material; - if ( distSq > localPrecisionSq ) { continue; } + if ( _mesh.material === undefined ) return; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { - var distance = raycaster.ray.origin.distanceTo( interRay ); + // calculate the world matrix for each instance - if ( distance < raycaster.near || distance > raycaster.far ) { continue; } + this.getMatrixAt( instanceId, _instanceLocalMatrix ); - intersects.push( { + _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + // the mesh represents this single instance - } ); + _mesh.matrixWorld = _instanceWorldMatrix; - } + _mesh.raycast( raycaster, _instanceIntersects ); - } else { + // process the result of raycast - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + for ( var i = 0, l = _instanceIntersects.length; i < l; i ++ ) { - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + var intersect = _instanceIntersects[ i ]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push( intersect ); - var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + } - if ( distSq > localPrecisionSq ) { continue; } + _instanceIntersects.length = 0; - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + } - var distance = raycaster.ray.origin.distanceTo( interRay ); + }, - if ( distance < raycaster.near || distance > raycaster.far ) { continue; } + setMatrixAt: function ( index, matrix ) { - intersects.push( { + matrix.toArray( this.instanceMatrix.array, index * 16 ); - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + }, - } ); + updateMorphTargets: function () { - } + } - } +} ); - } else if ( geometry.isGeometry ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } + */ - var vertices = geometry.vertices; - var nbVertices = vertices.length; +function LineBasicMaterial( parameters ) { - for ( var i = 0; i < nbVertices - 1; i += step ) { + Material.call( this ); - var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + this.type = 'LineBasicMaterial'; - if ( distSq > localPrecisionSq ) { continue; } + this.color = new Color( 0xffffff ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - var distance = raycaster.ray.origin.distanceTo( interRay ); + this.morphTargets = false; - if ( distance < raycaster.near || distance > raycaster.far ) { continue; } + this.setValues( parameters ); - intersects.push( { +} - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this +LineBasicMaterial.prototype = Object.create( Material.prototype ); +LineBasicMaterial.prototype.constructor = LineBasicMaterial; - } ); +LineBasicMaterial.prototype.isLineBasicMaterial = true; - } +LineBasicMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - }, + this.color.copy( source.color ); - clone: function () { + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - return new this.constructor( this.geometry, this.material ).copy( this ); + this.morphTargets = source.morphTargets; - } + return this; - } ); +}; - /** - * @author mrdoob / http://mrdoob.com/ - */ +/** + * @author mrdoob / http://mrdoob.com/ + */ - var _start$1 = new Vector3(); - var _end$1 = new Vector3(); +var _start = new Vector3(); +var _end = new Vector3(); +var _inverseMatrix$1 = new Matrix4(); +var _ray$1 = new Ray(); +var _sphere$2 = new Sphere(); - function LineSegments( geometry, material ) { +function Line( geometry, material, mode ) { - Line.call( this, geometry, material ); + if ( mode === 1 ) { - this.type = 'LineSegments'; + console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' ); } - LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + Object3D.call( this ); - constructor: LineSegments, + this.type = 'Line'; - isLineSegments: true, + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial(); - computeLineDistances: function () { + this.updateMorphTargets(); - var geometry = this.geometry; +} - if ( geometry.isBufferGeometry ) { +Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - // we assume non-indexed geometry + constructor: Line, - if ( geometry.index === null ) { + isLine: true, - var positionAttribute = geometry.attributes.position; - var lineDistances = []; + computeLineDistances: function () { - for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) { + var geometry = this.geometry; - _start$1.fromBufferAttribute( positionAttribute, i ); - _end$1.fromBufferAttribute( positionAttribute, i + 1 ); + if ( geometry.isBufferGeometry ) { - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + var positionAttribute = geometry.attributes.position; + var lineDistances = [ 0 ]; - } else { + for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) { - console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); + _start.fromBufferAttribute( positionAttribute, i - 1 ); + _end.fromBufferAttribute( positionAttribute, i ); + + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += _start.distanceTo( _end ); } - } else if ( geometry.isGeometry ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); + + } else { + + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - var vertices = geometry.vertices; - var lineDistances = geometry.lineDistances; + } - for ( var i = 0, l = vertices.length; i < l; i += 2 ) { + } else if ( geometry.isGeometry ) { - _start$1.copy( vertices[ i ] ); - _end$1.copy( vertices[ i + 1 ] ); + var vertices = geometry.vertices; + var lineDistances = geometry.lineDistances; - lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; - lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); + lineDistances[ 0 ] = 0; - } + for ( var i = 1, l = vertices.length; i < l; i ++ ) { - } + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] ); - return this; + } } - } ); + return this; - /** - * @author mgreter / http://github.com/mgreter - */ + }, + + raycast: function ( raycaster, intersects ) { - function LineLoop( geometry, material ) { + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Line.threshold; - Line.call( this, geometry, material ); + // Checking boundingSphere distance to ray - this.type = 'LineLoop'; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - } + _sphere$2.copy( geometry.boundingSphere ); + _sphere$2.applyMatrix4( matrixWorld ); + _sphere$2.radius += threshold; - LineLoop.prototype = Object.assign( Object.create( Line.prototype ), { + if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return; - constructor: LineLoop, + // - isLineLoop: true, + _inverseMatrix$1.getInverse( matrixWorld ); + _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); - } ); + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * alphaMap: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * - * morphTargets: - * } - */ + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = ( this && this.isLineSegments ) ? 2 : 1; - function PointsMaterial( parameters ) { + if ( geometry.isBufferGeometry ) { - Material.call( this ); + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - this.type = 'PointsMaterial'; + if ( index !== null ) { - this.color = new Color( 0xffffff ); + var indices = index.array; - this.map = null; + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - this.alphaMap = null; + var a = indices[ i ]; + var b = indices[ i + 1 ]; - this.size = 1; - this.sizeAttenuation = true; + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - this.morphTargets = false; + var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - this.setValues( parameters ); + if ( distSq > localThresholdSq ) continue; - } + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - PointsMaterial.prototype = Object.create( Material.prototype ); - PointsMaterial.prototype.constructor = PointsMaterial; + var distance = raycaster.ray.origin.distanceTo( interRay ); - PointsMaterial.prototype.isPointsMaterial = true; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - PointsMaterial.prototype.copy = function ( source ) { + intersects.push( { - Material.prototype.copy.call( this, source ); + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - this.color.copy( source.color ); + } ); - this.map = source.map; + } - this.alphaMap = source.alphaMap; + } else { - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { - this.morphTargets = source.morphTargets; + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - return this; + var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - }; + if ( distSq > localThresholdSq ) continue; - /** - * @author alteredq / http://alteredqualia.com/ - */ + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - var _inverseMatrix$2 = new Matrix4(); - var _ray$2 = new Ray(); - var _sphere$3 = new Sphere(); - var _position$1 = new Vector3(); + var distance = raycaster.ray.origin.distanceTo( interRay ); - function Points( geometry, material ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - Object3D.call( this ); + intersects.push( { - this.type = 'Points'; + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); + } ); - this.updateMorphTargets(); + } - } + } - Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + } else if ( geometry.isGeometry ) { - constructor: Points, + var vertices = geometry.vertices; + var nbVertices = vertices.length; - isPoints: true, + for ( var i = 0; i < nbVertices - 1; i += step ) { - raycast: function ( raycaster, intersects ) { + var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + if ( distSq > localThresholdSq ) continue; - // Checking boundingSphere distance to ray + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } + var distance = raycaster.ray.origin.distanceTo( interRay ); - _sphere$3.copy( geometry.boundingSphere ); - _sphere$3.applyMatrix4( matrixWorld ); - _sphere$3.radius += threshold; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; } + intersects.push( { - // + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - _inverseMatrix$2.getInverse( matrixWorld ); - _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); + } ); - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; + } - if ( geometry.isBufferGeometry ) { + } - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + }, - if ( index !== null ) { + updateMorphTargets: function () { - var indices = index.array; + var geometry = this.geometry; + var m, ml, name; - for ( var i = 0, il = indices.length; i < il; i ++ ) { + if ( geometry.isBufferGeometry ) { - var a = indices[ i ]; + var morphAttributes = geometry.morphAttributes; + var keys = Object.keys( morphAttributes ); - _position$1.fromArray( positions, a * 3 ); + if ( keys.length > 0 ) { - testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); + var morphAttribute = morphAttributes[ keys[ 0 ] ]; - } + if ( morphAttribute !== undefined ) { - } else { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - _position$1.fromArray( positions, i * 3 ); + name = morphAttribute[ m ].name || String( m ); - testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; } } - } else { + } - var vertices = geometry.vertices; + } else { - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + var morphTargets = geometry.morphTargets; - testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this ); + if ( morphTargets !== undefined && morphTargets.length > 0 ) { - } + console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); } - }, - - updateMorphTargets: function () { + } - var geometry = this.geometry; - var m, ml, name; + }, - if ( geometry.isBufferGeometry ) { + clone: function () { - var morphAttributes = geometry.morphAttributes; - var keys = Object.keys( morphAttributes ); + return new this.constructor( this.geometry, this.material ).copy( this ); - if ( keys.length > 0 ) { + } - var morphAttribute = morphAttributes[ keys[ 0 ] ]; +} ); - if ( morphAttribute !== undefined ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; +var _start$1 = new Vector3(); +var _end$1 = new Vector3(); - for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { +function LineSegments( geometry, material ) { - name = morphAttribute[ m ].name || String( m ); + Line.call( this, geometry, material ); - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + this.type = 'LineSegments'; - } +} - } +LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - } + constructor: LineSegments, - } else { + isLineSegments: true, - var morphTargets = geometry.morphTargets; + computeLineDistances: function () { - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + var geometry = this.geometry; - console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); + if ( geometry.isBufferGeometry ) { - } + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - }, + var positionAttribute = geometry.attributes.position; + var lineDistances = []; - clone: function () { + for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) { - return new this.constructor( this.geometry, this.material ).copy( this ); + _start$1.fromBufferAttribute( positionAttribute, i ); + _end$1.fromBufferAttribute( positionAttribute, i + 1 ); - } + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); - } ); + } - function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { + geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); - var rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); + } else { - if ( rayPointDistanceSq < localThresholdSq ) { + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - var intersectPoint = new Vector3(); + } - _ray$2.closestPointToPoint( point, intersectPoint ); - intersectPoint.applyMatrix4( matrixWorld ); + } else if ( geometry.isGeometry ) { - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + var vertices = geometry.vertices; + var lineDistances = geometry.lineDistances; - if ( distance < raycaster.near || distance > raycaster.far ) { return; } + for ( var i = 0, l = vertices.length; i < l; i += 2 ) { - intersects.push( { + _start$1.copy( vertices[ i ] ); + _end$1.copy( vertices[ i + 1 ] ); - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint, - index: index, - face: null, - object: object + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); - } ); + } } + return this; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ +} ); - function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { +/** + * @author mgreter / http://github.com/mgreter + */ - Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); +function LineLoop( geometry, material ) { - this.format = format !== undefined ? format : RGBFormat; + Line.call( this, geometry, material ); - this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.type = 'LineLoop'; - this.generateMipmaps = false; +} - } +LineLoop.prototype = Object.assign( Object.create( Line.prototype ), { - VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), { + constructor: LineLoop, - constructor: VideoTexture, + isLineLoop: true, - isVideoTexture: true, +} ); - update: function () { +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * alphaMap: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * + * morphTargets: + * } + */ - var video = this.image; +function PointsMaterial( parameters ) { - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + Material.call( this ); - this.needsUpdate = true; + this.type = 'PointsMaterial'; - } + this.color = new Color( 0xffffff ); - } + this.map = null; - } ); + this.alphaMap = null; - /** - * @author alteredq / http://alteredqualia.com/ - */ + this.size = 1; + this.sizeAttenuation = true; - function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + this.morphTargets = false; - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + this.setValues( parameters ); - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; +} - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) +PointsMaterial.prototype = Object.create( Material.prototype ); +PointsMaterial.prototype.constructor = PointsMaterial; - this.flipY = false; +PointsMaterial.prototype.isPointsMaterial = true; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files +PointsMaterial.prototype.copy = function ( source ) { - this.generateMipmaps = false; + Material.prototype.copy.call( this, source ); - } + this.color.copy( source.color ); - CompressedTexture.prototype = Object.create( Texture.prototype ); - CompressedTexture.prototype.constructor = CompressedTexture; + this.map = source.map; - CompressedTexture.prototype.isCompressedTexture = true; + this.alphaMap = source.alphaMap; - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + this.morphTargets = source.morphTargets; - Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + return this; - this.needsUpdate = true; +}; - } +/** + * @author alteredq / http://alteredqualia.com/ + */ - CanvasTexture.prototype = Object.create( Texture.prototype ); - CanvasTexture.prototype.constructor = CanvasTexture; - CanvasTexture.prototype.isCanvasTexture = true; +var _inverseMatrix$2 = new Matrix4(); +var _ray$2 = new Ray(); +var _sphere$3 = new Sphere(); +var _position$1 = new Vector3(); - /** - * @author Matt DesLauriers / @mattdesl - * @author atix / arthursilber.de - */ +function Points( geometry, material ) { - function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + Object3D.call( this ); - format = format !== undefined ? format : DepthFormat; + this.type = 'Points'; - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial(); - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); + this.updateMorphTargets(); - } +} - if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; } - if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; } +Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + constructor: Points, - this.image = { width: width, height: height }; + isPoints: true, - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + raycast: function ( raycaster, intersects ) { - this.flipY = false; - this.generateMipmaps = false; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; - } + // Checking boundingSphere distance to ray - DepthTexture.prototype = Object.create( Texture.prototype ); - DepthTexture.prototype.constructor = DepthTexture; - DepthTexture.prototype.isDepthTexture = true; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + _sphere$3.copy( geometry.boundingSphere ); + _sphere$3.applyMatrix4( matrixWorld ); + _sphere$3.radius += threshold; - function WireframeGeometry( geometry ) { + if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return; - BufferGeometry.call( this ); + // - this.type = 'WireframeGeometry'; + _inverseMatrix$2.getInverse( matrixWorld ); + _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); - // buffer + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; - var vertices = []; + if ( geometry.isBufferGeometry ) { - // helper variables + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; + + if ( index !== null ) { - var i, j, l, o, ol; - var edge = [ 0, 0 ], edges = {}, e, edge1, edge2; - var key, keys = [ 'a', 'b', 'c' ]; - var vertex; + var indices = index.array; - // different logic for Geometry and BufferGeometry + for ( var i = 0, il = indices.length; i < il; i ++ ) { - if ( geometry && geometry.isGeometry ) { + var a = indices[ i ]; - // create a data structure that contains all edges without duplicates + _position$1.fromArray( positions, a * 3 ); - var faces = geometry.faces; + testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); - for ( i = 0, l = faces.length; i < l; i ++ ) { + } - var face = faces[ i ]; + } else { - for ( j = 0; j < 3; j ++ ) { + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - edge1 = face[ keys[ j ] ]; - edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + _position$1.fromArray( positions, i * 3 ); - key = edge[ 0 ] + ',' + edge[ 1 ]; + testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); - if ( edges[ key ] === undefined ) { + } - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + } - } + } else { - } + var vertices = geometry.vertices; + + for ( var i = 0, l = vertices.length; i < l; i ++ ) { + + testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this ); } - // generate vertices + } - for ( key in edges ) { + }, - e = edges[ key ]; + updateMorphTargets: function () { - vertex = geometry.vertices[ e.index1 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + var geometry = this.geometry; + var m, ml, name; - vertex = geometry.vertices[ e.index2 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( geometry.isBufferGeometry ) { - } + var morphAttributes = geometry.morphAttributes; + var keys = Object.keys( morphAttributes ); - } else if ( geometry && geometry.isBufferGeometry ) { + if ( keys.length > 0 ) { - var position, indices, groups; - var group, start, count; - var index1, index2; + var morphAttribute = morphAttributes[ keys[ 0 ] ]; - vertex = new Vector3(); + if ( morphAttribute !== undefined ) { - if ( geometry.index !== null ) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - // indexed BufferGeometry + for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - position = geometry.attributes.position; - indices = geometry.index; - groups = geometry.groups; + name = morphAttribute[ m ].name || String( m ); - if ( groups.length === 0 ) { + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; - groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + } } - // create a data structure that contains all eges without duplicates + } - for ( o = 0, ol = groups.length; o < ol; ++ o ) { + } else { - group = groups[ o ]; + var morphTargets = geometry.morphTargets; - start = group.start; - count = group.count; + if ( morphTargets !== undefined && morphTargets.length > 0 ) { - for ( i = start, l = ( start + count ); i < l; i += 3 ) { + console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); - for ( j = 0; j < 3; j ++ ) { + } - edge1 = indices.getX( i + j ); - edge2 = indices.getX( i + ( j + 1 ) % 3 ); - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + } - key = edge[ 0 ] + ',' + edge[ 1 ]; + }, - if ( edges[ key ] === undefined ) { + clone: function () { - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + return new this.constructor( this.geometry, this.material ).copy( this ); - } + } - } +} ); - } +function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { - } + var rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); - // generate vertices + if ( rayPointDistanceSq < localThresholdSq ) { - for ( key in edges ) { + var intersectPoint = new Vector3(); - e = edges[ key ]; + _ray$2.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); - vertex.fromBufferAttribute( position, e.index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - vertex.fromBufferAttribute( position, e.index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - } + intersects.push( { - } else { + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint, + index: index, + face: null, + object: object - // non-indexed BufferGeometry + } ); - position = geometry.attributes.position; + } - for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) { +} - for ( j = 0; j < 3; j ++ ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - // three edges per triangle, an edge is represented as (index1, index2) - // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) +function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - index1 = 3 * i + j; - vertex.fromBufferAttribute( position, index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - index2 = 3 * i + ( ( j + 1 ) % 3 ); - vertex.fromBufferAttribute( position, index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + this.format = format !== undefined ? format : RGBFormat; - } + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - } + this.generateMipmaps = false; - } +} - } +VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), { - // build geometry + constructor: VideoTexture, - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + isVideoTexture: true, - } + update: function () { - WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); - WireframeGeometry.prototype.constructor = WireframeGeometry; + var video = this.image; - /** - * @author zz85 / https://github.com/zz85 - * @author Mugen87 / https://github.com/Mugen87 - * - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 - */ + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { - // ParametricGeometry + this.needsUpdate = true; - function ParametricGeometry( func, slices, stacks ) { + } - Geometry.call( this ); + } - this.type = 'ParametricGeometry'; +} ); - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; +/** + * @author alteredq / http://alteredqualia.com/ + */ - this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) ); - this.mergeVertices(); +function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - } + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - ParametricGeometry.prototype = Object.create( Geometry.prototype ); - ParametricGeometry.prototype.constructor = ParametricGeometry; + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - // ParametricBufferGeometry + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - function ParametricBufferGeometry( func, slices, stacks ) { + this.flipY = false; - BufferGeometry.call( this ); + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files - this.type = 'ParametricBufferGeometry'; + this.generateMipmaps = false; - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; +} - // buffers +CompressedTexture.prototype = Object.create( Texture.prototype ); +CompressedTexture.prototype.constructor = CompressedTexture; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; +CompressedTexture.prototype.isCompressedTexture = true; - var EPS = 0.00001; +/** + * @author mrdoob / http://mrdoob.com/ + */ - var normal = new Vector3(); +function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - var p0 = new Vector3(), p1 = new Vector3(); - var pu = new Vector3(), pv = new Vector3(); + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - var i, j; + this.needsUpdate = true; - if ( func.length < 3 ) { +} - console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); +CanvasTexture.prototype = Object.create( Texture.prototype ); +CanvasTexture.prototype.constructor = CanvasTexture; +CanvasTexture.prototype.isCanvasTexture = true; - } +/** + * @author Matt DesLauriers / @mattdesl + * @author atix / arthursilber.de + */ - // generate vertices, normals and uvs +function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - var sliceCount = slices + 1; + format = format !== undefined ? format : DepthFormat; - for ( i = 0; i <= stacks; i ++ ) { + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - var v = i / stacks; + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); - for ( j = 0; j <= slices; j ++ ) { + } - var u = j / slices; + if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; - // vertex + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - func( u, v, p0 ); - vertices.push( p0.x, p0.y, p0.z ); + this.image = { width: width, height: height }; - // normal + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - // approximate tangent vectors via finite differences + this.flipY = false; + this.generateMipmaps = false; - if ( u - EPS >= 0 ) { +} - func( u - EPS, v, p1 ); - pu.subVectors( p0, p1 ); +DepthTexture.prototype = Object.create( Texture.prototype ); +DepthTexture.prototype.constructor = DepthTexture; +DepthTexture.prototype.isDepthTexture = true; - } else { +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - func( u + EPS, v, p1 ); - pu.subVectors( p1, p0 ); +function WireframeGeometry( geometry ) { - } + BufferGeometry.call( this ); - if ( v - EPS >= 0 ) { + this.type = 'WireframeGeometry'; - func( u, v - EPS, p1 ); - pv.subVectors( p0, p1 ); + // buffer - } else { + var vertices = []; - func( u, v + EPS, p1 ); - pv.subVectors( p1, p0 ); + // helper variables - } + var i, j, l, o, ol; + var edge = [ 0, 0 ], edges = {}, e, edge1, edge2; + var key, keys = [ 'a', 'b', 'c' ]; + var vertex; - // cross product of tangent vectors returns surface normal + // different logic for Geometry and BufferGeometry - normal.crossVectors( pu, pv ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + if ( geometry && geometry.isGeometry ) { - // uv + // create a data structure that contains all edges without duplicates - uvs.push( u, v ); + var faces = geometry.faces; - } + for ( i = 0, l = faces.length; i < l; i ++ ) { - } + var face = faces[ i ]; - // generate indices + for ( j = 0; j < 3; j ++ ) { - for ( i = 0; i < stacks; i ++ ) { + edge1 = face[ keys[ j ] ]; + edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; + edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates + edge[ 1 ] = Math.max( edge1, edge2 ); - for ( j = 0; j < slices; j ++ ) { + key = edge[ 0 ] + ',' + edge[ 1 ]; - var a = i * sliceCount + j; - var b = i * sliceCount + j + 1; - var c = ( i + 1 ) * sliceCount + j + 1; - var d = ( i + 1 ) * sliceCount + j; + if ( edges[ key ] === undefined ) { - // faces one and two + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; - indices.push( a, b, d ); - indices.push( b, c, d ); + } } } - // build geometry + // generate vertices - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + for ( key in edges ) { - } + e = edges[ key ]; - ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry; + vertex = geometry.vertices[ e.index1 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - /** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley - * @author Mugen87 / https://github.com/Mugen87 - */ + vertex = geometry.vertices[ e.index2 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - // PolyhedronGeometry + } - function PolyhedronGeometry( vertices, indices, radius, detail ) { + } else if ( geometry && geometry.isBufferGeometry ) { - Geometry.call( this ); + var position, indices, groups; + var group, start, count; + var index1, index2; - this.type = 'PolyhedronGeometry'; + vertex = new Vector3(); - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + if ( geometry.index !== null ) { - this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) ); - this.mergeVertices(); + // indexed BufferGeometry - } + position = geometry.attributes.position; + indices = geometry.index; + groups = geometry.groups; + + if ( groups.length === 0 ) { - PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); - PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; - // PolyhedronBufferGeometry + } - function PolyhedronBufferGeometry( vertices, indices, radius, detail ) { + // create a data structure that contains all eges without duplicates - BufferGeometry.call( this ); + for ( o = 0, ol = groups.length; o < ol; ++ o ) { - this.type = 'PolyhedronBufferGeometry'; + group = groups[ o ]; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + start = group.start; + count = group.count; - radius = radius || 1; - detail = detail || 0; + for ( i = start, l = ( start + count ); i < l; i += 3 ) { - // default buffer data + for ( j = 0; j < 3; j ++ ) { - var vertexBuffer = []; - var uvBuffer = []; + edge1 = indices.getX( i + j ); + edge2 = indices.getX( i + ( j + 1 ) % 3 ); + edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates + edge[ 1 ] = Math.max( edge1, edge2 ); - // the subdivision creates the vertex buffer data + key = edge[ 0 ] + ',' + edge[ 1 ]; - subdivide( detail ); + if ( edges[ key ] === undefined ) { - // all vertices should lie on a conceptual sphere with a given radius + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; - applyRadius( radius ); + } - // finally, create the uv data + } - generateUVs(); + } - // build non-indexed geometry + } - this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + // generate vertices - if ( detail === 0 ) { + for ( key in edges ) { - this.computeVertexNormals(); // flat normals + e = edges[ key ]; - } else { + vertex.fromBufferAttribute( position, e.index1 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - this.normalizeNormals(); // smooth normals + vertex.fromBufferAttribute( position, e.index2 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - } + } - // helper functions + } else { - function subdivide( detail ) { + // non-indexed BufferGeometry - var a = new Vector3(); - var b = new Vector3(); - var c = new Vector3(); + position = geometry.attributes.position; - // iterate over all faces and apply a subdivison with the given detail value + for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) { - for ( var i = 0; i < indices.length; i += 3 ) { + for ( j = 0; j < 3; j ++ ) { - // get the vertices of the face + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) - getVertexByIndex( indices[ i + 0 ], a ); - getVertexByIndex( indices[ i + 1 ], b ); - getVertexByIndex( indices[ i + 2 ], c ); + index1 = 3 * i + j; + vertex.fromBufferAttribute( position, index1 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - // perform subdivision + index2 = 3 * i + ( ( j + 1 ) % 3 ); + vertex.fromBufferAttribute( position, index2 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - subdivideFace( a, b, c, detail ); + } } } - function subdivideFace( a, b, c, detail ) { - - var cols = Math.pow( 2, detail ); - - // we use this multidimensional array as a data structure for creating the subdivision + } - var v = []; + // build geometry - var i, j; + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - // construct all of the vertices for this subdivision +} - for ( i = 0; i <= cols; i ++ ) { +WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); +WireframeGeometry.prototype.constructor = WireframeGeometry; - v[ i ] = []; +/** + * @author zz85 / https://github.com/zz85 + * @author Mugen87 / https://github.com/Mugen87 + * + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html + */ - var aj = a.clone().lerp( c, i / cols ); - var bj = b.clone().lerp( c, i / cols ); +// ParametricGeometry - var rows = cols - i; +function ParametricGeometry( func, slices, stacks ) { - for ( j = 0; j <= rows; j ++ ) { + Geometry.call( this ); - if ( j === 0 && i === cols ) { + this.type = 'ParametricGeometry'; - v[ i ][ j ] = aj; + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - } else { + this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) ); + this.mergeVertices(); - v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); +} - } +ParametricGeometry.prototype = Object.create( Geometry.prototype ); +ParametricGeometry.prototype.constructor = ParametricGeometry; - } +// ParametricBufferGeometry - } +function ParametricBufferGeometry( func, slices, stacks ) { - // construct all of the faces + BufferGeometry.call( this ); - for ( i = 0; i < cols; i ++ ) { + this.type = 'ParametricBufferGeometry'; - for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + this.parameters = { + func: func, + slices: slices, + stacks: stacks + }; - var k = Math.floor( j / 2 ); + // buffers - if ( j % 2 === 0 ) { + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); - pushVertex( v[ i ][ k ] ); + var EPS = 0.00001; - } else { + var normal = new Vector3(); - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); + var p0 = new Vector3(), p1 = new Vector3(); + var pu = new Vector3(), pv = new Vector3(); - } + var i, j; - } + if ( func.length < 3 ) { - } + console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); - } + } - function applyRadius( radius ) { + // generate vertices, normals and uvs - var vertex = new Vector3(); + var sliceCount = slices + 1; - // iterate over the entire buffer and apply the radius to each vertex + for ( i = 0; i <= stacks; i ++ ) { - for ( var i = 0; i < vertexBuffer.length; i += 3 ) { + var v = i / stacks; - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + for ( j = 0; j <= slices; j ++ ) { - vertex.normalize().multiplyScalar( radius ); + var u = j / slices; - vertexBuffer[ i + 0 ] = vertex.x; - vertexBuffer[ i + 1 ] = vertex.y; - vertexBuffer[ i + 2 ] = vertex.z; + // vertex - } + func( u, v, p0 ); + vertices.push( p0.x, p0.y, p0.z ); - } + // normal - function generateUVs() { + // approximate tangent vectors via finite differences - var vertex = new Vector3(); + if ( u - EPS >= 0 ) { - for ( var i = 0; i < vertexBuffer.length; i += 3 ) { + func( u - EPS, v, p1 ); + pu.subVectors( p0, p1 ); - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + } else { - var u = azimuth( vertex ) / 2 / Math.PI + 0.5; - var v = inclination( vertex ) / Math.PI + 0.5; - uvBuffer.push( u, 1 - v ); + func( u + EPS, v, p1 ); + pu.subVectors( p1, p0 ); } - correctUVs(); + if ( v - EPS >= 0 ) { - correctSeam(); + func( u, v - EPS, p1 ); + pv.subVectors( p0, p1 ); - } + } else { - function correctSeam() { + func( u, v + EPS, p1 ); + pv.subVectors( p1, p0 ); - // handle case when face straddles the seam, see #3269 + } - for ( var i = 0; i < uvBuffer.length; i += 6 ) { + // cross product of tangent vectors returns surface normal - // uv data of a single face + normal.crossVectors( pu, pv ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - var x0 = uvBuffer[ i + 0 ]; - var x1 = uvBuffer[ i + 2 ]; - var x2 = uvBuffer[ i + 4 ]; + // uv - var max = Math.max( x0, x1, x2 ); - var min = Math.min( x0, x1, x2 ); + uvs.push( u, v ); - // 0.9 is somewhat arbitrary + } - if ( max > 0.9 && min < 0.1 ) { + } - if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; } - if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; } - if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; } + // generate indices - } + for ( i = 0; i < stacks; i ++ ) { - } + for ( j = 0; j < slices; j ++ ) { - } + var a = i * sliceCount + j; + var b = i * sliceCount + j + 1; + var c = ( i + 1 ) * sliceCount + j + 1; + var d = ( i + 1 ) * sliceCount + j; - function pushVertex( vertex ) { + // faces one and two - vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + indices.push( a, b, d ); + indices.push( b, c, d ); } - function getVertexByIndex( index, vertex ) { - - var stride = index * 3; - - vertex.x = vertices[ stride + 0 ]; - vertex.y = vertices[ stride + 1 ]; - vertex.z = vertices[ stride + 2 ]; - - } + } - function correctUVs() { + // build geometry - var a = new Vector3(); - var b = new Vector3(); - var c = new Vector3(); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - var centroid = new Vector3(); +} - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); +ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry; - for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { +/** + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley + * @author Mugen87 / https://github.com/Mugen87 + */ - a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); - b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); - c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); +// PolyhedronGeometry - uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); - uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); - uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); +function PolyhedronGeometry( vertices, indices, radius, detail ) { - centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + Geometry.call( this ); - var azi = azimuth( centroid ); + this.type = 'PolyhedronGeometry'; - correctUV( uvA, j + 0, a, azi ); - correctUV( uvB, j + 2, b, azi ); - correctUV( uvC, j + 4, c, azi ); + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - } + this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) ); + this.mergeVertices(); - } +} - function correctUV( uv, stride, vector, azimuth ) { +PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); +PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { +// PolyhedronBufferGeometry - uvBuffer[ stride ] = uv.x - 1; +function PolyhedronBufferGeometry( vertices, indices, radius, detail ) { - } + BufferGeometry.call( this ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + this.type = 'PolyhedronBufferGeometry'; - uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + this.parameters = { + vertices: vertices, + indices: indices, + radius: radius, + detail: detail + }; - } + radius = radius || 1; + detail = detail || 0; - } + // default buffer data - // Angle around the Y axis, counter-clockwise when looking from above. + var vertexBuffer = []; + var uvBuffer = []; - function azimuth( vector ) { + // the subdivision creates the vertex buffer data - return Math.atan2( vector.z, - vector.x ); + subdivide( detail ); - } + // all vertices should lie on a conceptual sphere with a given radius + applyRadius( radius ); - // Angle above the XZ plane. + // finally, create the uv data - function inclination( vector ) { + generateUVs(); - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + // build non-indexed geometry - } + this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); - } + if ( detail === 0 ) { - PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry; + this.computeVertexNormals(); // flat normals - /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 - */ + } else { - // TetrahedronGeometry + this.normalizeNormals(); // smooth normals - function TetrahedronGeometry( radius, detail ) { + } - Geometry.call( this ); + // helper functions - this.type = 'TetrahedronGeometry'; + function subdivide( detail ) { - this.parameters = { - radius: radius, - detail: detail - }; + var a = new Vector3(); + var b = new Vector3(); + var c = new Vector3(); - this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + // iterate over all faces and apply a subdivison with the given detail value - } + for ( var i = 0; i < indices.length; i += 3 ) { - TetrahedronGeometry.prototype = Object.create( Geometry.prototype ); - TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; + // get the vertices of the face - // TetrahedronBufferGeometry + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); - function TetrahedronBufferGeometry( radius, detail ) { + // perform subdivision - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + subdivideFace( a, b, c, detail ); - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + } - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + } - this.type = 'TetrahedronBufferGeometry'; + function subdivideFace( a, b, c, detail ) { - this.parameters = { - radius: radius, - detail: detail - }; + var cols = Math.pow( 2, detail ); - } + // we use this multidimensional array as a data structure for creating the subdivision - TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry; + var v = []; - /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 - */ + var i, j; - // OctahedronGeometry + // construct all of the vertices for this subdivision - function OctahedronGeometry( radius, detail ) { + for ( i = 0; i <= cols; i ++ ) { - Geometry.call( this ); + v[ i ] = []; - this.type = 'OctahedronGeometry'; + var aj = a.clone().lerp( c, i / cols ); + var bj = b.clone().lerp( c, i / cols ); - this.parameters = { - radius: radius, - detail: detail - }; + var rows = cols - i; - this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + for ( j = 0; j <= rows; j ++ ) { - } + if ( j === 0 && i === cols ) { - OctahedronGeometry.prototype = Object.create( Geometry.prototype ); - OctahedronGeometry.prototype.constructor = OctahedronGeometry; + v[ i ][ j ] = aj; - // OctahedronBufferGeometry + } else { - function OctahedronBufferGeometry( radius, detail ) { + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, - 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + } - var indices = [ - 0, 2, 4, 0, 4, 3, 0, 3, 5, - 0, 5, 2, 1, 2, 5, 1, 5, 3, - 1, 3, 4, 1, 4, 2 - ]; + } - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + } - this.type = 'OctahedronBufferGeometry'; + // construct all of the faces - this.parameters = { - radius: radius, - detail: detail - }; + for ( i = 0; i < cols; i ++ ) { - } + for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry; + var k = Math.floor( j / 2 ); - /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 - */ + if ( j % 2 === 0 ) { - // IcosahedronGeometry + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); - function IcosahedronGeometry( radius, detail ) { + } else { - Geometry.call( this ); + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); - this.type = 'IcosahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + } - this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + } } - IcosahedronGeometry.prototype = Object.create( Geometry.prototype ); - IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; + function applyRadius( radius ) { - // IcosahedronBufferGeometry - - function IcosahedronBufferGeometry( radius, detail ) { + var vertex = new Vector3(); - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + // iterate over the entire buffer and apply the radius to each vertex - var vertices = [ - - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, - 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, - t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 - ]; + for ( var i = 0; i < vertexBuffer.length; i += 3 ) { - var indices = [ - 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, - 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, - 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, - 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 - ]; + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + vertex.normalize().multiplyScalar( radius ); - this.type = 'IcosahedronBufferGeometry'; + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; - this.parameters = { - radius: radius, - detail: detail - }; + } } - IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry; + function generateUVs() { - /** - * @author Abe Pazos / https://hamoid.com - * @author Mugen87 / https://github.com/Mugen87 - */ + var vertex = new Vector3(); - // DodecahedronGeometry + for ( var i = 0; i < vertexBuffer.length; i += 3 ) { - function DodecahedronGeometry( radius, detail ) { + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - Geometry.call( this ); + var u = azimuth( vertex ) / 2 / Math.PI + 0.5; + var v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); - this.type = 'DodecahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + correctUVs(); - this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + correctSeam(); } - DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); - DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; + function correctSeam() { - // DodecahedronBufferGeometry + // handle case when face straddles the seam, see #3269 - function DodecahedronBufferGeometry( radius, detail ) { + for ( var i = 0; i < uvBuffer.length; i += 6 ) { - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var r = 1 / t; + // uv data of a single face - var vertices = [ + var x0 = uvBuffer[ i + 0 ]; + var x1 = uvBuffer[ i + 2 ]; + var x2 = uvBuffer[ i + 4 ]; - // (±1, ±1, ±1) - - 1, - 1, - 1, - 1, - 1, 1, - - 1, 1, - 1, - 1, 1, 1, - 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, 1, 1, 1, + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, + // 0.9 is somewhat arbitrary - // (±1/φ, ±φ, 0) - - r, - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, + if ( max > 0.9 && min < 0.1 ) { - // (±φ, 0, ±1/φ) - - t, 0, - r, t, 0, - r, - - t, 0, r, t, 0, r - ]; + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; - var indices = [ - 3, 11, 7, 3, 7, 15, 3, 15, 13, - 7, 19, 17, 7, 17, 6, 7, 6, 15, - 17, 4, 8, 17, 8, 10, 17, 10, 6, - 8, 0, 16, 8, 16, 2, 8, 2, 10, - 0, 12, 1, 0, 1, 18, 0, 18, 16, - 6, 10, 2, 6, 2, 13, 6, 13, 15, - 2, 16, 18, 2, 18, 3, 2, 3, 13, - 18, 1, 9, 18, 9, 11, 18, 11, 3, - 4, 14, 12, 4, 12, 0, 4, 0, 8, - 11, 9, 5, 11, 5, 19, 11, 19, 7, - 19, 5, 14, 19, 14, 4, 19, 4, 17, - 1, 12, 14, 1, 14, 5, 1, 5, 9 - ]; + } - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + } - this.type = 'DodecahedronBufferGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + function pushVertex( vertex ) { + + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); } - DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; + function getVertexByIndex( index, vertex ) { - /** - * @author oosmoxiecode / https://github.com/oosmoxiecode - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * @author jonobr1 / https://github.com/jonobr1 - * @author Mugen87 / https://github.com/Mugen87 - * - */ + var stride = index * 3; - // TubeGeometry + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; - function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) { + } - Geometry.call( this ); + function correctUVs() { - this.type = 'TubeGeometry'; + var a = new Vector3(); + var b = new Vector3(); + var c = new Vector3(); - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + var centroid = new Vector3(); - if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); } + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ); + for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { - // expose internals + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); - this.tangents = bufferGeometry.tangents; - this.normals = bufferGeometry.normals; - this.binormals = bufferGeometry.binormals; + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); - // create geometry + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); - this.fromBufferGeometry( bufferGeometry ); - this.mergeVertices(); + var azi = azimuth( centroid ); + + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); + + } } - TubeGeometry.prototype = Object.create( Geometry.prototype ); - TubeGeometry.prototype.constructor = TubeGeometry; + function correctUV( uv, stride, vector, azimuth ) { - // TubeBufferGeometry + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { - function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) { + uvBuffer[ stride ] = uv.x - 1; - BufferGeometry.call( this ); + } - this.type = 'TubeBufferGeometry'; + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; - tubularSegments = tubularSegments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; + } - var frames = path.computeFrenetFrames( tubularSegments, closed ); + } - // expose internals + // Angle around the Y axis, counter-clockwise when looking from above. - this.tangents = frames.tangents; - this.normals = frames.normals; - this.binormals = frames.binormals; + function azimuth( vector ) { - // helper variables + return Math.atan2( vector.z, - vector.x ); - var vertex = new Vector3(); - var normal = new Vector3(); - var uv = new Vector2(); - var P = new Vector3(); + } - var i, j; - // buffer + // Angle above the XZ plane. - var vertices = []; - var normals = []; - var uvs = []; - var indices = []; + function inclination( vector ) { - // create buffer data + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - generateBufferData(); + } - // build geometry +} - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); +PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry; - // functions +/** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - function generateBufferData() { +// TetrahedronGeometry - for ( i = 0; i < tubularSegments; i ++ ) { +function TetrahedronGeometry( radius, detail ) { - generateSegment( i ); + Geometry.call( this ); - } + this.type = 'TetrahedronGeometry'; - // if the geometry is not closed, generate the last row of vertices and normals - // at the regular position on the given path - // - // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + this.parameters = { + radius: radius, + detail: detail + }; - generateSegment( ( closed === false ) ? tubularSegments : 0 ); + this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - // uvs are generated in a separate function. - // this makes it easy compute correct values for closed geometries +} - generateUVs(); +TetrahedronGeometry.prototype = Object.create( Geometry.prototype ); +TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; - // finally create faces +// TetrahedronBufferGeometry - generateIndices(); +function TetrahedronBufferGeometry( radius, detail ) { - } + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - function generateSegment( i ) { + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - // we use getPointAt to sample evenly distributed points from the given path + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - P = path.getPointAt( i / tubularSegments, P ); + this.type = 'TetrahedronBufferGeometry'; - // retrieve corresponding normal and binormal + this.parameters = { + radius: radius, + detail: detail + }; - var N = frames.normals[ i ]; - var B = frames.binormals[ i ]; +} - // generate normals and vertices for the current segment +TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); +TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry; - for ( j = 0; j <= radialSegments; j ++ ) { +/** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - var v = j / radialSegments * Math.PI * 2; +// OctahedronGeometry - var sin = Math.sin( v ); - var cos = - Math.cos( v ); +function OctahedronGeometry( radius, detail ) { - // normal + Geometry.call( this ); - normal.x = ( cos * N.x + sin * B.x ); - normal.y = ( cos * N.y + sin * B.y ); - normal.z = ( cos * N.z + sin * B.z ); - normal.normalize(); + this.type = 'OctahedronGeometry'; - normals.push( normal.x, normal.y, normal.z ); + this.parameters = { + radius: radius, + detail: detail + }; - // vertex + this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - vertex.x = P.x + radius * normal.x; - vertex.y = P.y + radius * normal.y; - vertex.z = P.z + radius * normal.z; +} - vertices.push( vertex.x, vertex.y, vertex.z ); +OctahedronGeometry.prototype = Object.create( Geometry.prototype ); +OctahedronGeometry.prototype.constructor = OctahedronGeometry; - } +// OctahedronBufferGeometry - } +function OctahedronBufferGeometry( radius, detail ) { - function generateIndices() { + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - for ( j = 1; j <= tubularSegments; j ++ ) { + var indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, + 0, 5, 2, 1, 2, 5, 1, 5, 3, + 1, 3, 4, 1, 4, 2 + ]; - for ( i = 1; i <= radialSegments; i ++ ) { + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + this.type = 'OctahedronBufferGeometry'; - // faces + this.parameters = { + radius: radius, + detail: detail + }; - indices.push( a, b, d ); - indices.push( b, c, d ); +} - } +OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); +OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry; - } +/** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - } +// IcosahedronGeometry - function generateUVs() { +function IcosahedronGeometry( radius, detail ) { - for ( i = 0; i <= tubularSegments; i ++ ) { + Geometry.call( this ); - for ( j = 0; j <= radialSegments; j ++ ) { + this.type = 'IcosahedronGeometry'; - uv.x = i / tubularSegments; - uv.y = j / radialSegments; + this.parameters = { + radius: radius, + detail: detail + }; - uvs.push( uv.x, uv.y ); + this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - } +} - } +IcosahedronGeometry.prototype = Object.create( Geometry.prototype ); +IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; - } +// IcosahedronBufferGeometry - } +function IcosahedronBufferGeometry( radius, detail ) { - TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TubeBufferGeometry.prototype.constructor = TubeBufferGeometry; + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - TubeBufferGeometry.prototype.toJSON = function () { + var vertices = [ + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 + ]; - var data = BufferGeometry.prototype.toJSON.call( this ); + var indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; - data.path = this.parameters.path.toJSON(); + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - return data; + this.type = 'IcosahedronBufferGeometry'; + this.parameters = { + radius: radius, + detail: detail }; - /** - * @author oosmoxiecode - * @author Mugen87 / https://github.com/Mugen87 - * - * based on http://www.blackpawn.com/texts/pqtorus/ - */ +} - // TorusKnotGeometry +IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); +IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry; - function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { +/** + * @author Abe Pazos / https://hamoid.com + * @author Mugen87 / https://github.com/Mugen87 + */ - Geometry.call( this ); +// DodecahedronGeometry - this.type = 'TorusKnotGeometry'; +function DodecahedronGeometry( radius, detail ) { - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + Geometry.call( this ); - if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); } + this.type = 'DodecahedronGeometry'; - this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); - this.mergeVertices(); + this.parameters = { + radius: radius, + detail: detail + }; - } + this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); - TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; +} - // TorusKnotBufferGeometry +DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); +DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; - function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { +// DodecahedronBufferGeometry - BufferGeometry.call( this ); +function DodecahedronBufferGeometry( radius, detail ) { - this.type = 'TorusKnotBufferGeometry'; + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q - }; + var vertices = [ - radius = radius || 1; - tube = tube || 0.4; - tubularSegments = Math.floor( tubularSegments ) || 64; - radialSegments = Math.floor( radialSegments ) || 8; - p = p || 2; - q = q || 3; + // (±1, ±1, ±1) + - 1, - 1, - 1, - 1, - 1, 1, + - 1, 1, - 1, - 1, 1, 1, + 1, - 1, - 1, 1, - 1, 1, + 1, 1, - 1, 1, 1, 1, - // buffers + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, - // helper variables + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - var i, j; + var indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; - var vertex = new Vector3(); - var normal = new Vector3(); + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - var P1 = new Vector3(); - var P2 = new Vector3(); + this.type = 'DodecahedronBufferGeometry'; - var B = new Vector3(); - var T = new Vector3(); - var N = new Vector3(); + this.parameters = { + radius: radius, + detail: detail + }; - // generate vertices, normals and uvs +} - for ( i = 0; i <= tubularSegments; ++ i ) { +DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); +DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement +/** + * @author oosmoxiecode / https://github.com/oosmoxiecode + * @author WestLangley / https://github.com/WestLangley + * @author zz85 / https://github.com/zz85 + * @author miningold / https://github.com/miningold + * @author jonobr1 / https://github.com/jonobr1 + * @author Mugen87 / https://github.com/Mugen87 + * + */ - var u = i / tubularSegments * p * Math.PI * 2; +// TubeGeometry - // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. - // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions +function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) { - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + Geometry.call( this ); - // calculate orthonormal basis + this.type = 'TubeGeometry'; - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - // normalize B, N. T can be ignored, we don't use it + if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' ); - B.normalize(); - N.normalize(); + var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ); - for ( j = 0; j <= radialSegments; ++ j ) { + // expose internals - // now calculate the vertices. they are nothing more than an extrusion of the torus curve. - // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + this.tangents = bufferGeometry.tangents; + this.normals = bufferGeometry.normals; + this.binormals = bufferGeometry.binormals; - var v = j / radialSegments * Math.PI * 2; - var cx = - tube * Math.cos( v ); - var cy = tube * Math.sin( v ); + // create geometry - // now calculate the final vertex position. - // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve + this.fromBufferGeometry( bufferGeometry ); + this.mergeVertices(); - vertex.x = P1.x + ( cx * N.x + cy * B.x ); - vertex.y = P1.y + ( cx * N.y + cy * B.y ); - vertex.z = P1.z + ( cx * N.z + cy * B.z ); +} - vertices.push( vertex.x, vertex.y, vertex.z ); +TubeGeometry.prototype = Object.create( Geometry.prototype ); +TubeGeometry.prototype.constructor = TubeGeometry; - // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) +// TubeBufferGeometry - normal.subVectors( vertex, P1 ).normalize(); +function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) { - normals.push( normal.x, normal.y, normal.z ); + BufferGeometry.call( this ); - // uv + this.type = 'TubeBufferGeometry'; - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - } + tubularSegments = tubularSegments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; - } + var frames = path.computeFrenetFrames( tubularSegments, closed ); - // generate indices + // expose internals - for ( j = 1; j <= tubularSegments; j ++ ) { + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; - for ( i = 1; i <= radialSegments; i ++ ) { + // helper variables - // indices + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); + var P = new Vector3(); - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + var i, j; - // faces + // buffer - indices.push( a, b, d ); - indices.push( b, c, d ); + var vertices = []; + var normals = []; + var uvs = []; + var indices = []; - } + // create buffer data - } + generateBufferData(); - // build geometry + // build geometry - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - // this function calculates the current position on the torus curve + // functions - function calculatePositionOnCurve( u, p, q, radius, position ) { + function generateBufferData() { - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = q / p * u; - var cs = Math.cos( quOverP ); + for ( i = 0; i < tubularSegments; i ++ ) { - position.x = radius * ( 2 + cs ) * 0.5 * cu; - position.y = radius * ( 2 + cs ) * su * 0.5; - position.z = radius * Math.sin( quOverP ) * 0.5; + generateSegment( i ); } - } - - TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - - /** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ - - // TorusGeometry + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) - function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + generateSegment( ( closed === false ) ? tubularSegments : 0 ); - Geometry.call( this ); + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries - this.type = 'TorusGeometry'; + generateUVs(); - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; + // finally create faces - this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); - this.mergeVertices(); + generateIndices(); } - TorusGeometry.prototype = Object.create( Geometry.prototype ); - TorusGeometry.prototype.constructor = TorusGeometry; - - // TorusBufferGeometry - - function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - - BufferGeometry.call( this ); - - this.type = 'TorusBufferGeometry'; + function generateSegment( i ) { - this.parameters = { - radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc - }; - - radius = radius || 1; - tube = tube || 0.4; - radialSegments = Math.floor( radialSegments ) || 8; - tubularSegments = Math.floor( tubularSegments ) || 6; - arc = arc || Math.PI * 2; - - // buffers - - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + // we use getPointAt to sample evenly distributed points from the given path - // helper variables + P = path.getPointAt( i / tubularSegments, P ); - var center = new Vector3(); - var vertex = new Vector3(); - var normal = new Vector3(); + // retrieve corresponding normal and binormal - var j, i; + var N = frames.normals[ i ]; + var B = frames.binormals[ i ]; - // generate vertices, normals and uvs + // generate normals and vertices for the current segment for ( j = 0; j <= radialSegments; j ++ ) { - for ( i = 0; i <= tubularSegments; i ++ ) { - - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; - - // vertex - - vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = tube * Math.sin( v ); + var v = j / radialSegments * Math.PI * 2; - vertices.push( vertex.x, vertex.y, vertex.z ); + var sin = Math.sin( v ); + var cos = - Math.cos( v ); - // normal + // normal - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); - normal.subVectors( vertex, center ).normalize(); + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); - normals.push( normal.x, normal.y, normal.z ); + normals.push( normal.x, normal.y, normal.z ); - // uv + // vertex - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; - } + vertices.push( vertex.x, vertex.y, vertex.z ); } - // generate indices + } - for ( j = 1; j <= radialSegments; j ++ ) { + function generateIndices() { - for ( i = 1; i <= tubularSegments; i ++ ) { + for ( j = 1; j <= tubularSegments; j ++ ) { - // indices + for ( i = 1; i <= radialSegments; i ++ ) { - var a = ( tubularSegments + 1 ) * j + i - 1; - var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( tubularSegments + 1 ) * j + i; + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; // faces @@ -29490,20627 +29482,21469 @@ } - // build geometry - - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } - TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - - /** - * @author Mugen87 / https://github.com/Mugen87 - * Port from https://github.com/mapbox/earcut (v2.1.5) - */ + function generateUVs() { - var Earcut = { + for ( i = 0; i <= tubularSegments; i ++ ) { - triangulate: function ( data, holeIndices, dim ) { + for ( j = 0; j <= radialSegments; j ++ ) { - dim = dim || 2; + uv.x = i / tubularSegments; + uv.y = j / radialSegments; - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length, - outerNode = linkedList( data, 0, outerLen, dim, true ), - triangles = []; + uvs.push( uv.x, uv.y ); - if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; } + } - var minX, minY, maxX, maxY, x, y, invSize; + } - if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); } + } - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if ( data.length > 80 * dim ) { +} - minX = maxX = data[ 0 ]; - minY = maxY = data[ 1 ]; +TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TubeBufferGeometry.prototype.constructor = TubeBufferGeometry; - for ( var i = dim; i < outerLen; i += dim ) { +TubeBufferGeometry.prototype.toJSON = function () { - x = data[ i ]; - y = data[ i + 1 ]; - if ( x < minX ) { minX = x; } - if ( y < minY ) { minY = y; } - if ( x > maxX ) { maxX = x; } - if ( y > maxY ) { maxY = y; } + var data = BufferGeometry.prototype.toJSON.call( this ); - } + data.path = this.parameters.path.toJSON(); - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max( maxX - minX, maxY - minY ); - invSize = invSize !== 0 ? 1 / invSize : 0; + return data; - } +}; - earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); +/** + * @author oosmoxiecode + * @author Mugen87 / https://github.com/Mugen87 + * + * based on http://www.blackpawn.com/texts/pqtorus/ + */ - return triangles; +// TorusKnotGeometry - } +function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { - }; + Geometry.call( this ); - // create a circular doubly linked list from polygon points in the specified winding order - function linkedList( data, start, end, dim, clockwise ) { + this.type = 'TorusKnotGeometry'; - var i, last; + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { + if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); } + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.mergeVertices(); - } else { +} - for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); } +TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); +TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; - } +// TorusKnotBufferGeometry - if ( last && equals( last, last.next ) ) { +function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { - removeNode( last ); - last = last.next; + BufferGeometry.call( this ); - } + this.type = 'TorusKnotBufferGeometry'; - return last; + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - } + radius = radius || 1; + tube = tube || 0.4; + tubularSegments = Math.floor( tubularSegments ) || 64; + radialSegments = Math.floor( radialSegments ) || 8; + p = p || 2; + q = q || 3; - // eliminate colinear or duplicate points - function filterPoints( start, end ) { + // buffers - if ( ! start ) { return start; } - if ( ! end ) { end = start; } + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - var p = start, - again; - do { + // helper variables - again = false; + var i, j; - if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { + var vertex = new Vector3(); + var normal = new Vector3(); - removeNode( p ); - p = end = p.prev; - if ( p === p.next ) { break; } - again = true; + var P1 = new Vector3(); + var P2 = new Vector3(); - } else { + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); - p = p.next; + // generate vertices, normals and uvs - } + for ( i = 0; i <= tubularSegments; ++ i ) { - } while ( again || p !== end ); + // the radian "u" is used to calculate the position on the torus curve of the current tubular segement - return end; + var u = i / tubularSegments * p * Math.PI * 2; - } + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions - // main ear slicing loop which triangulates a polygon (given as a linked list) - function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - if ( ! ear ) { return; } + // calculate orthonormal basis - // interlink polygon nodes in z-order - if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); } + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - var stop = ear, - prev, next; + // normalize B, N. T can be ignored, we don't use it - // iterate through ears, slicing them one by one - while ( ear.prev !== ear.next ) { + B.normalize(); + N.normalize(); - prev = ear.prev; - next = ear.next; + for ( j = 0; j <= radialSegments; ++ j ) { - if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. - // cut off the triangle - triangles.push( prev.i / dim ); - triangles.push( ear.i / dim ); - triangles.push( next.i / dim ); + var v = j / radialSegments * Math.PI * 2; + var cx = - tube * Math.cos( v ); + var cy = tube * Math.sin( v ); - removeNode( ear ); + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); - continue; + vertices.push( vertex.x, vertex.y, vertex.z ); - } + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - ear = next; + normal.subVectors( vertex, P1 ).normalize(); - // if we looped through the whole remaining polygon and can't find any more ears - if ( ear === stop ) { + normals.push( normal.x, normal.y, normal.z ); - // try filtering points and slicing again - if ( ! pass ) { + // uv - earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - // if this didn't work, try curing all small self-intersections locally + } - } else if ( pass === 1 ) { + } - ear = cureLocalIntersections( ear, triangles, dim ); - earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); + // generate indices - // as a last resort, try splitting the remaining polygon into two + for ( j = 1; j <= tubularSegments; j ++ ) { - } else if ( pass === 2 ) { + for ( i = 1; i <= radialSegments; i ++ ) { - splitEarcut( ear, triangles, dim, minX, minY, invSize ); + // indices - } + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - break; + // faces - } + indices.push( a, b, d ); + indices.push( b, c, d ); } } - // check whether a polygon node forms a valid ear with adjacent nodes - function isEar( ear ) { + // build geometry - var a = ear.prev, - b = ear, - c = ear.next; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear + // this function calculates the current position on the torus curve - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; + function calculatePositionOnCurve( u, p, q, radius, position ) { - while ( p !== ear.prev ) { + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = q / p * u; + var cs = Math.cos( quOverP ); - if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) { return false; } - p = p.next; + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; - } + } - return true; +} - } +TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - function isEarHashed( ear, minX, minY, invSize ) { +/** + * @author oosmoxiecode + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - var a = ear.prev, - b = ear, - c = ear.next; +// TorusGeometry - if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear +function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - // triangle bbox; min & max are calculated like this for speed - var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), - minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), - maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), - maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); + Geometry.call( this ); - // z-order range for the current triangle bbox; - var minZ = zOrder( minTX, minTY, minX, minY, invSize ), - maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); + this.type = 'TorusGeometry'; - var p = ear.prevZ, - n = ear.nextZ; + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - // look for points inside the triangle in both directions - while ( p && p.z >= minZ && n && n.z <= maxZ ) { + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + this.mergeVertices(); - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) { return false; } - p = p.prevZ; +} - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) { return false; } - n = n.nextZ; +TorusGeometry.prototype = Object.create( Geometry.prototype ); +TorusGeometry.prototype.constructor = TorusGeometry; - } +// TorusBufferGeometry - // look for remaining points in decreasing z-order - while ( p && p.z >= minZ ) { +function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - if ( p !== ear.prev && p !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && - area( p.prev, p, p.next ) >= 0 ) { return false; } - p = p.prevZ; + BufferGeometry.call( this ); - } + this.type = 'TorusBufferGeometry'; - // look for remaining points in increasing z-order - while ( n && n.z <= maxZ ) { + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - if ( n !== ear.prev && n !== ear.next && - pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && - area( n.prev, n, n.next ) >= 0 ) { return false; } - n = n.nextZ; + radius = radius || 1; + tube = tube || 0.4; + radialSegments = Math.floor( radialSegments ) || 8; + tubularSegments = Math.floor( tubularSegments ) || 6; + arc = arc || Math.PI * 2; - } + // buffers - return true; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - } + // helper variables - // go through all polygon nodes and cure small local self-intersections - function cureLocalIntersections( start, triangles, dim ) { + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); - var p = start; - do { + var j, i; - var a = p.prev, - b = p.next.next; + // generate vertices, normals and uvs - if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + for ( j = 0; j <= radialSegments; j ++ ) { - triangles.push( a.i / dim ); - triangles.push( p.i / dim ); - triangles.push( b.i / dim ); + for ( i = 0; i <= tubularSegments; i ++ ) { - // remove two nodes involved - removeNode( p ); - removeNode( p.next ); + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - p = start = b; + // vertex - } + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); - p = p.next; + vertices.push( vertex.x, vertex.y, vertex.z ); - } while ( p !== start ); + // normal - return p; + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); - } + normals.push( normal.x, normal.y, normal.z ); - // try splitting polygon into two and triangulate them independently - function splitEarcut( start, triangles, dim, minX, minY, invSize ) { + // uv - // look for a valid diagonal that divides the polygon into two - var a = start; - do { + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - var b = a.next.next; - while ( b !== a.prev ) { + } - if ( a.i !== b.i && isValidDiagonal( a, b ) ) { + } - // split the polygon in two by the diagonal - var c = splitPolygon( a, b ); + // generate indices - // filter colinear points around the cuts - a = filterPoints( a, a.next ); - c = filterPoints( c, c.next ); + for ( j = 1; j <= radialSegments; j ++ ) { - // run earcut on each half - earcutLinked( a, triangles, dim, minX, minY, invSize ); - earcutLinked( c, triangles, dim, minX, minY, invSize ); - return; + for ( i = 1; i <= tubularSegments; i ++ ) { - } + // indices - b = b.next; + var a = ( tubularSegments + 1 ) * j + i - 1; + var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + var d = ( tubularSegments + 1 ) * j + i; - } + // faces - a = a.next; + indices.push( a, b, d ); + indices.push( b, c, d ); - } while ( a !== start ); + } } - // link every hole into the outer loop, producing a single-ring polygon without holes - function eliminateHoles( data, holeIndices, outerNode, dim ) { + // build geometry - var queue = [], - i, len, start, end, list; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - for ( i = 0, len = holeIndices.length; i < len; i ++ ) { +} - start = holeIndices[ i ] * dim; - end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; - list = linkedList( data, start, end, dim, false ); - if ( list === list.next ) { list.steiner = true; } - queue.push( getLeftmost( list ) ); +TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - } +/** + * @author Mugen87 / https://github.com/Mugen87 + * Port from https://github.com/mapbox/earcut (v2.2.2) + */ - queue.sort( compareX ); +var Earcut = { - // process holes from left to right - for ( i = 0; i < queue.length; i ++ ) { + triangulate: function ( data, holeIndices, dim ) { - eliminateHole( queue[ i ], outerNode ); - outerNode = filterPoints( outerNode, outerNode.next ); + dim = dim || 2; - } + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length, + outerNode = linkedList( data, 0, outerLen, dim, true ), + triangles = []; - return outerNode; + if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles; - } + var minX, minY, maxX, maxY, x, y, invSize; - function compareX( a, b ) { + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); - return a.x - b.x; + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if ( data.length > 80 * dim ) { - } + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; - // find a bridge between vertices that connects hole with an outer ring and and link it - function eliminateHole( hole, outerNode ) { + for ( var i = dim; i < outerLen; i += dim ) { - outerNode = findHoleBridge( hole, outerNode ); - if ( outerNode ) { + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; - var b = splitPolygon( outerNode, hole ); - filterPoints( b, b.next ); + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 1 / invSize : 0; } - } + earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); - // David Eberly's algorithm for finding a bridge between hole and outer polygon - function findHoleBridge( hole, outerNode ) { + return triangles; - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = - Infinity, - m; + } - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { +}; - if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList( data, start, end, dim, clockwise ) { - var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); - if ( x <= hx && x > qx ) { + var i, last; - qx = x; - if ( x === hx ) { + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { - if ( hy === p.y ) { return p; } - if ( hy === p.next.y ) { return p.next; } + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - } + } else { - m = p.x < p.next.x ? p : p.next; + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - } + } - } + if ( last && equals( last, last.next ) ) { - p = p.next; + removeNode( last ); + last = last.next; - } while ( p !== outerNode ); + } - if ( ! m ) { return null; } + return last; - if ( hx === qx ) { return m.prev; } // hole touches outer segment; pick lower endpoint +} - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point +// eliminate colinear or duplicate points +function filterPoints( start, end ) { - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; + if ( ! start ) return start; + if ( ! end ) end = start; - p = m.next; + var p = start, + again; + do { - while ( p !== stop ) { + again = false; - if ( hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { - tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; - if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) { + } else { - m = p; - tanMin = tan; + p = p.next; - } + } - } + } while ( again || p !== end ); - p = p.next; + return end; - } +} - return m; +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { - } + if ( ! ear ) return; // interlink polygon nodes in z-order - function indexCurve( start, minX, minY, invSize ) { + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); - var p = start; - do { + var stop = ear, + prev, next; - if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); } - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; + // iterate through ears, slicing them one by one + while ( ear.prev !== ear.next ) { - } while ( p !== start ); + prev = ear.prev; + next = ear.next; - p.prevZ.nextZ = null; - p.prevZ = null; + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { - sortLinked( p ); + // cut off the triangle + triangles.push( prev.i / dim ); + triangles.push( ear.i / dim ); + triangles.push( next.i / dim ); - } + removeNode( ear ); - // Simon Tatham's linked list merge sort algorithm - // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html - function sortLinked( list ) { + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; + continue; - do { + } - p = list; - list = null; - tail = null; - numMerges = 0; + ear = next; - while ( p ) { + // if we looped through the whole remaining polygon and can't find any more ears + if ( ear === stop ) { - numMerges ++; - q = p; - pSize = 0; - for ( i = 0; i < inSize; i ++ ) { + // try filtering points and slicing again + if ( ! pass ) { - pSize ++; - q = q.nextZ; - if ( ! q ) { break; } + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); - } + // if this didn't work, try curing all small self-intersections locally - qSize = inSize; + } else if ( pass === 1 ) { - while ( pSize > 0 || ( qSize > 0 && q ) ) { + ear = cureLocalIntersections( filterPoints( ear ), triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); - if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { + // as a last resort, try splitting the remaining polygon into two - e = p; - p = p.nextZ; - pSize --; + } else if ( pass === 2 ) { - } else { + splitEarcut( ear, triangles, dim, minX, minY, invSize ); - e = q; - q = q.nextZ; - qSize --; + } - } + break; + + } - if ( tail ) { tail.nextZ = e; } - else { list = e; } + } - e.prevZ = tail; - tail = e; +} - } +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar( ear ) { - p = q; + var a = ear.prev, + b = ear, + c = ear.next; - } + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - tail.nextZ = null; - inSize *= 2; + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; - } while ( numMerges > 1 ); + while ( p !== ear.prev ) { - return list; + if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.next; } - // z-order of a point given coords and inverse of the longer side of data bbox - function zOrder( x, y, minX, minY, invSize ) { + return true; - // coords are transformed into non-negative 15-bit integer range - x = 32767 * ( x - minX ) * invSize; - y = 32767 * ( y - minY ) * invSize; +} - x = ( x | ( x << 8 ) ) & 0x00FF00FF; - x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; - x = ( x | ( x << 2 ) ) & 0x33333333; - x = ( x | ( x << 1 ) ) & 0x55555555; +function isEarHashed( ear, minX, minY, invSize ) { - y = ( y | ( y << 8 ) ) & 0x00FF00FF; - y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; - y = ( y | ( y << 2 ) ) & 0x33333333; - y = ( y | ( y << 1 ) ) & 0x55555555; + var a = ear.prev, + b = ear, + c = ear.next; - return x | ( y << 1 ); + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - } + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), + minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), + maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), + maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); - // find the leftmost node of a polygon ring - function getLeftmost( start ) { + // z-order range for the current triangle bbox; + var minZ = zOrder( minTX, minTY, minX, minY, invSize ), + maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); - var p = start, - leftmost = start; - do { + var p = ear.prevZ, + n = ear.nextZ; - if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; } - p = p.next; + // look for points inside the triangle in both directions + while ( p && p.z >= minZ && n && n.z <= maxZ ) { - } while ( p !== start ); + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; - return leftmost; + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; } - // check if a point lies within a convex triangle - function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { + // look for remaining points in decreasing z-order + while ( p && p.z >= minZ ) { - return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && - ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && - ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.prevZ; } - // check if a diagonal between two polygon nodes is valid (lies in polygon interior) - function isValidDiagonal( a, b ) { + // look for remaining points in increasing z-order + while ( n && n.z <= maxZ ) { - return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && - locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ); + if ( n !== ear.prev && n !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && + area( n.prev, n, n.next ) >= 0 ) return false; + n = n.nextZ; } - // signed area of a triangle - function area( p, q, r ) { + return true; - return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); +} - } +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections( start, triangles, dim ) { - // check if two points are equal - function equals( p1, p2 ) { + var p = start; + do { - return p1.x === p2.x && p1.y === p2.y; + var a = p.prev, + b = p.next.next; - } + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { - // check if two segments intersect - function intersects( p1, q1, p2, q2 ) { + triangles.push( a.i / dim ); + triangles.push( p.i / dim ); + triangles.push( b.i / dim ); - if ( ( equals( p1, p2 ) && equals( q1, q2 ) ) || - ( equals( p1, q2 ) && equals( p2, q1 ) ) ) { return true; } - return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 && - area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0; + // remove two nodes involved + removeNode( p ); + removeNode( p.next ); - } + p = start = b; - // check if a polygon diagonal intersects any polygon segments - function intersectsPolygon( a, b ) { + } - var p = a; - do { + p = p.next; - if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects( p, p.next, a, b ) ) { return true; } - p = p.next; + } while ( p !== start ); - } while ( p !== a ); + return filterPoints( p ); - return false; +} - } +// try splitting polygon into two and triangulate them independently +function splitEarcut( start, triangles, dim, minX, minY, invSize ) { - // check if a polygon diagonal is locally inside the polygon - function locallyInside( a, b ) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { - return area( a.prev, a, a.next ) < 0 ? - area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : - area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; + var b = a.next.next; + while ( b !== a.prev ) { - } + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { - // check if the middle point of a polygon diagonal is inside the polygon - function middleInside( a, b ) { + // split the polygon in two by the diagonal + var c = splitPolygon( a, b ); - var p = a, - inside = false, - px = ( a.x + b.x ) / 2, - py = ( a.y + b.y ) / 2; - do { + // filter colinear points around the cuts + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); - if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && - ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) - { inside = ! inside; } - p = p.next; + // run earcut on each half + earcutLinked( a, triangles, dim, minX, minY, invSize ); + earcutLinked( c, triangles, dim, minX, minY, invSize ); + return; - } while ( p !== a ); + } - return inside; + b = b.next; - } + } - // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; - // if one belongs to the outer ring and another to a hole, it merges it into a single ring - function splitPolygon( a, b ) { + a = a.next; - var a2 = new Node( a.i, a.x, a.y ), - b2 = new Node( b.i, b.x, b.y ), - an = a.next, - bp = b.prev; + } while ( a !== start ); - a.next = b; - b.prev = a; +} - a2.next = an; - an.prev = a2; +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles( data, holeIndices, outerNode, dim ) { - b2.next = a2; - a2.prev = b2; + var queue = [], + i, len, start, end, list; - bp.next = b2; - b2.prev = bp; + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { - return b2; + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); } - // create a node and optionally link it with previous one (in a circular doubly linked list) - function insertNode( i, x, y, last ) { + queue.sort( compareX ); + + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { - var p = new Node( i, x, y ); + eliminateHole( queue[ i ], outerNode ); + outerNode = filterPoints( outerNode, outerNode.next ); - if ( ! last ) { + } - p.prev = p; - p.next = p; + return outerNode; - } else { +} - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; +function compareX( a, b ) { - } + return a.x - b.x; - return p; +} - } +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole( hole, outerNode ) { - function removeNode( p ) { + outerNode = findHoleBridge( hole, outerNode ); + if ( outerNode ) { - p.next.prev = p.prev; - p.prev.next = p.next; + var b = splitPolygon( outerNode, hole ); - if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; } - if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; } + // filter collinear points around the cuts + filterPoints( outerNode, outerNode.next ); + filterPoints( b, b.next ); } - function Node( i, x, y ) { +} - // vertex index in coordinates array - this.i = i; +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge( hole, outerNode ) { - // vertex coordinates - this.x = x; - this.y = y; + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = - Infinity, + m; - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { - // z-order curve value - this.z = null; + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; + var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); + if ( x <= hx && x > qx ) { - // indicates whether this is a steiner point - this.steiner = false; + qx = x; + if ( x === hx ) { - } + if ( hy === p.y ) return p; + if ( hy === p.next.y ) return p.next; - function signedArea( data, start, end, dim ) { + } - var sum = 0; - for ( var i = start, j = end - dim; i < end; i += dim ) { + m = p.x < p.next.x ? p : p.next; - sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); - j = i; + } } - return sum; + p = p.next; - } + } while ( p !== outerNode ); - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + if ( ! m ) return null; + + if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; - var ShapeUtils = { + p = m; - // calculate area of the contour polygon + do { - area: function ( contour ) { + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { - var n = contour.length; - var a = 0.0; + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { + if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) { - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + m = p; + tanMin = tan; } - return a * 0.5; + } - }, + p = p.next; - isClockWise: function ( pts ) { + } while ( p !== stop ); - return ShapeUtils.area( pts ) < 0; + return m; - }, +} - triangulateShape: function ( contour, holes ) { +// whether sector in vertex m contains sector in vertex p in the same coordinates +function sectorContainsSector( m, p ) { - var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] - var holeIndices = []; // array of hole indices - var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] + return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0; - removeDupEndPts( contour ); - addContour( vertices, contour ); +} - // +// interlink polygon nodes in z-order +function indexCurve( start, minX, minY, invSize ) { - var holeIndex = contour.length; + var p = start; + do { - holes.forEach( removeDupEndPts ); + if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; - for ( var i = 0; i < holes.length; i ++ ) { + } while ( p !== start ); - holeIndices.push( holeIndex ); - holeIndex += holes[ i ].length; - addContour( vertices, holes[ i ] ); + p.prevZ.nextZ = null; + p.prevZ = null; - } + sortLinked( p ); - // +} - var triangles = Earcut.triangulate( vertices, holeIndices ); +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked( list ) { - // + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; - for ( var i = 0; i < triangles.length; i += 3 ) { + do { - faces.push( triangles.slice( i, i + 3 ) ); + p = list; + list = null; + tail = null; + numMerges = 0; - } + while ( p ) { - return faces; + numMerges ++; + q = p; + pSize = 0; + for ( i = 0; i < inSize; i ++ ) { - } + pSize ++; + q = q.nextZ; + if ( ! q ) break; - }; + } - function removeDupEndPts( points ) { + qSize = inSize; - var l = points.length; + while ( pSize > 0 || ( qSize > 0 && q ) ) { - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { - points.pop(); + e = p; + p = p.nextZ; + pSize --; - } + } else { - } + e = q; + q = q.nextZ; + qSize --; + + } + + if ( tail ) tail.nextZ = e; + else list = e; - function addContour( vertices, contour ) { + e.prevZ = tail; + tail = e; - for ( var i = 0; i < contour.length; i ++ ) { + } - vertices.push( contour[ i ].x ); - vertices.push( contour[ i ].y ); + p = q; } - } + tail.nextZ = null; + inSize *= 2; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * depth: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline (including bevelOffset) is bevel - * bevelOffset: , // how far from shape outline does bevel start - * bevelSegments: , // number of bevel layers - * - * extrudePath: // curve to extrude shape along - * - * UVGenerator: // object that provides UV generator functions - * - * } - */ + } while ( numMerges > 1 ); - // ExtrudeGeometry + return list; - function ExtrudeGeometry( shapes, options ) { +} - Geometry.call( this ); +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder( x, y, minX, minY, invSize ) { - this.type = 'ExtrudeGeometry'; + // coords are transformed into non-negative 15-bit integer range + x = 32767 * ( x - minX ) * invSize; + y = 32767 * ( y - minY ) * invSize; - this.parameters = { - shapes: shapes, - options: options - }; + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; - this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) ); - this.mergeVertices(); + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; - } + return x | ( y << 1 ); - ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); - ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; +} - ExtrudeGeometry.prototype.toJSON = function () { +// find the leftmost node of a polygon ring +function getLeftmost( start ) { - var data = Geometry.prototype.toJSON.call( this ); + var p = start, + leftmost = start; + do { - var shapes = this.parameters.shapes; - var options = this.parameters.options; + if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p; + p = p.next; - return toJSON( shapes, options, data ); + } while ( p !== start ); - }; + return leftmost; - // ExtrudeBufferGeometry +} - function ExtrudeBufferGeometry( shapes, options ) { +// check if a point lies within a convex triangle +function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { - BufferGeometry.call( this ); + return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && + ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && + ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; - this.type = 'ExtrudeBufferGeometry'; +} - this.parameters = { - shapes: shapes, - options: options - }; +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal( a, b ) { - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges + ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible + ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors + equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case - var scope = this; +} - var verticesArray = []; - var uvArray = []; +// signed area of a triangle +function area( p, q, r ) { - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); - var shape = shapes[ i ]; - addShape( shape ); +} - } +// check if two points are equal +function equals( p1, p2 ) { - // build geometry + return p1.x === p2.x && p1.y === p2.y; - this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); +} - this.computeVertexNormals(); +// check if two segments intersect +function intersects( p1, q1, p2, q2 ) { - // functions + var o1 = sign( area( p1, q1, p2 ) ); + var o2 = sign( area( p1, q1, q2 ) ); + var o3 = sign( area( p2, q2, p1 ) ); + var o4 = sign( area( p2, q2, q1 ) ); - function addShape( shape ) { + if ( o1 !== o2 && o3 !== o4 ) return true; // general case - var placeholder = []; + if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 + if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 + if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 + if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 - // options + return false; - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - var steps = options.steps !== undefined ? options.steps : 1; - var depth = options.depth !== undefined ? options.depth : 100; +} - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; - var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; +// for collinear points p, q, r, check if point q lies on segment pr +function onSegment( p, q, r ) { - var extrudePath = options.extrudePath; + return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y ); - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; +} - // deprecated options +function sign( num ) { - if ( options.amount !== undefined ) { + return num > 0 ? 1 : num < 0 ? - 1 : 0; - console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' ); - depth = options.amount; +} - } +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon( a, b ) { - // + var p = a; + do { - var extrudePts, extrudeByPath = false; - var splineTube, binormal, normal, position2; + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) return true; + p = p.next; - if ( extrudePath ) { + } while ( p !== a ); - extrudePts = extrudePath.getSpacedPoints( steps ); + return false; - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion +} - // SETUP TNB variables +// check if a polygon diagonal is locally inside the polygon +function locallyInside( a, b ) { - // TODO1 - have a .isClosed in spline? + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; - splineTube = extrudePath.computeFrenetFrames( steps, false ); +} - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside( a, b ) { - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + var p = a, + inside = false, + px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; + do { - } + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) + inside = ! inside; + p = p.next; - // Safeguards if bevels are not enabled + } while ( p !== a ); - if ( ! bevelEnabled ) { + return inside; - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; - bevelOffset = 0; +} - } +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon( a, b ) { - // Variables initialization + var a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; - var ahole, h, hl; // looping of holes + a.next = b; + b.prev = a; - var shapePoints = shape.extractPoints( curveSegments ); + a2.next = an; + an.prev = a2; - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + b2.next = a2; + a2.prev = b2; - var reverse = ! ShapeUtils.isClockWise( vertices ); + bp.next = b2; + b2.prev = bp; - if ( reverse ) { + return b2; - vertices = vertices.reverse(); +} - // Maybe we should also check if holes are in the opposite direction, just to be safe ... +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode( i, x, y, last ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + var p = new Node( i, x, y ); - ahole = holes[ h ]; + if ( ! last ) { - if ( ShapeUtils.isClockWise( ahole ) ) { + p.prev = p; + p.next = p; - holes[ h ] = ahole.reverse(); + } else { - } + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; - } + } - } + return p; +} - var faces = ShapeUtils.triangulateShape( vertices, holes ); +function removeNode( p ) { - /* Vertices */ + p.next.prev = p.prev; + p.prev.next = p.next; - var contour = vertices; // vertices has all points but contour has only points of circumference + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { +} - ahole = holes[ h ]; +function Node( i, x, y ) { - vertices = vertices.concat( ahole ); + // vertex index in coordinates array + this.i = i; - } + // vertex coordinates + this.x = x; + this.y = y; + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; - function scalePt2( pt, vec, size ) { + // z-order curve value + this.z = null; - if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); } + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - return vec.clone().multiplyScalar( size ).add( pt ); + // indicates whether this is a steiner point + this.steiner = false; - } +} - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; +function signedArea( data, start, end, dim ) { + var sum = 0; + for ( var i = start, j = end - dim; i < end; i += dim ) { - // Find directions for point movement + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; + } - function getBevelVec( inPt, inPrev, inNext ) { + return sum; - // computes for inPt the corresponding point inPt' on a new contour - // shifted by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. +} - var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + */ - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html +var ShapeUtils = { - var v_prev_x = inPt.x - inPrev.x, - v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, - v_next_y = inNext.y - inPt.y; + // calculate area of the contour polygon - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + area: function ( contour ) { - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + var n = contour.length; + var a = 0.0; - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - // not collinear + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - // length of vectors for normalizing + } - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + return a * 0.5; - // shift adjacent points by unit vectors to the left + }, - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + isClockWise: function ( pts ) { - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + return ShapeUtils.area( pts ) < 0; - // scaling factor for v_prev to intersection point + }, - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + triangulateShape: function ( contour, holes ) { - // vector from inPt to intersection point + var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + var holeIndices = []; // array of hole indices + var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + removeDupEndPts( contour ); + addContour( vertices, contour ); - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + // - return new Vector2( v_trans_x, v_trans_y ); + var holeIndex = contour.length; - } else { + holes.forEach( removeDupEndPts ); - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + for ( var i = 0; i < holes.length; i ++ ) { - } + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); - } else { + } - // handle special case of collinear edges + // - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + var triangles = Earcut.triangulate( vertices, holeIndices ); - if ( v_next_x > Number.EPSILON ) { + // - direction_eq = true; + for ( var i = 0; i < triangles.length; i += 3 ) { - } + faces.push( triangles.slice( i, i + 3 ) ); - } else { + } - if ( v_prev_x < - Number.EPSILON ) { + return faces; - if ( v_next_x < - Number.EPSILON ) { + } - direction_eq = true; +}; - } +function removeDupEndPts( points ) { - } else { + var l = points.length; - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - direction_eq = true; + points.pop(); - } + } - } +} - } +function addContour( vertices, contour ) { - if ( direction_eq ) { + for ( var i = 0; i < contour.length; i ++ ) { - // console.log("Warning: lines are a straight sequence"); - v_trans_x = - v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); - } else { + } - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); +} - } +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * depth: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline (including bevelOffset) is bevel + * bevelOffset: , // how far from shape outline does bevel start + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ - } +// ExtrudeGeometry - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); +function ExtrudeGeometry( shapes, options ) { - } + Geometry.call( this ); + this.type = 'ExtrudeGeometry'; - var contourMovements = []; + this.parameters = { + shapes: shapes, + options: options + }; - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) ); + this.mergeVertices(); - if ( j === il ) { j = 0; } - if ( k === il ) { k = 0; } +} - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) +ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); +ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); +ExtrudeGeometry.prototype.toJSON = function () { - } + var data = Geometry.prototype.toJSON.call( this ); - var holesMovements = [], - oneHoleMovements, verticesMovements = contourMovements.concat(); + var shapes = this.parameters.shapes; + var options = this.parameters.options; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + return toJSON( shapes, options, data ); - ahole = holes[ h ]; +}; - oneHoleMovements = []; +// ExtrudeBufferGeometry - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { +function ExtrudeBufferGeometry( shapes, options ) { - if ( j === il ) { j = 0; } - if ( k === il ) { k = 0; } + BufferGeometry.call( this ); - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + this.type = 'ExtrudeBufferGeometry'; - } + this.parameters = { + shapes: shapes, + options: options + }; - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - } + var scope = this; + var verticesArray = []; + var uvArray = []; - // Loop bevelSegments, 1 for the front, 1 for the back + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - for ( b = 0; b < bevelSegments; b ++ ) { + var shape = shapes[ i ]; + addShape( shape ); - //for ( b = bevelSegments; b > 0; b -- ) { + } - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + // build geometry - // contract shape + this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); - for ( i = 0, il = contour.length; i < il; i ++ ) { + this.computeVertexNormals(); - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + // functions - v( vert.x, vert.y, - z ); + function addShape( shape ) { - } + var placeholder = []; - // expand holes + // options - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + var steps = options.steps !== undefined ? options.steps : 1; + var depth = options.depth !== undefined ? options.depth : 100; - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; + var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; + var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - for ( i = 0, il = ahole.length; i < il; i ++ ) { + var extrudePath = options.extrudePath; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; - v( vert.x, vert.y, - z ); + // deprecated options - } + if ( options.amount !== undefined ) { - } + console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' ); + depth = options.amount; - } + } - bs = bevelSize + bevelOffset; + // - // Back facing vertices + var extrudePts, extrudeByPath = false; + var splineTube, binormal, normal, position2; - for ( i = 0; i < vlen; i ++ ) { + if ( extrudePath ) { - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + extrudePts = extrudePath.getSpacedPoints( steps ); - if ( ! extrudeByPath ) { + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - v( vert.x, vert.y, 0 ); + // SETUP TNB variables - } else { + // TODO1 - have a .isClosed in spline? - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + splineTube = extrudePath.computeFrenetFrames( steps, false ); - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); - v( position2.x, position2.y, position2.z ); + } - } + // Safeguards if bevels are not enabled - } + if ( ! bevelEnabled ) { + + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; - // Add stepped vertices... - // Including front facing vertices + } - var s; + // Variables initialization - for ( s = 1; s <= steps; s ++ ) { + var ahole, h, hl; // looping of holes - for ( i = 0; i < vlen; i ++ ) { + var shapePoints = shape.extractPoints( curveSegments ); - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - if ( ! extrudeByPath ) { + var reverse = ! ShapeUtils.isClockWise( vertices ); - v( vert.x, vert.y, depth / steps * s ); + if ( reverse ) { - } else { + vertices = vertices.reverse(); - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + ahole = holes[ h ]; - v( position2.x, position2.y, position2.z ); + if ( ShapeUtils.isClockWise( ahole ) ) { - } + holes[ h ] = ahole.reverse(); } } + } - // Add bevel segments planes - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + var faces = ShapeUtils.triangulateShape( vertices, holes ); - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; + /* Vertices */ - // contract shape + var contour = vertices; // vertices has all points but contour has only points of circumference - for ( i = 0, il = contour.length; i < il; i ++ ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, depth + z ); + ahole = holes[ h ]; - } + vertices = vertices.concat( ahole ); - // expand holes + } - for ( h = 0, hl = holes.length; h < hl; h ++ ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + function scalePt2( pt, vec, size ) { - for ( i = 0, il = ahole.length; i < il; i ++ ) { + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + return vec.clone().multiplyScalar( size ).add( pt ); - if ( ! extrudeByPath ) { + } - v( vert.x, vert.y, depth + z ); + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - } else { - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + // Find directions for point movement - } - } + function getBevelVec( inPt, inPrev, inNext ) { - } + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. - } + var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt - /* Faces */ + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - // Top and bottom faces + var v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + var v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; - buildLidFaces(); + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - // Sides faces + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - buildSideFaces(); + if ( Math.abs( collinear0 ) > Number.EPSILON ) { + // not collinear - ///// Internal functions + // length of vectors for normalizing - function buildLidFaces() { + var v_prev_len = Math.sqrt( v_prev_lensq ); + var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - var start = verticesArray.length / 3; + // shift adjacent points by unit vectors to the left - if ( bevelEnabled ) { + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - var layer = 0; // steps + 1 - var offset = vlen * layer; + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - // Bottom faces + // scaling factor for v_prev to intersection point - for ( i = 0; i < flen; i ++ ) { + var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + // vector from inPt to intersection point - } + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { + + return new Vector2( v_trans_x, v_trans_y ); + + } else { + + shrink_by = Math.sqrt( v_trans_lensq / 2 ); + + } - layer = steps + bevelSegments * 2; - offset = vlen * layer; + } else { + + // handle special case of collinear edges - // Top faces + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - for ( i = 0; i < flen; i ++ ) { + if ( v_next_x > Number.EPSILON ) { - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + direction_eq = true; } } else { - // Bottom faces + if ( v_prev_x < - Number.EPSILON ) { - for ( i = 0; i < flen; i ++ ) { + if ( v_next_x < - Number.EPSILON ) { - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + direction_eq = true; - } + } + + } else { - // Top faces + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - for ( i = 0; i < flen; i ++ ) { + direction_eq = true; - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + } } } - scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + if ( direction_eq ) { - } + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); - // Create faces for the z-sides of the shape + } else { - function buildSideFaces() { + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); - var start = verticesArray.length / 3; - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + } - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + } - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - //, true - layeroffset += ahole.length; + } - } + var contourMovements = []; - scope.addGroup( start, verticesArray.length / 3 - start, 1 ); + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + if ( j === il ) j = 0; + if ( k === il ) k = 0; - } + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - function sidewalls( contour, layeroffset ) { + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - var j, k; - i = contour.length; + } - while ( -- i >= 0 ) { + var holesMovements = [], + oneHoleMovements, verticesMovements = contourMovements.concat(); - j = i; - k = i - 1; - if ( k < 0 ) { k = contour.length - 1; } + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - //console.log('b', i,j, i-1, k,vertices.length); + ahole = holes[ h ]; - var s = 0, - sl = steps + bevelSegments * 2; + oneHoleMovements = []; - for ( s = 0; s < sl; s ++ ) { + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + if ( j === il ) j = 0; + if ( k === il ) k = 0; - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - f4( a, b, c, d ); + } - } + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - } + } - } - function v( x, y, z ) { + // Loop bevelSegments, 1 for the front, 1 for the back - placeholder.push( x ); - placeholder.push( y ); - placeholder.push( z ); + for ( b = 0; b < bevelSegments; b ++ ) { - } + //for ( b = bevelSegments; b > 0; b -- ) { + t = b / bevelSegments; + z = bevelThickness * Math.cos( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - function f3( a, b, c ) { + // contract shape - addVertex( a ); - addVertex( b ); - addVertex( c ); + for ( i = 0, il = contour.length; i < il; i ++ ) { - var nextIndex = verticesArray.length / 3; - var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); + v( vert.x, vert.y, - z ); } - function f4( a, b, c, d ) { + // expand holes - addVertex( a ); - addVertex( b ); - addVertex( d ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - addVertex( b ); - addVertex( c ); - addVertex( d ); + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + for ( i = 0, il = ahole.length; i < il; i ++ ) { - var nextIndex = verticesArray.length / 3; - var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 3 ] ); + v( vert.x, vert.y, - z ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); - addUV( uvs[ 3 ] ); + } } - function addVertex( index ) { + } - verticesArray.push( placeholder[ index * 3 + 0 ] ); - verticesArray.push( placeholder[ index * 3 + 1 ] ); - verticesArray.push( placeholder[ index * 3 + 2 ] ); + bs = bevelSize + bevelOffset; - } + // Back facing vertices + for ( i = 0; i < vlen; i ++ ) { - function addUV( vector2 ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - uvArray.push( vector2.x ); - uvArray.push( vector2.y ); + if ( ! extrudeByPath ) { - } + v( vert.x, vert.y, 0 ); - } + } else { - } + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry; + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - ExtrudeBufferGeometry.prototype.toJSON = function () { + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - var data = BufferGeometry.prototype.toJSON.call( this ); + v( position2.x, position2.y, position2.z ); + + } - var shapes = this.parameters.shapes; - var options = this.parameters.options; + } - return toJSON( shapes, options, data ); + // Add stepped vertices... + // Including front facing vertices - }; + var s; - // + for ( s = 1; s <= steps; s ++ ) { - var WorldUVGenerator = { + for ( i = 0; i < vlen; i ++ ) { - generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - var a_x = vertices[ indexA * 3 ]; - var a_y = vertices[ indexA * 3 + 1 ]; - var b_x = vertices[ indexB * 3 ]; - var b_y = vertices[ indexB * 3 + 1 ]; - var c_x = vertices[ indexC * 3 ]; - var c_y = vertices[ indexC * 3 + 1 ]; + if ( ! extrudeByPath ) { - return [ - new Vector2( a_x, a_y ), - new Vector2( b_x, b_y ), - new Vector2( c_x, c_y ) - ]; + v( vert.x, vert.y, depth / steps * s ); - }, + } else { - generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { - - var a_x = vertices[ indexA * 3 ]; - var a_y = vertices[ indexA * 3 + 1 ]; - var a_z = vertices[ indexA * 3 + 2 ]; - var b_x = vertices[ indexB * 3 ]; - var b_y = vertices[ indexB * 3 + 1 ]; - var b_z = vertices[ indexB * 3 + 2 ]; - var c_x = vertices[ indexC * 3 ]; - var c_y = vertices[ indexC * 3 + 1 ]; - var c_z = vertices[ indexC * 3 + 2 ]; - var d_x = vertices[ indexD * 3 ]; - var d_y = vertices[ indexD * 3 + 1 ]; - var d_z = vertices[ indexD * 3 + 2 ]; - - if ( Math.abs( a_y - b_y ) < 0.01 ) { - - return [ - new Vector2( a_x, 1 - a_z ), - new Vector2( b_x, 1 - b_z ), - new Vector2( c_x, 1 - c_z ), - new Vector2( d_x, 1 - d_z ) - ]; + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - } else { + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - return [ - new Vector2( a_y, 1 - a_z ), - new Vector2( b_y, 1 - b_z ), - new Vector2( c_y, 1 - c_z ), - new Vector2( d_y, 1 - d_z ) - ]; + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + + v( position2.x, position2.y, position2.z ); + + } } } - }; - function toJSON( shapes, options, data ) { - // + // Add bevel segments planes - data.shapes = []; + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { - if ( Array.isArray( shapes ) ) { + t = b / bevelSegments; + z = bevelThickness * Math.cos( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + // contract shape - var shape = shapes[ i ]; + for ( i = 0, il = contour.length; i < il; i ++ ) { - data.shapes.push( shape.uuid ); + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, depth + z ); } - } else { + // expand holes - data.shapes.push( shapes.uuid ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - } + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - // + for ( i = 0, il = ahole.length; i < il; i ++ ) { - if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); } + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - return data; + if ( ! extrudeByPath ) { - } + v( vert.x, vert.y, depth + z ); - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: , // how far from text outline (including bevelOffset) is bevel - * bevelOffset: // how far from text outline does bevel start - * } - */ + } else { - // TextGeometry + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); - function TextGeometry( text, parameters ) { + } - Geometry.call( this ); + } - this.type = 'TextGeometry'; + } - this.parameters = { - text: text, - parameters: parameters - }; + } - this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) ); - this.mergeVertices(); + /* Faces */ - } + // Top and bottom faces - TextGeometry.prototype = Object.create( Geometry.prototype ); - TextGeometry.prototype.constructor = TextGeometry; + buildLidFaces(); - // TextBufferGeometry + // Sides faces - function TextBufferGeometry( text, parameters ) { + buildSideFaces(); - parameters = parameters || {}; - var font = parameters.font; + ///// Internal functions - if ( ! ( font && font.isFont ) ) { + function buildLidFaces() { - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new Geometry(); + var start = verticesArray.length / 3; - } + if ( bevelEnabled ) { - var shapes = font.generateShapes( text, parameters.size ); + var layer = 0; // steps + 1 + var offset = vlen * layer; - // translate parameters to ExtrudeGeometry API + // Bottom faces - parameters.depth = parameters.height !== undefined ? parameters.height : 50; + for ( i = 0; i < flen; i ++ ) { - // defaults + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; } - if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; } - if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; } + } - ExtrudeBufferGeometry.call( this, shapes, parameters ); + layer = steps + bevelSegments * 2; + offset = vlen * layer; - this.type = 'TextBufferGeometry'; + // Top faces - } + for ( i = 0; i < flen; i ++ ) { - TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype ); - TextBufferGeometry.prototype.constructor = TextBufferGeometry; + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author benaadams / https://twitter.com/ben_a_adams - * @author Mugen87 / https://github.com/Mugen87 - */ + } - // SphereGeometry + } else { - function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + // Bottom faces - Geometry.call( this ); + for ( i = 0; i < flen; i ++ ) { - this.type = 'SphereGeometry'; + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - this.mergeVertices(); + // Top faces - } + for ( i = 0; i < flen; i ++ ) { - SphereGeometry.prototype = Object.create( Geometry.prototype ); - SphereGeometry.prototype.constructor = SphereGeometry; + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - // SphereBufferGeometry + } - function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + } - BufferGeometry.call( this ); + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); - this.type = 'SphereBufferGeometry'; + } - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + // Create faces for the z-sides of the shape - radius = radius || 1; + function buildSideFaces() { - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + var start = verticesArray.length / 3; + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); - var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); + //, true + layeroffset += ahole.length; - var ix, iy; + } - var index = 0; - var grid = []; - var vertex = new Vector3(); - var normal = new Vector3(); + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); - // buffers - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + } - // generate vertices, normals and uvs + function sidewalls( contour, layeroffset ) { - for ( iy = 0; iy <= heightSegments; iy ++ ) { + var j, k; + i = contour.length; - var verticesRow = []; + while ( -- i >= 0 ) { - var v = iy / heightSegments; + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - // special case for the poles + //console.log('b', i,j, i-1, k,vertices.length); - var uOffset = 0; + var s = 0, + sl = steps + bevelSegments * 2; - if ( iy == 0 && thetaStart == 0 ) { + for ( s = 0; s < sl; s ++ ) { - uOffset = 0.5 / widthSegments; + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); - } else if ( iy == heightSegments && thetaEnd == Math.PI ) { + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; - uOffset = - 0.5 / widthSegments; + f4( a, b, c, d ); + + } } - for ( ix = 0; ix <= widthSegments; ix ++ ) { + } - var u = ix / widthSegments; + function v( x, y, z ) { - // vertex + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + } - vertices.push( vertex.x, vertex.y, vertex.z ); - // normal + function f3( a, b, c ) { - normal.copy( vertex ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + addVertex( a ); + addVertex( b ); + addVertex( c ); - // uv + var nextIndex = verticesArray.length / 3; + var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - uvs.push( u + uOffset, 1 - v ); + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); - verticesRow.push( index ++ ); + } - } + function f4( a, b, c, d ) { - grid.push( verticesRow ); + addVertex( a ); + addVertex( b ); + addVertex( d ); - } + addVertex( b ); + addVertex( c ); + addVertex( d ); - // indices - for ( iy = 0; iy < heightSegments; iy ++ ) { + var nextIndex = verticesArray.length / 3; + var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); - for ( ix = 0; ix < widthSegments; ix ++ ) { + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); - var a = grid[ iy ][ ix + 1 ]; - var b = grid[ iy ][ ix ]; - var c = grid[ iy + 1 ][ ix ]; - var d = grid[ iy + 1 ][ ix + 1 ]; + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); - if ( iy !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); } - if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); } + } - } + function addVertex( index ) { + + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); } - // build geometry - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + function addUV( vector2 ) { - } + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); - SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + } - /** - * @author Kaleb Murphy - * @author Mugen87 / https://github.com/Mugen87 - */ + } - // RingGeometry +} - function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { +ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry; - Geometry.call( this ); +ExtrudeBufferGeometry.prototype.toJSON = function () { - this.type = 'RingGeometry'; + var data = BufferGeometry.prototype.toJSON.call( this ); - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var shapes = this.parameters.shapes; + var options = this.parameters.options; - this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); - this.mergeVertices(); + return toJSON( shapes, options, data ); - } +}; - RingGeometry.prototype = Object.create( Geometry.prototype ); - RingGeometry.prototype.constructor = RingGeometry; +// - // RingBufferGeometry +var WorldUVGenerator = { - function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { - BufferGeometry.call( this ); + var a_x = vertices[ indexA * 3 ]; + var a_y = vertices[ indexA * 3 + 1 ]; + var b_x = vertices[ indexB * 3 ]; + var b_y = vertices[ indexB * 3 + 1 ]; + var c_x = vertices[ indexC * 3 ]; + var c_y = vertices[ indexC * 3 + 1 ]; - this.type = 'RingBufferGeometry'; + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + }, - innerRadius = innerRadius || 0.5; - outerRadius = outerRadius || 1; + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + var a_x = vertices[ indexA * 3 ]; + var a_y = vertices[ indexA * 3 + 1 ]; + var a_z = vertices[ indexA * 3 + 2 ]; + var b_x = vertices[ indexB * 3 ]; + var b_y = vertices[ indexB * 3 + 1 ]; + var b_z = vertices[ indexB * 3 + 2 ]; + var c_x = vertices[ indexC * 3 ]; + var c_y = vertices[ indexC * 3 + 1 ]; + var c_z = vertices[ indexC * 3 + 2 ]; + var d_x = vertices[ indexD * 3 ]; + var d_y = vertices[ indexD * 3 + 1 ]; + var d_z = vertices[ indexD * 3 + 2 ]; - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + if ( Math.abs( a_y - b_y ) < 0.01 ) { - // buffers + return [ + new Vector2( a_x, 1 - a_z ), + new Vector2( b_x, 1 - b_z ), + new Vector2( c_x, 1 - c_z ), + new Vector2( d_x, 1 - d_z ) + ]; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + } else { - // some helper variables + return [ + new Vector2( a_y, 1 - a_z ), + new Vector2( b_y, 1 - b_z ), + new Vector2( c_y, 1 - c_z ), + new Vector2( d_y, 1 - d_z ) + ]; - var segment; - var radius = innerRadius; - var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new Vector3(); - var uv = new Vector2(); - var j, i; + } - // generate vertices, normals and uvs + } +}; - for ( j = 0; j <= phiSegments; j ++ ) { +function toJSON( shapes, options, data ) { - for ( i = 0; i <= thetaSegments; i ++ ) { + // - // values are generate from the inside of the ring to the outside + data.shapes = []; - segment = thetaStart + i / thetaSegments * thetaLength; + if ( Array.isArray( shapes ) ) { - // vertex + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + var shape = shapes[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + data.shapes.push( shape.uuid ); - // normal + } - normals.push( 0, 0, 1 ); + } else { - // uv + data.shapes.push( shapes.uuid ); - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; + } - uvs.push( uv.x, uv.y ); + // - } + if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON(); - // increase the radius for next row of vertices + return data; - radius += radiusStep; +} - } +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * Text = 3D Text + * + * parameters = { + * font: , // font + * + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: , // how far from text outline (including bevelOffset) is bevel + * bevelOffset: // how far from text outline does bevel start + * } + */ - // indices +// TextGeometry - for ( j = 0; j < phiSegments; j ++ ) { +function TextGeometry( text, parameters ) { - var thetaSegmentLevel = j * ( thetaSegments + 1 ); + Geometry.call( this ); - for ( i = 0; i < thetaSegments; i ++ ) { + this.type = 'TextGeometry'; - segment = i + thetaSegmentLevel; + this.parameters = { + text: text, + parameters: parameters + }; - var a = segment; - var b = segment + thetaSegments + 1; - var c = segment + thetaSegments + 2; - var d = segment + 1; + this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) ); + this.mergeVertices(); - // faces +} - indices.push( a, b, d ); - indices.push( b, c, d ); +TextGeometry.prototype = Object.create( Geometry.prototype ); +TextGeometry.prototype.constructor = TextGeometry; - } +// TextBufferGeometry - } +function TextBufferGeometry( text, parameters ) { - // build geometry + parameters = parameters || {}; - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + var font = parameters.font; - } + if ( ! ( font && font.isFont ) ) { - RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - RingBufferGeometry.prototype.constructor = RingBufferGeometry; + console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); + return new Geometry(); - /** - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://clara.io - * @author Mugen87 / https://github.com/Mugen87 - */ + } - // LatheGeometry + var shapes = font.generateShapes( text, parameters.size ); - function LatheGeometry( points, segments, phiStart, phiLength ) { + // translate parameters to ExtrudeGeometry API - Geometry.call( this ); + parameters.depth = parameters.height !== undefined ? parameters.height : 50; - this.type = 'LatheGeometry'; + // defaults - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; - this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); - this.mergeVertices(); + ExtrudeBufferGeometry.call( this, shapes, parameters ); - } + this.type = 'TextBufferGeometry'; - LatheGeometry.prototype = Object.create( Geometry.prototype ); - LatheGeometry.prototype.constructor = LatheGeometry; +} - // LatheBufferGeometry +TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype ); +TextBufferGeometry.prototype.constructor = TextBufferGeometry; - function LatheBufferGeometry( points, segments, phiStart, phiLength ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author benaadams / https://twitter.com/ben_a_adams + * @author Mugen87 / https://github.com/Mugen87 + */ - BufferGeometry.call( this ); +// SphereGeometry - this.type = 'LatheBufferGeometry'; +function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + Geometry.call( this ); - segments = Math.floor( segments ) || 12; - phiStart = phiStart || 0; - phiLength = phiLength || Math.PI * 2; + this.type = 'SphereGeometry'; - // clamp phiLength so it's in range of [ 0, 2PI ] + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); + this.mergeVertices(); +} - // buffers +SphereGeometry.prototype = Object.create( Geometry.prototype ); +SphereGeometry.prototype.constructor = SphereGeometry; - var indices = []; - var vertices = []; - var uvs = []; +// SphereBufferGeometry - // helper variables +function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { - var base; - var inverseSegments = 1.0 / segments; - var vertex = new Vector3(); - var uv = new Vector2(); - var i, j; + BufferGeometry.call( this ); - // generate vertices and uvs + this.type = 'SphereBufferGeometry'; - for ( i = 0; i <= segments; i ++ ) { + this.parameters = { + radius: radius, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - var phi = phiStart + i * inverseSegments * phiLength; + radius = radius || 1; - var sin = Math.sin( phi ); - var cos = Math.cos( phi ); + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); - for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; - // vertex + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; + var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); - vertices.push( vertex.x, vertex.y, vertex.z ); + var ix, iy; - // uv + var index = 0; + var grid = []; - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); + var vertex = new Vector3(); + var normal = new Vector3(); - uvs.push( uv.x, uv.y ); + // buffers + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - } + // generate vertices, normals and uvs - } + for ( iy = 0; iy <= heightSegments; iy ++ ) { - // indices + var verticesRow = []; - for ( i = 0; i < segments; i ++ ) { + var v = iy / heightSegments; - for ( j = 0; j < ( points.length - 1 ); j ++ ) { + // special case for the poles - base = j + i * points.length; + var uOffset = 0; - var a = base; - var b = base + points.length; - var c = base + points.length + 1; - var d = base + 1; + if ( iy == 0 && thetaStart == 0 ) { - // faces + uOffset = 0.5 / widthSegments; - indices.push( a, b, d ); - indices.push( b, c, d ); + } else if ( iy == heightSegments && thetaEnd == Math.PI ) { - } + uOffset = - 0.5 / widthSegments; } - // build geometry - - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + for ( ix = 0; ix <= widthSegments; ix ++ ) { - // generate normals + var u = ix / widthSegments; - this.computeVertexNormals(); + // vertex - // if the geometry is closed, we need to average the normals along the seam. - // because the corresponding vertices are identical (but still have different UVs). + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - if ( phiLength === Math.PI * 2 ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - var normals = this.attributes.normal.array; - var n1 = new Vector3(); - var n2 = new Vector3(); - var n = new Vector3(); + // normal - // this is the buffer offset for the last line of vertices + normal.copy( vertex ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - base = segments * points.length * 3; + // uv - for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + uvs.push( u + uOffset, 1 - v ); - // select the normal of the vertex in the first line + verticesRow.push( index ++ ); - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + } - // select the normal of the vertex in the last line + grid.push( verticesRow ); - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + } - // average normals + // indices - n.addVectors( n1, n2 ).normalize(); + for ( iy = 0; iy < heightSegments; iy ++ ) { - // assign the new values to both normals + for ( ix = 0; ix < widthSegments; ix ++ ) { - normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; - normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; - normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; + var a = grid[ iy ][ ix + 1 ]; + var b = grid[ iy ][ ix ]; + var c = grid[ iy + 1 ][ ix ]; + var d = grid[ iy + 1 ][ ix + 1 ]; - } + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); } } - LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; - - /** - * @author jonobr1 / http://jonobr1.com - * @author Mugen87 / https://github.com/Mugen87 - */ + // build geometry - // ShapeGeometry + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - function ShapeGeometry( shapes, curveSegments ) { +} - Geometry.call( this ); +SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; - this.type = 'ShapeGeometry'; +/** + * @author Kaleb Murphy + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( typeof curveSegments === 'object' ) { +// RingGeometry - console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' ); +function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - curveSegments = curveSegments.curveSegments; + Geometry.call( this ); - } + this.type = 'RingGeometry'; - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) ); - this.mergeVertices(); + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + this.mergeVertices(); - } +} - ShapeGeometry.prototype = Object.create( Geometry.prototype ); - ShapeGeometry.prototype.constructor = ShapeGeometry; +RingGeometry.prototype = Object.create( Geometry.prototype ); +RingGeometry.prototype.constructor = RingGeometry; - ShapeGeometry.prototype.toJSON = function () { +// RingBufferGeometry - var data = Geometry.prototype.toJSON.call( this ); +function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { - var shapes = this.parameters.shapes; + BufferGeometry.call( this ); - return toJSON$1( shapes, data ); + this.type = 'RingBufferGeometry'; + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength }; - // ShapeBufferGeometry + innerRadius = innerRadius || 0.5; + outerRadius = outerRadius || 1; - function ShapeBufferGeometry( shapes, curveSegments ) { + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - BufferGeometry.call( this ); + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; - this.type = 'ShapeBufferGeometry'; + // buffers - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - curveSegments = curveSegments || 12; + // some helper variables - // buffers + var segment; + var radius = innerRadius; + var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + var vertex = new Vector3(); + var uv = new Vector2(); + var j, i; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + // generate vertices, normals and uvs - // helper variables + for ( j = 0; j <= phiSegments; j ++ ) { - var groupStart = 0; - var groupCount = 0; + for ( i = 0; i <= thetaSegments; i ++ ) { - // allow single and array values for "shapes" parameter + // values are generate from the inside of the ring to the outside - if ( Array.isArray( shapes ) === false ) { + segment = thetaStart + i / thetaSegments * thetaLength; - addShape( shapes ); + // vertex - } else { + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - for ( var i = 0; i < shapes.length; i ++ ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - addShape( shapes[ i ] ); + // normal - this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + normals.push( 0, 0, 1 ); - groupStart += groupCount; - groupCount = 0; + // uv - } + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; - } + uvs.push( uv.x, uv.y ); - // build geometry + } - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // increase the radius for next row of vertices + radius += radiusStep; - // helper functions + } - function addShape( shape ) { + // indices - var i, l, shapeHole; + for ( j = 0; j < phiSegments; j ++ ) { - var indexOffset = vertices.length / 3; - var points = shape.extractPoints( curveSegments ); + var thetaSegmentLevel = j * ( thetaSegments + 1 ); - var shapeVertices = points.shape; - var shapeHoles = points.holes; + for ( i = 0; i < thetaSegments; i ++ ) { - // check direction of vertices + segment = i + thetaSegmentLevel; - if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + var a = segment; + var b = segment + thetaSegments + 1; + var c = segment + thetaSegments + 2; + var d = segment + 1; - shapeVertices = shapeVertices.reverse(); + // faces - } + indices.push( a, b, d ); + indices.push( b, c, d ); - for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { + } - shapeHole = shapeHoles[ i ]; + } - if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + // build geometry - shapeHoles[ i ] = shapeHole.reverse(); + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } +} - } +RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +RingBufferGeometry.prototype.constructor = RingBufferGeometry; - var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); +/** + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://clara.io + * @author Mugen87 / https://github.com/Mugen87 + */ - // join vertices of inner and outer paths to a single array +// LatheGeometry - for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { +function LatheGeometry( points, segments, phiStart, phiLength ) { - shapeHole = shapeHoles[ i ]; - shapeVertices = shapeVertices.concat( shapeHole ); + Geometry.call( this ); - } + this.type = 'LatheGeometry'; - // vertices, normals, uvs + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - for ( i = 0, l = shapeVertices.length; i < l; i ++ ) { + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.mergeVertices(); - var vertex = shapeVertices[ i ]; +} - vertices.push( vertex.x, vertex.y, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( vertex.x, vertex.y ); // world uvs +LatheGeometry.prototype = Object.create( Geometry.prototype ); +LatheGeometry.prototype.constructor = LatheGeometry; - } +// LatheBufferGeometry - // incides +function LatheBufferGeometry( points, segments, phiStart, phiLength ) { - for ( i = 0, l = faces.length; i < l; i ++ ) { + BufferGeometry.call( this ); - var face = faces[ i ]; + this.type = 'LatheBufferGeometry'; - var a = face[ 0 ] + indexOffset; - var b = face[ 1 ] + indexOffset; - var c = face[ 2 ] + indexOffset; + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; - indices.push( a, b, c ); - groupCount += 3; + segments = Math.floor( segments ) || 12; + phiStart = phiStart || 0; + phiLength = phiLength || Math.PI * 2; - } + // clamp phiLength so it's in range of [ 0, 2PI ] - } + phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 ); - } - ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry; + // buffers - ShapeBufferGeometry.prototype.toJSON = function () { + var indices = []; + var vertices = []; + var uvs = []; - var data = BufferGeometry.prototype.toJSON.call( this ); + // helper variables - var shapes = this.parameters.shapes; + var base; + var inverseSegments = 1.0 / segments; + var vertex = new Vector3(); + var uv = new Vector2(); + var i, j; - return toJSON$1( shapes, data ); + // generate vertices and uvs - }; + for ( i = 0; i <= segments; i ++ ) { - // + var phi = phiStart + i * inverseSegments * phiLength; - function toJSON$1( shapes, data ) { + var sin = Math.sin( phi ); + var cos = Math.cos( phi ); - data.shapes = []; + for ( j = 0; j <= ( points.length - 1 ); j ++ ) { - if ( Array.isArray( shapes ) ) { + // vertex - for ( var i = 0, l = shapes.length; i < l; i ++ ) { + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; - var shape = shapes[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - data.shapes.push( shape.uuid ); + // uv - } + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); - } else { + uvs.push( uv.x, uv.y ); - data.shapes.push( shapes.uuid ); } - return data; - } - /** - * @author WestLangley / http://github.com/WestLangley - * @author Mugen87 / https://github.com/Mugen87 - */ - - function EdgesGeometry( geometry, thresholdAngle ) { + // indices - BufferGeometry.call( this ); + for ( i = 0; i < segments; i ++ ) { - this.type = 'EdgesGeometry'; + for ( j = 0; j < ( points.length - 1 ); j ++ ) { - this.parameters = { - thresholdAngle: thresholdAngle - }; - - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - - // buffer + base = j + i * points.length; - var vertices = []; - - // helper variables + var a = base; + var b = base + points.length; + var c = base + points.length + 1; + var d = base + 1; - var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle ); - var edge = [ 0, 0 ], edges = {}, edge1, edge2; - var key, keys = [ 'a', 'b', 'c' ]; + // faces - // prepare source geometry + indices.push( a, b, d ); + indices.push( b, c, d ); - var geometry2; + } - if ( geometry.isBufferGeometry ) { + } - geometry2 = new Geometry(); - geometry2.fromBufferGeometry( geometry ); + // build geometry - } else { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - geometry2 = geometry.clone(); + // generate normals - } + this.computeVertexNormals(); - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + // if the geometry is closed, we need to average the normals along the seam. + // because the corresponding vertices are identical (but still have different UVs). - var sourceVertices = geometry2.vertices; - var faces = geometry2.faces; + if ( phiLength === Math.PI * 2 ) { - // now create a data structure where each entry represents an edge with its adjoining faces + var normals = this.attributes.normal.array; + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + // this is the buffer offset for the last line of vertices - var face = faces[ i ]; + base = segments * points.length * 3; - for ( var j = 0; j < 3; j ++ ) { + for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) { - edge1 = face[ keys[ j ] ]; - edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; - edge[ 0 ] = Math.min( edge1, edge2 ); - edge[ 1 ] = Math.max( edge1, edge2 ); + // select the normal of the vertex in the first line - key = edge[ 0 ] + ',' + edge[ 1 ]; + n1.x = normals[ j + 0 ]; + n1.y = normals[ j + 1 ]; + n1.z = normals[ j + 2 ]; - if ( edges[ key ] === undefined ) { + // select the normal of the vertex in the last line - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined }; + n2.x = normals[ base + j + 0 ]; + n2.y = normals[ base + j + 1 ]; + n2.z = normals[ base + j + 2 ]; - } else { + // average normals - edges[ key ].face2 = i; + n.addVectors( n1, n2 ).normalize(); - } + // assign the new values to both normals - } + normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; + normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; + normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; } - // generate vertices + } - for ( key in edges ) { +} - var e = edges[ key ]; +LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; - // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree. +/** + * @author jonobr1 / http://jonobr1.com + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) { +// ShapeGeometry - var vertex = sourceVertices[ e.index1 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); +function ShapeGeometry( shapes, curveSegments ) { - vertex = sourceVertices[ e.index2 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + Geometry.call( this ); - } + this.type = 'ShapeGeometry'; - } + if ( typeof curveSegments === 'object' ) { - // build geometry + console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + curveSegments = curveSegments.curveSegments; } - EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); - EdgesGeometry.prototype.constructor = EdgesGeometry; + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) ); + this.mergeVertices(); - // CylinderGeometry +} - function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +ShapeGeometry.prototype = Object.create( Geometry.prototype ); +ShapeGeometry.prototype.constructor = ShapeGeometry; - Geometry.call( this ); +ShapeGeometry.prototype.toJSON = function () { - this.type = 'CylinderGeometry'; + var data = Geometry.prototype.toJSON.call( this ); - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var shapes = this.parameters.shapes; - this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); - this.mergeVertices(); + return toJSON$1( shapes, data ); - } +}; - CylinderGeometry.prototype = Object.create( Geometry.prototype ); - CylinderGeometry.prototype.constructor = CylinderGeometry; +// ShapeBufferGeometry - // CylinderBufferGeometry +function ShapeBufferGeometry( shapes, curveSegments ) { - function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + BufferGeometry.call( this ); - BufferGeometry.call( this ); + this.type = 'ShapeBufferGeometry'; - this.type = 'CylinderBufferGeometry'; + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + curveSegments = curveSegments || 12; - var scope = this; + // buffers - radiusTop = radiusTop !== undefined ? radiusTop : 1; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 1; - height = height || 1; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + // helper variables - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + var groupStart = 0; + var groupCount = 0; - // buffers + // allow single and array values for "shapes" parameter - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + if ( Array.isArray( shapes ) === false ) { - // helper variables + addShape( shapes ); - var index = 0; - var indexArray = []; - var halfHeight = height / 2; - var groupStart = 0; + } else { - // generate geometry + for ( var i = 0; i < shapes.length; i ++ ) { - generateTorso(); + addShape( shapes[ i ] ); - if ( openEnded === false ) { + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support - if ( radiusTop > 0 ) { generateCap( true ); } - if ( radiusBottom > 0 ) { generateCap( false ); } + groupStart += groupCount; + groupCount = 0; } - // build geometry + } - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // build geometry - function generateTorso() { + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - var x, y; - var normal = new Vector3(); - var vertex = new Vector3(); - var groupCount = 0; + // helper functions - // this will be used to calculate the normal - var slope = ( radiusBottom - radiusTop ) / height; + function addShape( shape ) { - // generate vertices, normals and uvs + var i, l, shapeHole; - for ( y = 0; y <= heightSegments; y ++ ) { + var indexOffset = vertices.length / 3; + var points = shape.extractPoints( curveSegments ); - var indexRow = []; + var shapeVertices = points.shape; + var shapeHoles = points.holes; - var v = y / heightSegments; + // check direction of vertices - // calculate the radius of the current row + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + shapeVertices = shapeVertices.reverse(); - for ( x = 0; x <= radialSegments; x ++ ) { + } - var u = x / radialSegments; + for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { - var theta = u * thetaLength + thetaStart; + shapeHole = shapeHoles[ i ]; - var sinTheta = Math.sin( theta ); - var cosTheta = Math.cos( theta ); + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { - // vertex + shapeHoles[ i ] = shapeHole.reverse(); - vertex.x = radius * sinTheta; - vertex.y = - v * height + halfHeight; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + } - normal.set( sinTheta, slope, cosTheta ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); - // uv + // join vertices of inner and outer paths to a single array - uvs.push( u, 1 - v ); + for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { - // save index of vertex in respective row + shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); - indexRow.push( index ++ ); + } - } + // vertices, normals, uvs - // now save vertices of the row in our index array + for ( i = 0, l = shapeVertices.length; i < l; i ++ ) { - indexArray.push( indexRow ); + var vertex = shapeVertices[ i ]; - } + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs - // generate indices + } - for ( x = 0; x < radialSegments; x ++ ) { + // incides - for ( y = 0; y < heightSegments; y ++ ) { + for ( i = 0, l = faces.length; i < l; i ++ ) { - // we use the index array to access the correct indices + var face = faces[ i ]; - var a = indexArray[ y ][ x ]; - var b = indexArray[ y + 1 ][ x ]; - var c = indexArray[ y + 1 ][ x + 1 ]; - var d = indexArray[ y ][ x + 1 ]; + var a = face[ 0 ] + indexOffset; + var b = face[ 1 ] + indexOffset; + var c = face[ 2 ] + indexOffset; - // faces + indices.push( a, b, c ); + groupCount += 3; - indices.push( a, b, d ); - indices.push( b, c, d ); + } - // update group counter + } - groupCount += 6; +} - } +ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry; - } +ShapeBufferGeometry.prototype.toJSON = function () { - // add a group to the geometry. this will ensure multi material support + var data = BufferGeometry.prototype.toJSON.call( this ); - scope.addGroup( groupStart, groupCount, 0 ); + var shapes = this.parameters.shapes; - // calculate new start value for groups + return toJSON$1( shapes, data ); - groupStart += groupCount; +}; - } +// - function generateCap( top ) { +function toJSON$1( shapes, data ) { - var x, centerIndexStart, centerIndexEnd; + data.shapes = []; - var uv = new Vector2(); - var vertex = new Vector3(); + if ( Array.isArray( shapes ) ) { - var groupCount = 0; + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + var shape = shapes[ i ]; - // save the index of the first center vertex - centerIndexStart = index; + data.shapes.push( shape.uuid ); - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + } - for ( x = 1; x <= radialSegments; x ++ ) { + } else { - // vertex + data.shapes.push( shapes.uuid ); - vertices.push( 0, halfHeight * sign, 0 ); + } - // normal + return data; - normals.push( 0, sign, 0 ); +} - // uv +/** + * @author WestLangley / http://github.com/WestLangley + * @author Mugen87 / https://github.com/Mugen87 + */ - uvs.push( 0.5, 0.5 ); +function EdgesGeometry( geometry, thresholdAngle ) { - // increase index + BufferGeometry.call( this ); - index ++; + this.type = 'EdgesGeometry'; - } + this.parameters = { + thresholdAngle: thresholdAngle + }; - // save the index of the last center vertex + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; - centerIndexEnd = index; + // buffer - // now we generate the surrounding vertices, normals and uvs + var vertices = []; - for ( x = 0; x <= radialSegments; x ++ ) { + // helper variables - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle ); + var edge = [ 0, 0 ], edges = {}, edge1, edge2; + var key, keys = [ 'a', 'b', 'c' ]; - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + // prepare source geometry - // vertex + var geometry2; - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( geometry.isBufferGeometry ) { - // normal + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); - normals.push( 0, sign, 0 ); + } else { - // uv + geometry2 = geometry.clone(); - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.push( uv.x, uv.y ); + } - // increase index + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); - index ++; + var sourceVertices = geometry2.vertices; + var faces = geometry2.faces; - } + // now create a data structure where each entry represents an edge with its adjoining faces - // generate indices + for ( var i = 0, l = faces.length; i < l; i ++ ) { - for ( x = 0; x < radialSegments; x ++ ) { + var face = faces[ i ]; - var c = centerIndexStart + x; - var i = centerIndexEnd + x; + for ( var j = 0; j < 3; j ++ ) { - if ( top === true ) { + edge1 = face[ keys[ j ] ]; + edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; + edge[ 0 ] = Math.min( edge1, edge2 ); + edge[ 1 ] = Math.max( edge1, edge2 ); - // face top + key = edge[ 0 ] + ',' + edge[ 1 ]; - indices.push( i, i + 1, c ); + if ( edges[ key ] === undefined ) { - } else { + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined }; - // face bottom + } else { - indices.push( i + 1, i, c ); + edges[ key ].face2 = i; - } + } + + } - groupCount += 3; + } - } + // generate vertices - // add a group to the geometry. this will ensure multi material support + for ( key in edges ) { - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + var e = edges[ key ]; - // calculate new start value for groups + // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree. - groupStart += groupCount; + if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) { + + var vertex = sourceVertices[ e.index1 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); + + vertex = sourceVertices[ e.index2 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); } } - CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - - /** - * @author abelnation / http://github.com/abelnation - */ + // build geometry - // ConeGeometry + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { +} - CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); +EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); +EdgesGeometry.prototype.constructor = EdgesGeometry; - this.type = 'ConeGeometry'; +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; +// CylinderGeometry - } +function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); - ConeGeometry.prototype.constructor = ConeGeometry; + Geometry.call( this ); - // ConeBufferGeometry + this.type = 'CylinderGeometry'; - function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.mergeVertices(); - this.type = 'ConeBufferGeometry'; +} - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; +CylinderGeometry.prototype = Object.create( Geometry.prototype ); +CylinderGeometry.prototype.constructor = CylinderGeometry; - } +// CylinderBufferGeometry - ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype ); - ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; +function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - /** - * @author benaadams / https://twitter.com/ben_a_adams - * @author Mugen87 / https://github.com/Mugen87 - * @author hughes - */ + BufferGeometry.call( this ); - // CircleGeometry + this.type = 'CylinderBufferGeometry'; - function CircleGeometry( radius, segments, thetaStart, thetaLength ) { + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - Geometry.call( this ); + var scope = this; - this.type = 'CircleGeometry'; + radiusTop = radiusTop !== undefined ? radiusTop : 1; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 1; + height = height || 1; - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; - this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); - this.mergeVertices(); + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - } + // buffers - CircleGeometry.prototype = Object.create( Geometry.prototype ); - CircleGeometry.prototype.constructor = CircleGeometry; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - // CircleBufferGeometry + // helper variables - function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { + var index = 0; + var indexArray = []; + var halfHeight = height / 2; + var groupStart = 0; - BufferGeometry.call( this ); + // generate geometry - this.type = 'CircleBufferGeometry'; + generateTorso(); - this.parameters = { - radius: radius, - segments: segments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( openEnded === false ) { - radius = radius || 1; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + } - // buffers + // build geometry - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - // helper variables + function generateTorso() { - var i, s; + var x, y; + var normal = new Vector3(); var vertex = new Vector3(); - var uv = new Vector2(); - // center point + var groupCount = 0; - vertices.push( 0, 0, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( 0.5, 0.5 ); + // this will be used to calculate the normal + var slope = ( radiusBottom - radiusTop ) / height; - for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) { + // generate vertices, normals and uvs - var segment = thetaStart + s / segments * thetaLength; + for ( y = 0; y <= heightSegments; y ++ ) { - // vertex + var indexRow = []; - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + var v = y / heightSegments; - vertices.push( vertex.x, vertex.y, vertex.z ); + // calculate the radius of the current row - // normal + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; - normals.push( 0, 0, 1 ); + for ( x = 0; x <= radialSegments; x ++ ) { - // uvs + var u = x / radialSegments; - uv.x = ( vertices[ i ] / radius + 1 ) / 2; - uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + var theta = u * thetaLength + thetaStart; - uvs.push( uv.x, uv.y ); + var sinTheta = Math.sin( theta ); + var cosTheta = Math.cos( theta ); - } + // vertex - // indices + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - for ( i = 1; i <= segments; i ++ ) { + // normal - indices.push( i, i + 1, 0 ); + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - } + // uv - // build geometry + uvs.push( u, 1 - v ); - this.setIndex( indices ); - this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // save index of vertex in respective row - } + indexRow.push( index ++ ); - CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; - - - - var Geometries = /*#__PURE__*/Object.freeze({ - __proto__: null, - WireframeGeometry: WireframeGeometry, - ParametricGeometry: ParametricGeometry, - ParametricBufferGeometry: ParametricBufferGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TetrahedronBufferGeometry: TetrahedronBufferGeometry, - OctahedronGeometry: OctahedronGeometry, - OctahedronBufferGeometry: OctahedronBufferGeometry, - IcosahedronGeometry: IcosahedronGeometry, - IcosahedronBufferGeometry: IcosahedronBufferGeometry, - DodecahedronGeometry: DodecahedronGeometry, - DodecahedronBufferGeometry: DodecahedronBufferGeometry, - PolyhedronGeometry: PolyhedronGeometry, - PolyhedronBufferGeometry: PolyhedronBufferGeometry, - TubeGeometry: TubeGeometry, - TubeBufferGeometry: TubeBufferGeometry, - TorusKnotGeometry: TorusKnotGeometry, - TorusKnotBufferGeometry: TorusKnotBufferGeometry, - TorusGeometry: TorusGeometry, - TorusBufferGeometry: TorusBufferGeometry, - TextGeometry: TextGeometry, - TextBufferGeometry: TextBufferGeometry, - SphereGeometry: SphereGeometry, - SphereBufferGeometry: SphereBufferGeometry, - RingGeometry: RingGeometry, - RingBufferGeometry: RingBufferGeometry, - PlaneGeometry: PlaneGeometry, - PlaneBufferGeometry: PlaneBufferGeometry, - LatheGeometry: LatheGeometry, - LatheBufferGeometry: LatheBufferGeometry, - ShapeGeometry: ShapeGeometry, - ShapeBufferGeometry: ShapeBufferGeometry, - ExtrudeGeometry: ExtrudeGeometry, - ExtrudeBufferGeometry: ExtrudeBufferGeometry, - EdgesGeometry: EdgesGeometry, - ConeGeometry: ConeGeometry, - ConeBufferGeometry: ConeBufferGeometry, - CylinderGeometry: CylinderGeometry, - CylinderBufferGeometry: CylinderBufferGeometry, - CircleGeometry: CircleGeometry, - CircleBufferGeometry: CircleBufferGeometry, - BoxGeometry: BoxGeometry, - BoxBufferGeometry: BoxBufferGeometry - }); + } - /** - * @author mrdoob / http://mrdoob.com/ - * - * parameters = { - * color: - * } - */ + // now save vertices of the row in our index array - function ShadowMaterial( parameters ) { + indexArray.push( indexRow ); - Material.call( this ); + } - this.type = 'ShadowMaterial'; + // generate indices - this.color = new Color( 0x000000 ); - this.transparent = true; + for ( x = 0; x < radialSegments; x ++ ) { - this.setValues( parameters ); + for ( y = 0; y < heightSegments; y ++ ) { - } + // we use the index array to access the correct indices - ShadowMaterial.prototype = Object.create( Material.prototype ); - ShadowMaterial.prototype.constructor = ShadowMaterial; + var a = indexArray[ y ][ x ]; + var b = indexArray[ y + 1 ][ x ]; + var c = indexArray[ y + 1 ][ x + 1 ]; + var d = indexArray[ y ][ x + 1 ]; - ShadowMaterial.prototype.isShadowMaterial = true; + // faces - ShadowMaterial.prototype.copy = function ( source ) { + indices.push( a, b, d ); + indices.push( b, c, d ); - Material.prototype.copy.call( this, source ); + // update group counter - this.color.copy( source.color ); + groupCount += 6; - return this; + } - }; + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + // add a group to the geometry. this will ensure multi material support - function RawShaderMaterial( parameters ) { + scope.addGroup( groupStart, groupCount, 0 ); - ShaderMaterial.call( this, parameters ); + // calculate new start value for groups - this.type = 'RawShaderMaterial'; + groupStart += groupCount; } - RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); - RawShaderMaterial.prototype.constructor = RawShaderMaterial; + function generateCap( top ) { - RawShaderMaterial.prototype.isRawShaderMaterial = true; + var x, centerIndexStart, centerIndexEnd; - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * roughness: , - * metalness: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * roughnessMap: new THREE.Texture( ), - * - * metalnessMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * envMapIntensity: - * - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + var uv = new Vector2(); + var vertex = new Vector3(); - function MeshStandardMaterial( parameters ) { + var groupCount = 0; - Material.call( this ); + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; - this.defines = { 'STANDARD': '' }; + // save the index of the first center vertex + centerIndexStart = index; - this.type = 'MeshStandardMaterial'; + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + for ( x = 1; x <= radialSegments; x ++ ) { - this.map = null; + // vertex - this.lightMap = null; - this.lightMapIntensity = 1.0; + vertices.push( 0, halfHeight * sign, 0 ); - this.aoMap = null; - this.aoMapIntensity = 1.0; + // normal - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + normals.push( 0, sign, 0 ); - this.bumpMap = null; - this.bumpScale = 1; + // uv - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + uvs.push( 0.5, 0.5 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + // increase index - this.roughnessMap = null; + index ++; - this.metalnessMap = null; + } - this.alphaMap = null; + // save the index of the last center vertex - this.envMap = null; - this.envMapIntensity = 1.0; + centerIndexEnd = index; - this.refractionRatio = 0.98; + // now we generate the surrounding vertices, normals and uvs - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + for ( x = 0; x <= radialSegments; x ++ ) { - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; - this.setValues( parameters ); + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); - } + // vertex - MeshStandardMaterial.prototype = Object.create( Material.prototype ); - MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); - MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + // normal - MeshStandardMaterial.prototype.copy = function ( source ) { + normals.push( 0, sign, 0 ); - Material.prototype.copy.call( this, source ); + // uv - this.defines = { 'STANDARD': '' }; + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + // increase index - this.map = source.map; + index ++; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + } - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + // generate indices - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + for ( x = 0; x < radialSegments; x ++ ) { - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + var c = centerIndexStart + x; + var i = centerIndexEnd + x; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + if ( top === true ) { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + // face top - this.roughnessMap = source.roughnessMap; + indices.push( i, i + 1, c ); - this.metalnessMap = source.metalnessMap; + } else { - this.alphaMap = source.alphaMap; + // face bottom - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + indices.push( i + 1, i, c ); - this.refractionRatio = source.refractionRatio; + } - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + groupCount += 3; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + } - return this; + // add a group to the geometry. this will ensure multi material support - }; + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * clearcoat: - * clearcoatRoughness: - * - * sheen: - * - * clearcoatNormalScale: , - * clearcoatNormalMap: new THREE.Texture( ), - * } - */ + // calculate new start value for groups - function MeshPhysicalMaterial( parameters ) { + groupStart += groupCount; - MeshStandardMaterial.call( this ); + } - this.defines = { +} - 'STANDARD': '', - 'PHYSICAL': '' +CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; - }; +/** + * @author abelnation / http://github.com/abelnation + */ - this.type = 'MeshPhysicalMaterial'; +// ConeGeometry - this.reflectivity = 0.5; // maps to F0 = 0.04 +function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - this.clearcoat = 0.0; - this.clearcoatRoughness = 0.0; + CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - this.sheen = null; // null will disable sheen bsdf + this.type = 'ConeGeometry'; - this.clearcoatNormalScale = new Vector2( 1, 1 ); - this.clearcoatNormalMap = null; + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.transparency = 0.0; +} - this.setValues( parameters ); +ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); +ConeGeometry.prototype.constructor = ConeGeometry; - } +// ConeBufferGeometry - MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; +function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { - MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); - MeshPhysicalMaterial.prototype.copy = function ( source ) { + this.type = 'ConeBufferGeometry'; - MeshStandardMaterial.prototype.copy.call( this, source ); + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.defines = { +} - 'STANDARD': '', - 'PHYSICAL': '' +ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype ); +ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; - }; +/** + * @author benaadams / https://twitter.com/ben_a_adams + * @author Mugen87 / https://github.com/Mugen87 + * @author hughes + */ - this.reflectivity = source.reflectivity; +// CircleGeometry - this.clearcoat = source.clearcoat; - this.clearcoatRoughness = source.clearcoatRoughness; +function CircleGeometry( radius, segments, thetaStart, thetaLength ) { - if ( source.sheen ) { this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); } - else { this.sheen = null; } + Geometry.call( this ); - this.clearcoatNormalMap = source.clearcoatNormalMap; - this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + this.type = 'CircleGeometry'; - this.transparency = source.transparency; + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - return this; + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + this.mergeVertices(); - }; +} - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.MultiplyOperation, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ +CircleGeometry.prototype = Object.create( Geometry.prototype ); +CircleGeometry.prototype.constructor = CircleGeometry; - function MeshPhongMaterial( parameters ) { +// CircleBufferGeometry - Material.call( this ); +function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { - this.type = 'MeshPhongMaterial'; + BufferGeometry.call( this ); - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + this.type = 'CircleBufferGeometry'; - this.map = null; + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; - this.lightMap = null; - this.lightMapIntensity = 1.0; + radius = radius || 1; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; - this.aoMap = null; - this.aoMapIntensity = 1.0; + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + // buffers - this.bumpMap = null; - this.bumpScale = 1; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + // helper variables - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + var i, s; + var vertex = new Vector3(); + var uv = new Vector2(); - this.specularMap = null; + // center point - this.alphaMap = null; + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + var segment = thetaStart + s / segments * thetaLength; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + // vertex - this.setValues( parameters ); + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); - } + vertices.push( vertex.x, vertex.y, vertex.z ); - MeshPhongMaterial.prototype = Object.create( Material.prototype ); - MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + // normal - MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + normals.push( 0, 0, 1 ); - MeshPhongMaterial.prototype.copy = function ( source ) { + // uvs - Material.prototype.copy.call( this, source ); + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + uvs.push( uv.x, uv.y ); - this.map = source.map; + } - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + // indices - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + for ( i = 1; i <= segments; i ++ ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + indices.push( i, i + 1, 0 ); - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + } - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + // build geometry - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + this.setIndex( indices ); + this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - this.specularMap = source.specularMap; +} - this.alphaMap = source.alphaMap; +CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); +CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; +var Geometries = /*#__PURE__*/Object.freeze({ + __proto__: null, + WireframeGeometry: WireframeGeometry, + ParametricGeometry: ParametricGeometry, + ParametricBufferGeometry: ParametricBufferGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TetrahedronBufferGeometry: TetrahedronBufferGeometry, + OctahedronGeometry: OctahedronGeometry, + OctahedronBufferGeometry: OctahedronBufferGeometry, + IcosahedronGeometry: IcosahedronGeometry, + IcosahedronBufferGeometry: IcosahedronBufferGeometry, + DodecahedronGeometry: DodecahedronGeometry, + DodecahedronBufferGeometry: DodecahedronBufferGeometry, + PolyhedronGeometry: PolyhedronGeometry, + PolyhedronBufferGeometry: PolyhedronBufferGeometry, + TubeGeometry: TubeGeometry, + TubeBufferGeometry: TubeBufferGeometry, + TorusKnotGeometry: TorusKnotGeometry, + TorusKnotBufferGeometry: TorusKnotBufferGeometry, + TorusGeometry: TorusGeometry, + TorusBufferGeometry: TorusBufferGeometry, + TextGeometry: TextGeometry, + TextBufferGeometry: TextBufferGeometry, + SphereGeometry: SphereGeometry, + SphereBufferGeometry: SphereBufferGeometry, + RingGeometry: RingGeometry, + RingBufferGeometry: RingBufferGeometry, + PlaneGeometry: PlaneGeometry, + PlaneBufferGeometry: PlaneBufferGeometry, + LatheGeometry: LatheGeometry, + LatheBufferGeometry: LatheBufferGeometry, + ShapeGeometry: ShapeGeometry, + ShapeBufferGeometry: ShapeBufferGeometry, + ExtrudeGeometry: ExtrudeGeometry, + ExtrudeBufferGeometry: ExtrudeBufferGeometry, + EdgesGeometry: EdgesGeometry, + ConeGeometry: ConeGeometry, + ConeBufferGeometry: ConeBufferGeometry, + CylinderGeometry: CylinderGeometry, + CylinderBufferGeometry: CylinderBufferGeometry, + CircleGeometry: CircleGeometry, + CircleBufferGeometry: CircleBufferGeometry, + BoxGeometry: BoxGeometry, + BoxBufferGeometry: BoxBufferGeometry +}); + +/** + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * color: + * } + */ + +function ShadowMaterial( parameters ) { + + Material.call( this ); + + this.type = 'ShadowMaterial'; + + this.color = new Color( 0x000000 ); + this.transparent = true; + + this.setValues( parameters ); + +} + +ShadowMaterial.prototype = Object.create( Material.prototype ); +ShadowMaterial.prototype.constructor = ShadowMaterial; + +ShadowMaterial.prototype.isShadowMaterial = true; + +ShadowMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + + return this; + +}; + +/** + * @author mrdoob / http://mrdoob.com/ + */ + +function RawShaderMaterial( parameters ) { + + ShaderMaterial.call( this, parameters ); + + this.type = 'RawShaderMaterial'; + +} + +RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); +RawShaderMaterial.prototype.constructor = RawShaderMaterial; + +RawShaderMaterial.prototype.isRawShaderMaterial = true; + +/** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * roughness: , + * metalness: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalMapType: THREE.TangentSpaceNormalMap, + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * roughnessMap: new THREE.Texture( ), + * + * metalnessMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * envMapIntensity: + * + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; +function MeshStandardMaterial( parameters ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + Material.call( this ); - return this; + this.defines = { 'STANDARD': '' }; - }; + this.type = 'MeshStandardMaterial'; - /** - * @author takahirox / http://github.com/takahirox - * - * parameters = { - * gradientMap: new THREE.Texture( ) - * } - */ + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 1.0; + this.metalness = 0.0; - function MeshToonMaterial( parameters ) { + this.map = null; - MeshPhongMaterial.call( this ); + this.lightMap = null; + this.lightMapIntensity = 1.0; - this.defines = { 'TOON': '' }; + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.type = 'MeshToonMaterial'; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - this.gradientMap = null; + this.bumpMap = null; + this.bumpScale = 1; - this.setValues( parameters ); + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - } + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype ); - MeshToonMaterial.prototype.constructor = MeshToonMaterial; + this.roughnessMap = null; - MeshToonMaterial.prototype.isMeshToonMaterial = true; + this.metalnessMap = null; - MeshToonMaterial.prototype.copy = function ( source ) { + this.alphaMap = null; - MeshPhongMaterial.prototype.copy.call( this, source ); + this.envMap = null; + this.envMapIntensity = 1.0; + + this.refractionRatio = 0.98; - this.gradientMap = source.gradientMap; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - return this; + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - }; + this.vertexTangents = false; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * opacity: , - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + this.setValues( parameters ); - function MeshNormalMaterial( parameters ) { +} - Material.call( this ); +MeshStandardMaterial.prototype = Object.create( Material.prototype ); +MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; - this.type = 'MeshNormalMaterial'; +MeshStandardMaterial.prototype.isMeshStandardMaterial = true; - this.bumpMap = null; - this.bumpScale = 1; +MeshStandardMaterial.prototype.copy = function ( source ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + Material.prototype.copy.call( this, source ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + this.defines = { 'STANDARD': '' }; - this.wireframe = false; - this.wireframeLinewidth = 1; + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; - this.fog = false; + this.map = source.map; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.setValues( parameters ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - MeshNormalMaterial.prototype = Object.create( Material.prototype ); - MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - MeshNormalMaterial.prototype.copy = function ( source ) { + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - Material.prototype.copy.call( this, source ); + this.roughnessMap = source.roughnessMap; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.metalnessMap = source.metalnessMap; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + this.alphaMap = source.alphaMap; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + this.refractionRatio = source.refractionRatio; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - return this; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }; + this.vertexTangents = source.vertexTangents; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + return this; - function MeshLambertMaterial( parameters ) { +}; - Material.call( this ); +/** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * clearcoat: , + * clearcoatMap: new THREE.Texture( ), + * clearcoatRoughness: , + * clearcoatRoughnessMap: new THREE.Texture( ), + * clearcoatNormalScale: , + * clearcoatNormalMap: new THREE.Texture( ), + * + * reflectivity: , + * + * sheen: , + * + * transparency: + * } + */ - this.type = 'MeshLambertMaterial'; +function MeshPhysicalMaterial( parameters ) { - this.color = new Color( 0xffffff ); // diffuse + MeshStandardMaterial.call( this ); - this.map = null; + this.defines = { - this.lightMap = null; - this.lightMapIntensity = 1.0; + 'STANDARD': '', + 'PHYSICAL': '' - this.aoMap = null; - this.aoMapIntensity = 1.0; + }; - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + this.type = 'MeshPhysicalMaterial'; - this.specularMap = null; + this.clearcoat = 0.0; + this.clearcoatMap = null; + this.clearcoatRoughness = 0.0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2( 1, 1 ); + this.clearcoatNormalMap = null; - this.alphaMap = null; + this.reflectivity = 0.5; // maps to F0 = 0.04 - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + this.sheen = null; // null will disable sheen bsdf - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + this.transparency = 0.0; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.setValues( parameters ); - this.setValues( parameters ); +} - } +MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); +MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; - MeshLambertMaterial.prototype = Object.create( Material.prototype ); - MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; +MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; - MeshLambertMaterial.prototype.isMeshLambertMaterial = true; +MeshPhysicalMaterial.prototype.copy = function ( source ) { - MeshLambertMaterial.prototype.copy = function ( source ) { + MeshStandardMaterial.prototype.copy.call( this, source ); - Material.prototype.copy.call( this, source ); + this.defines = { - this.color.copy( source.color ); + 'STANDARD': '', + 'PHYSICAL': '' - this.map = source.map; + }; - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); + + this.reflectivity = source.reflectivity; + + if ( source.sheen ) { + + this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); + + } else { + + this.sheen = null; + + } + + this.transparency = source.transparency; + + return this; + +}; + +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * specular: , + * shininess: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalMapType: THREE.TangentSpaceNormalMap, + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.MultiplyOperation, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; +function MeshPhongMaterial( parameters ) { - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + Material.call( this ); - this.specularMap = source.specularMap; + this.type = 'MeshPhongMaterial'; - this.alphaMap = source.alphaMap; + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + this.map = null; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + this.lightMap = null; + this.lightMapIntensity = 1.0; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + this.aoMap = null; + this.aoMapIntensity = 1.0; - return this; + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - }; + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + +} + +MeshPhongMaterial.prototype = Object.create( Material.prototype ); +MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + +MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + +MeshPhongMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * opacity: , - * - * matcap: new THREE.Texture( ), - * - * map: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalMapType: THREE.TangentSpaceNormalMap, - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * alphaMap: new THREE.Texture( ), - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + this.specularMap = source.specularMap; - function MeshMatcapMaterial( parameters ) { + this.alphaMap = source.alphaMap; - Material.call( this ); + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - this.defines = { 'MATCAP': '' }; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.type = 'MeshMatcapMaterial'; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.color = new Color( 0xffffff ); // diffuse + return this; - this.matcap = null; +}; - this.map = null; +/** + * @author takahirox / http://github.com/takahirox + * + * parameters = { + * color: , + * specular: , + * shininess: , + * + * map: new THREE.Texture( ), + * gradientMap: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalMapType: THREE.TangentSpaceNormalMap, + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - this.bumpMap = null; - this.bumpScale = 1; +function MeshToonMaterial( parameters ) { - this.normalMap = null; - this.normalMapType = TangentSpaceNormalMap; - this.normalScale = new Vector2( 1, 1 ); + Material.call( this ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + this.defines = { 'TOON': '' }; - this.alphaMap = null; + this.type = 'MeshToonMaterial'; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + this.color = new Color( 0xffffff ); + this.specular = new Color( 0x111111 ); + this.shininess = 30; - this.setValues( parameters ); + this.map = null; + this.gradientMap = null; - } + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + +} + +MeshToonMaterial.prototype = Object.create( Material.prototype ); +MeshToonMaterial.prototype.constructor = MeshToonMaterial; + +MeshToonMaterial.prototype.isMeshToonMaterial = true; + +MeshToonMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + this.gradientMap = source.gradientMap; - MeshMatcapMaterial.prototype = Object.create( Material.prototype ); - MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - MeshMatcapMaterial.prototype.copy = function ( source ) { + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - Material.prototype.copy.call( this, source ); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - this.defines = { 'MATCAP': '' }; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - this.color.copy( source.color ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - this.matcap = source.matcap; + this.specularMap = source.specularMap; - this.map = source.map; + this.alphaMap = source.alphaMap; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - this.normalMap = source.normalMap; - this.normalMapType = source.normalMapType; - this.normalScale.copy( source.normalScale ); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + return this; - this.alphaMap = source.alphaMap; +}; - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; +/** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * opacity: , + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalMapType: THREE.TangentSpaceNormalMap, + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + +function MeshNormalMaterial( parameters ) { - return this; + Material.call( this ); - }; + this.type = 'MeshNormalMaterial'; - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + this.bumpMap = null; + this.bumpScale = 1; - function LineDashedMaterial( parameters ) { + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - LineBasicMaterial.call( this ); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - this.type = 'LineDashedMaterial'; + this.wireframe = false; + this.wireframeLinewidth = 1; - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + this.fog = false; - this.setValues( parameters ); + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - } + this.setValues( parameters ); - LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype ); - LineDashedMaterial.prototype.constructor = LineDashedMaterial; +} + +MeshNormalMaterial.prototype = Object.create( Material.prototype ); +MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + +MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + +MeshNormalMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - LineDashedMaterial.prototype.isLineDashedMaterial = true; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - LineDashedMaterial.prototype.copy = function ( source ) { + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - LineBasicMaterial.prototype.copy.call( this, source ); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + return this; - return this; +}; - }; +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ +function MeshLambertMaterial( parameters ) { + Material.call( this ); - var Materials = /*#__PURE__*/Object.freeze({ - __proto__: null, - ShadowMaterial: ShadowMaterial, - SpriteMaterial: SpriteMaterial, - RawShaderMaterial: RawShaderMaterial, - ShaderMaterial: ShaderMaterial, - PointsMaterial: PointsMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshToonMaterial: MeshToonMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshDistanceMaterial: MeshDistanceMaterial, - MeshBasicMaterial: MeshBasicMaterial, - MeshMatcapMaterial: MeshMatcapMaterial, - LineDashedMaterial: LineDashedMaterial, - LineBasicMaterial: LineBasicMaterial, - Material: Material - }); + this.type = 'MeshLambertMaterial'; - /** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + this.color = new Color( 0xffffff ); // diffuse - var AnimationUtils = { + this.map = null; - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function ( array, from, to ) { + this.lightMap = null; + this.lightMapIntensity = 1.0; - if ( AnimationUtils.isTypedArray( array ) ) { + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; - // in ios9 array.subarray(from, undefined) will return empty array - // but array.subarray(from) or array.subarray(from, len) is correct - return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + this.specularMap = null; - } + this.alphaMap = null; - return array.slice( from, to ); + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - }, + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - // converts an array to a specific type - convertArray: function ( array, type, forceClone ) { + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) { return array; } + this.setValues( parameters ); - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { +} - return new type( array ); // create typed array +MeshLambertMaterial.prototype = Object.create( Material.prototype ); +MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; - } +MeshLambertMaterial.prototype.isMeshLambertMaterial = true; - return Array.prototype.slice.call( array ); // create Array +MeshLambertMaterial.prototype.copy = function ( source ) { - }, + Material.prototype.copy.call( this, source ); - isTypedArray: function ( object ) { + this.color.copy( source.color ); - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + this.map = source.map; - }, + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - // returns an array by which times and values can be sorted - getKeyframeOrder: function ( times ) { + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - function compareTime( i, j ) { + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; - return times[ i ] - times[ j ]; + this.specularMap = source.specularMap; - } + this.alphaMap = source.alphaMap; - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; } + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - result.sort( compareTime ); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - return result; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - }, + return this; - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function ( values, stride, order ) { +}; - var nValues = values.length; - var result = new values.constructor( nValues ); +/** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * opacity: , + * + * matcap: new THREE.Texture( ), + * + * map: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalMapType: THREE.TangentSpaceNormalMap, + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * alphaMap: new THREE.Texture( ), + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { +function MeshMatcapMaterial( parameters ) { - var srcOffset = order[ i ] * stride; + Material.call( this ); - for ( var j = 0; j !== stride; ++ j ) { + this.defines = { 'MATCAP': '' }; - result[ dstOffset ++ ] = values[ srcOffset + j ]; + this.type = 'MeshMatcapMaterial'; - } + this.color = new Color( 0xffffff ); // diffuse - } + this.matcap = null; - return result; + this.map = null; - }, + this.bumpMap = null; + this.bumpScale = 1; - // function for parsing AOS keyframe formats - flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2( 1, 1 ); - var i = 1, key = jsonKeys[ 0 ]; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + this.alphaMap = null; - key = jsonKeys[ i ++ ]; + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; - } + this.setValues( parameters ); - if ( key === undefined ) { return; } // no data +} - var value = key[ valuePropertyName ]; - if ( value === undefined ) { return; } // no data +MeshMatcapMaterial.prototype = Object.create( Material.prototype ); +MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial; - if ( Array.isArray( value ) ) { +MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; - do { +MeshMatcapMaterial.prototype.copy = function ( source ) { - value = key[ valuePropertyName ]; + Material.prototype.copy.call( this, source ); - if ( value !== undefined ) { + this.defines = { 'MATCAP': '' }; - times.push( key.time ); - values.push.apply( values, value ); // push all elements + this.color.copy( source.color ); - } + this.matcap = source.matcap; - key = jsonKeys[ i ++ ]; + this.map = source.map; - } while ( key !== undefined ); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; - } else if ( value.toArray !== undefined ) { + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy( source.normalScale ); - // ...assume THREE.Math-ish + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - do { + this.alphaMap = source.alphaMap; - value = key[ valuePropertyName ]; + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - if ( value !== undefined ) { + return this; - times.push( key.time ); - value.toArray( values, values.length ); +}; - } +/** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ - key = jsonKeys[ i ++ ]; +function LineDashedMaterial( parameters ) { - } while ( key !== undefined ); + LineBasicMaterial.call( this ); - } else { + this.type = 'LineDashedMaterial'; - // otherwise push as-is + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; - do { + this.setValues( parameters ); - value = key[ valuePropertyName ]; +} - if ( value !== undefined ) { +LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype ); +LineDashedMaterial.prototype.constructor = LineDashedMaterial; - times.push( key.time ); - values.push( value ); +LineDashedMaterial.prototype.isLineDashedMaterial = true; - } +LineDashedMaterial.prototype.copy = function ( source ) { - key = jsonKeys[ i ++ ]; + LineBasicMaterial.prototype.copy.call( this, source ); - } while ( key !== undefined ); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; - } + return this; - }, +}; - subclip: function ( sourceClip, name, startFrame, endFrame, fps ) { +var Materials = /*#__PURE__*/Object.freeze({ + __proto__: null, + ShadowMaterial: ShadowMaterial, + SpriteMaterial: SpriteMaterial, + RawShaderMaterial: RawShaderMaterial, + ShaderMaterial: ShaderMaterial, + PointsMaterial: PointsMaterial, + MeshPhysicalMaterial: MeshPhysicalMaterial, + MeshStandardMaterial: MeshStandardMaterial, + MeshPhongMaterial: MeshPhongMaterial, + MeshToonMaterial: MeshToonMaterial, + MeshNormalMaterial: MeshNormalMaterial, + MeshLambertMaterial: MeshLambertMaterial, + MeshDepthMaterial: MeshDepthMaterial, + MeshDistanceMaterial: MeshDistanceMaterial, + MeshBasicMaterial: MeshBasicMaterial, + MeshMatcapMaterial: MeshMatcapMaterial, + LineDashedMaterial: LineDashedMaterial, + LineBasicMaterial: LineBasicMaterial, + Material: Material +}); - fps = fps || 30; +/** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - var clip = sourceClip.clone(); +var AnimationUtils = { - clip.name = name; + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function ( array, from, to ) { - var tracks = []; + if ( AnimationUtils.isTypedArray( array ) ) { - for ( var i = 0; i < clip.tracks.length; ++ i ) { + // in ios9 array.subarray(from, undefined) will return empty array + // but array.subarray(from) or array.subarray(from, len) is correct + return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); - var track = clip.tracks[ i ]; - var valueSize = track.getValueSize(); + } - var times = []; - var values = []; + return array.slice( from, to ); - for ( var j = 0; j < track.times.length; ++ j ) { + }, - var frame = track.times[ j ] * fps; + // converts an array to a specific type + convertArray: function ( array, type, forceClone ) { - if ( frame < startFrame || frame >= endFrame ) { continue; } + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - times.push( track.times[ j ] ); + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - for ( var k = 0; k < valueSize; ++ k ) { + return new type( array ); // create typed array - values.push( track.values[ j * valueSize + k ] ); + } - } + return Array.prototype.slice.call( array ); // create Array - } + }, - if ( times.length === 0 ) { continue; } + isTypedArray: function ( object ) { - track.times = AnimationUtils.convertArray( times, track.times.constructor ); - track.values = AnimationUtils.convertArray( values, track.values.constructor ); + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); - tracks.push( track ); + }, - } + // returns an array by which times and values can be sorted + getKeyframeOrder: function ( times ) { - clip.tracks = tracks; + function compareTime( i, j ) { - // find minimum .times value across all tracks in the trimmed clip + return times[ i ] - times[ j ]; - var minStartTime = Infinity; + } - for ( var i = 0; i < clip.tracks.length; ++ i ) { + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { + result.sort( compareTime ); - minStartTime = clip.tracks[ i ].times[ 0 ]; + return result; - } + }, - } + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function ( values, stride, order ) { - // shift all tracks such that clip begins at t=0 + var nValues = values.length; + var result = new values.constructor( nValues ); - for ( var i = 0; i < clip.tracks.length; ++ i ) { + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - clip.tracks[ i ].shift( - 1 * minStartTime ); + var srcOffset = order[ i ] * stride; - } + for ( var j = 0; j !== stride; ++ j ) { - clip.resetDuration(); + result[ dstOffset ++ ] = values[ srcOffset + j ]; - return clip; + } } - }; - - /** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - * @author tschw - */ + return result; - function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + }, - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + // function for parsing AOS keyframe formats + flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + var i = 1, key = jsonKeys[ 0 ]; - } + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { - Object.assign( Interpolant.prototype, { + key = jsonKeys[ i ++ ]; - evaluate: function ( t ) { + } - var pp = this.parameterPositions, - i1 = this._cachedIndex, + if ( key === undefined ) return; // no data - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - validate_interval: { + if ( Array.isArray( value ) ) { - seek: { + do { - var right; + value = key[ valuePropertyName ]; - linear_scan: { + if ( value !== undefined ) { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + times.push( key.time ); + values.push.apply( values, value ); // push all elements - for ( var giveUpAt = i1 + 2; ; ) { + } - if ( t1 === undefined ) { + key = jsonKeys[ i ++ ]; - if ( t < t0 ) { break forward_scan; } + } while ( key !== undefined ); - // after end + } else if ( value.toArray !== undefined ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + // ...assume THREE.Math-ish - } + do { - if ( i1 === giveUpAt ) { break; } // this loop + value = key[ valuePropertyName ]; - t0 = t1; - t1 = pp[ ++ i1 ]; + if ( value !== undefined ) { - if ( t < t1 ) { + times.push( key.time ); + value.toArray( values, values.length ); - // we have arrived at the sought interval - break seek; + } - } + key = jsonKeys[ i ++ ]; - } + } while ( key !== undefined ); - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + } else { - } + // otherwise push as-is - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + do { - // looping? + value = key[ valuePropertyName ]; - var t1global = pp[ 1 ]; + if ( value !== undefined ) { - if ( t < t1global ) { + times.push( key.time ); + values.push( value ); - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + } - } + key = jsonKeys[ i ++ ]; - // linear reverse scan + } while ( key !== undefined ); - for ( var giveUpAt = i1 - 2; ; ) { + } - if ( t0 === undefined ) { + }, - // before start + subclip: function ( sourceClip, name, startFrame, endFrame, fps ) { - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + fps = fps || 30; - } + var clip = sourceClip.clone(); - if ( i1 === giveUpAt ) { break; } // this loop + clip.name = name; - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + var tracks = []; - if ( t >= t0 ) { + for ( var i = 0; i < clip.tracks.length; ++ i ) { - // we have arrived at the sought interval - break seek; + var track = clip.tracks[ i ]; + var valueSize = track.getValueSize(); - } + var times = []; + var values = []; - } + for ( var j = 0; j < track.times.length; ++ j ) { - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + var frame = track.times[ j ] * fps; - } + if ( frame < startFrame || frame >= endFrame ) continue; - // the interval is valid + times.push( track.times[ j ] ); - break validate_interval; + for ( var k = 0; k < valueSize; ++ k ) { - } // linear scan + values.push( track.values[ j * valueSize + k ] ); - // binary search + } - while ( i1 < right ) { + } - var mid = ( i1 + right ) >>> 1; + if ( times.length === 0 ) continue; - if ( t < pp[ mid ] ) { + track.times = AnimationUtils.convertArray( times, track.times.constructor ); + track.values = AnimationUtils.convertArray( values, track.values.constructor ); - right = mid; + tracks.push( track ); - } else { + } - i1 = mid + 1; + clip.tracks = tracks; - } + // find minimum .times value across all tracks in the trimmed clip - } + var minStartTime = Infinity; - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + for ( var i = 0; i < clip.tracks.length; ++ i ) { - // check boundary cases, again + if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { - if ( t0 === undefined ) { + minStartTime = clip.tracks[ i ].times[ 0 ]; - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } - } + } - if ( t1 === undefined ) { + // shift all tracks such that clip begins at t=0 - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + for ( var i = 0; i < clip.tracks.length; ++ i ) { - } + clip.tracks[ i ].shift( - 1 * minStartTime ); - } // seek + } - this._cachedIndex = i1; + clip.resetDuration(); - this.intervalChanged_( i1, t0, t1 ); + return clip; - } // validate_interval + }, - return this.interpolate_( i1, t0, t, t1 ); + makeClipAdditive: function ( targetClip, referenceFrame, referenceClip, fps ) { - }, + if ( referenceFrame === undefined ) referenceFrame = 0; + if ( referenceClip === undefined ) referenceClip = targetClip; + if ( fps === undefined || fps <= 0 ) fps = 30; - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + var numTracks = targetClip.tracks.length; + var referenceTime = referenceFrame / fps; - // --- Protected interface + // Make each track's values relative to the values at the reference frame + for ( var i = 0; i < numTracks; ++ i ) { - DefaultSettings_: {}, + var referenceTrack = referenceClip.tracks[ i ]; + var referenceTrackType = referenceTrack.ValueTypeName; - getSettings_: function () { + // Skip this track if it's non-numeric + if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue; - return this.settings || this.DefaultSettings_; + // Find the track in the target clip whose name and type matches the reference track + var targetTrack = targetClip.tracks.find( function ( track ) { - }, + return track.name === referenceTrack.name + && track.ValueTypeName === referenceTrackType; - copySampleValue_: function ( index ) { + } ); - // copies a sample value to the result buffer + if ( targetTrack === undefined ) continue; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + var valueSize = referenceTrack.getValueSize(); + var lastIndex = referenceTrack.times.length - 1; + var referenceValue; - for ( var i = 0; i !== stride; ++ i ) { + // Find the value to subtract out of the track + if ( referenceTime <= referenceTrack.times[ 0 ] ) { - result[ i ] = values[ offset + i ]; + // Reference frame is earlier than the first keyframe, so just use the first keyframe + referenceValue = AnimationUtils.arraySlice( referenceTrack.values, 0, referenceTrack.valueSize ); - } + } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) { - return result; + // Reference frame is after the last keyframe, so just use the last keyframe + var startIndex = lastIndex * valueSize; + referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex ); - }, + } else { - // Template methods for derived classes: + // Interpolate to the reference value + var interpolant = referenceTrack.createInterpolant(); + interpolant.evaluate( referenceTime ); + referenceValue = interpolant.resultBuffer; - interpolate_: function ( /* i1, t0, t, t1 */ ) { + } - throw new Error( 'call to abstract method' ); - // implementations shall return this.resultBuffer + // Conjugate the quaternion + if ( referenceTrackType === 'quaternion' ) { - }, + var referenceQuat = new Quaternion( + referenceValue[ 0 ], + referenceValue[ 1 ], + referenceValue[ 2 ], + referenceValue[ 3 ] + ).normalize().conjugate(); + referenceQuat.toArray( referenceValue ); - intervalChanged_: function ( /* i1, t0, t1 */ ) { + } - // empty + // Subtract the reference value from all of the track values - } + var numTimes = targetTrack.times.length; + for ( var j = 0; j < numTimes; ++ j ) { - } ); + var valueStart = j * valueSize; - //!\ DECLARE ALIAS AFTER assign prototype ! - Object.assign( Interpolant.prototype, { + if ( referenceTrackType === 'quaternion' ) { - //( 0, t, t0 ), returns this.resultBuffer - beforeStart_: Interpolant.prototype.copySampleValue_, + // Multiply the conjugate for quaternion track types + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); - //( N-1, tN-1, t ), returns this.resultBuffer - afterEnd_: Interpolant.prototype.copySampleValue_, + } else { - } ); + // Subtract each value for all other numeric track types + for ( var k = 0; k < valueSize; ++ k ) { - /** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - * - * @author tschw - */ + targetTrack.values[ valueStart + k ] -= referenceValue[ k ]; - function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + } - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + } - this._weightPrev = - 0; - this._offsetPrev = - 0; - this._weightNext = - 0; - this._offsetNext = - 0; + } - } + } - CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + targetClip.blendMode = AdditiveAnimationBlendMode; - constructor: CubicInterpolant, + return targetClip; - DefaultSettings_: { + } - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding +}; - }, +/** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: + * + * http://www.oodesign.com/template-method-pattern.html + * + * @author tschw + */ - intervalChanged_: function ( i1, t0, t1 ) { +function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - if ( tPrev === undefined ) { +} - switch ( this.getSettings_().endingStart ) { +Object.assign( Interpolant.prototype, { - case ZeroSlopeEnding: + evaluate: function ( t ) { - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + var pp = this.parameterPositions, + i1 = this._cachedIndex, - break; + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - case WrapAroundEnding: + validate_interval: { - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + seek: { - break; + var right; - default: // ZeroCurvatureEnding + linear_scan: { - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - } + for ( var giveUpAt = i1 + 2; ; ) { - } + if ( t1 === undefined ) { - if ( tNext === undefined ) { + if ( t < t0 ) break forward_scan; - switch ( this.getSettings_().endingEnd ) { + // after end - case ZeroSlopeEnding: + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + } - break; + if ( i1 === giveUpAt ) break; // this loop - case WrapAroundEnding: + t0 = t1; + t1 = pp[ ++ i1 ]; - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + if ( t < t1 ) { - break; + // we have arrived at the sought interval + break seek; - default: // ZeroCurvatureEnding + } - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + } - } + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - } + } - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + // looping? - }, + var t1global = pp[ 1 ]; - interpolate_: function ( i1, t0, t, t1 ) { + if ( t < t1global ) { - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + } - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + // linear reverse scan - // evaluate polynomials + for ( var giveUpAt = i1 - 2; ; ) { - var sP = - wP * ppp + 2 * wP * pp - wP * p; - var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; - var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - var sN = wN * ppp - wN * pp; + if ( t0 === undefined ) { - // combine data linearly + // before start - for ( var i = 0; i !== stride; ++ i ) { + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + } - } + if ( i1 === giveUpAt ) break; // this loop - return result; + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - } + if ( t >= t0 ) { - } ); + // we have arrived at the sought interval + break seek; - /** - * @author tschw - */ + } - function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + } - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - } + } - LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + // the interval is valid - constructor: LinearInterpolant, + break validate_interval; - interpolate_: function ( i1, t0, t, t1 ) { + } // linear scan - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + // binary search - offset1 = i1 * stride, - offset0 = offset1 - stride, + while ( i1 < right ) { - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + var mid = ( i1 + right ) >>> 1; - for ( var i = 0; i !== stride; ++ i ) { + if ( t < pp[ mid ] ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + right = mid; - } + } else { - return result; + i1 = mid + 1; - } + } - } ); + } - /** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // check boundary cases, again - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + if ( t0 === undefined ) { - } + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + } - constructor: DiscreteInterpolant, + if ( t1 === undefined ) { - interpolate_: function ( i1 /*, t0, t, t1 */ ) { + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - return this.copySampleValue_( i1 - 1 ); + } - } + } // seek - } ); + this._cachedIndex = i1; - /** - * - * A timed sequence of keyframes for a specific property. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + this.intervalChanged_( i1, t0, t1 ); - function KeyframeTrack( name, times, values, interpolation ) { + } // validate_interval - if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); } - if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); } + return this.interpolate_( i1, t0, t, t1 ); - this.name = name; + }, - this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - this.setInterpolation( interpolation || this.DefaultInterpolation ); + // --- Protected interface - } + DefaultSettings_: {}, - // Static methods + getSettings_: function () { - Object.assign( KeyframeTrack, { + return this.settings || this.DefaultSettings_; - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + }, - toJSON: function ( track ) { + copySampleValue_: function ( index ) { - var trackType = track.constructor; + // copies a sample value to the result buffer - var json; + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + for ( var i = 0; i !== stride; ++ i ) { - json = trackType.toJSON( track ); + result[ i ] = values[ offset + i ]; - } else { + } - // by default, we assume the data can be serialized as-is - json = { + return result; - 'name': track.name, - 'times': AnimationUtils.convertArray( track.times, Array ), - 'values': AnimationUtils.convertArray( track.values, Array ) + }, - }; + // Template methods for derived classes: - var interpolation = track.getInterpolation(); + interpolate_: function ( /* i1, t0, t, t1 */ ) { - if ( interpolation !== track.DefaultInterpolation ) { + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer - json.interpolation = interpolation; + }, - } + intervalChanged_: function ( /* i1, t0, t1 */ ) { - } + // empty - json.type = track.ValueTypeName; // mandatory + } - return json; +} ); - } +// DECLARE ALIAS AFTER assign prototype +Object.assign( Interpolant.prototype, { - } ); + //( 0, t, t0 ), returns this.resultBuffer + beforeStart_: Interpolant.prototype.copySampleValue_, - Object.assign( KeyframeTrack.prototype, { + //( N-1, tN-1, t ), returns this.resultBuffer + afterEnd_: Interpolant.prototype.copySampleValue_, - constructor: KeyframeTrack, +} ); - TimeBufferType: Float32Array, +/** + * Fast and simple cubic spline interpolant. + * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. + * + * @author tschw + */ - ValueBufferType: Float32Array, +function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - DefaultInterpolation: InterpolateLinear, + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - InterpolantFactoryMethodDiscrete: function ( result ) { + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; - return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); +} - }, +CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - InterpolantFactoryMethodLinear: function ( result ) { + constructor: CubicInterpolant, - return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); + DefaultSettings_: { - }, + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - InterpolantFactoryMethodSmooth: function ( result ) { + }, - return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); + intervalChanged_: function ( i1, t0, t1 ) { - }, + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - setInterpolation: function ( interpolation ) { + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - var factoryMethod; + if ( tPrev === undefined ) { - switch ( interpolation ) { + switch ( this.getSettings_().endingStart ) { - case InterpolateDiscrete: + case ZeroSlopeEnding: - factoryMethod = this.InterpolantFactoryMethodDiscrete; + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; break; - case InterpolateLinear: + case WrapAroundEnding: - factoryMethod = this.InterpolantFactoryMethodLinear; + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; break; - case InterpolateSmooth: - - factoryMethod = this.InterpolantFactoryMethodSmooth; + default: // ZeroCurvatureEnding - break; + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; } - if ( factoryMethod === undefined ) { + } - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + if ( tNext === undefined ) { - if ( this.createInterpolant === undefined ) { + switch ( this.getSettings_().endingEnd ) { - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + case ZeroSlopeEnding: - this.setInterpolation( this.DefaultInterpolation ); + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - } else { + break; - throw new Error( message ); // fatal, in this case + case WrapAroundEnding: - } + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - } + break; - console.warn( 'THREE.KeyframeTrack:', message ); - return this; + default: // ZeroCurvatureEnding + + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; } - this.createInterpolant = factoryMethod; + } - return this; + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - }, + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; - getInterpolation: function () { + }, - switch ( this.createInterpolant ) { + interpolate_: function ( i1, t0, t, t1 ) { - case this.InterpolantFactoryMethodDiscrete: + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - return InterpolateDiscrete; + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - case this.InterpolantFactoryMethodLinear: + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - return InterpolateLinear; + // evaluate polynomials - case this.InterpolantFactoryMethodSmooth: + var sP = - wP * ppp + 2 * wP * pp - wP * p; + var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + var sN = wN * ppp - wN * pp; - return InterpolateSmooth; + // combine data linearly - } + for ( var i = 0; i !== stride; ++ i ) { - }, + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; - getValueSize: function () { + } - return this.values.length / this.times.length; + return result; - }, + } - // move all keyframes either forwards or backwards in time - shift: function ( timeOffset ) { +} ); - if ( timeOffset !== 0.0 ) { +/** + * @author tschw + */ - var times = this.times; +function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - for ( var i = 0, n = times.length; i !== n; ++ i ) { + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - times[ i ] += timeOffset; +} - } +LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - } + constructor: LinearInterpolant, - return this; + interpolate_: function ( i1, t0, t, t1 ) { - }, + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function ( timeScale ) { + offset1 = i1 * stride, + offset0 = offset1 - stride, - if ( timeScale !== 1.0 ) { + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - var times = this.times; + for ( var i = 0; i !== stride; ++ i ) { - for ( var i = 0, n = times.length; i !== n; ++ i ) { + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - times[ i ] *= timeScale; + } - } + return result; - } + } - return this; +} ); - }, +/** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function ( startTime, endTime ) { +function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - while ( from !== nKeys && times[ from ] < startTime ) { +} - ++ from; +DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - } + constructor: DiscreteInterpolant, - while ( to !== - 1 && times[ to ] > endTime ) { + interpolate_: function ( i1 /*, t0, t, t1 */ ) { - -- to; + return this.copySampleValue_( i1 - 1 ); - } + } - ++ to; // inclusive -> exclusive bound +} ); - if ( from !== 0 || to !== nKeys ) { +/** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) { to = Math.max( to, 1 ), from = to - 1; } +function KeyframeTrack( name, times, values, interpolation ) { - var stride = this.getValueSize(); - this.times = AnimationUtils.arraySlice( times, from, to ); - this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); - } + this.name = name; - return this; + this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); - }, + this.setInterpolation( interpolation || this.DefaultInterpolation ); - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function () { +} - var valid = true; +// Static methods - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { +Object.assign( KeyframeTrack, { - console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); - valid = false; + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - } + toJSON: function ( track ) { - var times = this.times, - values = this.values, + var trackType = track.constructor; - nKeys = times.length; + var json; - if ( nKeys === 0 ) { + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - console.error( 'THREE.KeyframeTrack: Track is empty.', this ); - valid = false; + json = trackType.toJSON( track ); - } + } else { - var prevTime = null; + // by default, we assume the data can be serialized as-is + json = { - for ( var i = 0; i !== nKeys; i ++ ) { + 'name': track.name, + 'times': AnimationUtils.convertArray( track.times, Array ), + 'values': AnimationUtils.convertArray( track.values, Array ) - var currTime = times[ i ]; + }; - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + var interpolation = track.getInterpolation(); - console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); - valid = false; - break; + if ( interpolation !== track.DefaultInterpolation ) { - } + json.interpolation = interpolation; - if ( prevTime !== null && prevTime > currTime ) { + } - console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); - valid = false; - break; + } - } + json.type = track.ValueTypeName; // mandatory - prevTime = currTime; + return json; - } + } - if ( values !== undefined ) { +} ); - if ( AnimationUtils.isTypedArray( values ) ) { +Object.assign( KeyframeTrack.prototype, { - for ( var i = 0, n = values.length; i !== n; ++ i ) { + constructor: KeyframeTrack, - var value = values[ i ]; + TimeBufferType: Float32Array, - if ( isNaN( value ) ) { + ValueBufferType: Float32Array, - console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); - valid = false; - break; + DefaultInterpolation: InterpolateLinear, - } + InterpolantFactoryMethodDiscrete: function ( result ) { - } + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); - } + }, - } + InterpolantFactoryMethodLinear: function ( result ) { - return valid; + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); - }, + }, - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function () { + InterpolantFactoryMethodSmooth: function ( result ) { - var times = this.times, - values = this.values, - stride = this.getValueSize(), + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); - smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + }, - writeIndex = 1, - lastIndex = times.length - 1; + setInterpolation: function ( interpolation ) { - for ( var i = 1; i < lastIndex; ++ i ) { + var factoryMethod; - var keep = false; + switch ( interpolation ) { - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + case InterpolateDiscrete: - // remove adjacent keyframes scheduled at the same time + factoryMethod = this.InterpolantFactoryMethodDiscrete; - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + break; - if ( ! smoothInterpolation ) { + case InterpolateLinear: - // remove unnecessary keyframes same as their neighbors + factoryMethod = this.InterpolantFactoryMethodLinear; - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + break; - for ( var j = 0; j !== stride; ++ j ) { + case InterpolateSmooth: - var value = values[ offset + j ]; + factoryMethod = this.InterpolantFactoryMethodSmooth; - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + break; - keep = true; - break; + } - } + if ( factoryMethod === undefined ) { - } + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - } else { + if ( this.createInterpolant === undefined ) { - keep = true; + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - } + this.setInterpolation( this.DefaultInterpolation ); - } + } else { - // in-place compaction + throw new Error( message ); // fatal, in this case - if ( keep ) { + } - if ( i !== writeIndex ) { + } - times[ writeIndex ] = times[ i ]; + console.warn( 'THREE.KeyframeTrack:', message ); + return this; - var readOffset = i * stride, - writeOffset = writeIndex * stride; + } - for ( var j = 0; j !== stride; ++ j ) { + this.createInterpolant = factoryMethod; - values[ writeOffset + j ] = values[ readOffset + j ]; + return this; - } + }, - } + getInterpolation: function () { - ++ writeIndex; + switch ( this.createInterpolant ) { - } + case this.InterpolantFactoryMethodDiscrete: - } + return InterpolateDiscrete; - // flush last keyframe (compaction looks ahead) + case this.InterpolantFactoryMethodLinear: - if ( lastIndex > 0 ) { + return InterpolateLinear; - times[ writeIndex ] = times[ lastIndex ]; + case this.InterpolantFactoryMethodSmooth: - for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { + return InterpolateSmooth; - values[ writeOffset + j ] = values[ readOffset + j ]; + } - } + }, - ++ writeIndex; + getValueSize: function () { - } + return this.values.length / this.times.length; - if ( writeIndex !== times.length ) { + }, - this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + // move all keyframes either forwards or backwards in time + shift: function ( timeOffset ) { - } + if ( timeOffset !== 0.0 ) { - return this; + var times = this.times; - }, + for ( var i = 0, n = times.length; i !== n; ++ i ) { - clone: function () { + times[ i ] += timeOffset; - var times = AnimationUtils.arraySlice( this.times, 0 ); - var values = AnimationUtils.arraySlice( this.values, 0 ); - - var TypedKeyframeTrack = this.constructor; - var track = new TypedKeyframeTrack( this.name, times, values ); - - // Interpolant argument to constructor is not saved, so copy the factory method directly. - track.createInterpolant = this.createInterpolant; - - return track; + } } - } ); + return this; - /** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + }, - function BooleanKeyframeTrack( name, times, values ) { + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function ( timeScale ) { - KeyframeTrack.call( this, name, times, values ); + if ( timeScale !== 1.0 ) { - } + var times = this.times; - BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + for ( var i = 0, n = times.length; i !== n; ++ i ) { - constructor: BooleanKeyframeTrack, + times[ i ] *= timeScale; - ValueTypeName: 'bool', - ValueBufferType: Array, + } - DefaultInterpolation: InterpolateDiscrete, + } - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined + return this; - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + }, - } ); + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function ( startTime, endTime ) { - /** - * - * A Track of keyframe values that represent color. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; - function ColorKeyframeTrack( name, times, values, interpolation ) { + while ( from !== nKeys && times[ from ] < startTime ) { - KeyframeTrack.call( this, name, times, values, interpolation ); + ++ from; - } + } - ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + while ( to !== - 1 && times[ to ] > endTime ) { - constructor: ColorKeyframeTrack, + -- to; - ValueTypeName: 'color' + } - // ValueBufferType is inherited + ++ to; // inclusive -> exclusive bound - // DefaultInterpolation is inherited + if ( from !== 0 || to !== nKeys ) { - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) { - } ); + to = Math.max( to, 1 ); + from = to - 1; - /** - * - * A Track of numeric keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } - function NumberKeyframeTrack( name, times, values, interpolation ) { + var stride = this.getValueSize(); + this.times = AnimationUtils.arraySlice( times, from, to ); + this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); - KeyframeTrack.call( this, name, times, values, interpolation ); + } - } + return this; - NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + }, - constructor: NumberKeyframeTrack, + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function () { - ValueTypeName: 'number' + var valid = true; - // ValueBufferType is inherited + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - // DefaultInterpolation is inherited + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; - } ); + } - /** - * Spherical linear unit quaternion interpolant. - * - * @author tschw - */ + var times = this.times, + values = this.values, - function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + nKeys = times.length; - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + if ( nKeys === 0 ) { - } + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; + + } - QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + var prevTime = null; - constructor: QuaternionLinearInterpolant, + for ( var i = 0; i !== nKeys; i ++ ) { - interpolate_: function ( i1, t0, t, t1 ) { + var currTime = times[ i ]; - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - offset = i1 * stride, + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; - alpha = ( t - t0 ) / ( t1 - t0 ); + } - for ( var end = offset + stride; offset !== end; offset += 4 ) { + if ( prevTime !== null && prevTime > currTime ) { - Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; } - return result; + prevTime = currTime; } - } ); + if ( values !== undefined ) { - /** - * - * A Track of quaternion keyframe values. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + if ( AnimationUtils.isTypedArray( values ) ) { - function QuaternionKeyframeTrack( name, times, values, interpolation ) { + for ( var i = 0, n = values.length; i !== n; ++ i ) { - KeyframeTrack.call( this, name, times, values, interpolation ); + var value = values[ i ]; - } + if ( isNaN( value ) ) { - QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); + valid = false; + break; - constructor: QuaternionKeyframeTrack, + } - ValueTypeName: 'quaternion', + } - // ValueBufferType is inherited + } - DefaultInterpolation: InterpolateLinear, + } - InterpolantFactoryMethodLinear: function ( result ) { + return valid; - return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); + }, - }, + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function () { - InterpolantFactoryMethodSmooth: undefined // not yet implemented + // times or values may be shared with other tracks, so overwriting is unsafe + var times = AnimationUtils.arraySlice( this.times ), + values = AnimationUtils.arraySlice( this.values ), + stride = this.getValueSize(), - } ); + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, - /** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + writeIndex = 1, + lastIndex = times.length - 1; - function StringKeyframeTrack( name, times, values, interpolation ) { + for ( var i = 1; i < lastIndex; ++ i ) { - KeyframeTrack.call( this, name, times, values, interpolation ); + var keep = false; - } + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + // remove adjacent keyframes scheduled at the same time - constructor: StringKeyframeTrack, + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - ValueTypeName: 'string', - ValueBufferType: Array, + if ( ! smoothInterpolation ) { - DefaultInterpolation: InterpolateDiscrete, + // remove unnecessary keyframes same as their neighbors - InterpolantFactoryMethodLinear: undefined, + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - InterpolantFactoryMethodSmooth: undefined + for ( var j = 0; j !== stride; ++ j ) { - } ); + var value = values[ offset + j ]; - /** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - function VectorKeyframeTrack( name, times, values, interpolation ) { + keep = true; + break; - KeyframeTrack.call( this, name, times, values, interpolation ); + } - } + } - VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { + } else { - constructor: VectorKeyframeTrack, + keep = true; - ValueTypeName: 'vector' + } - // ValueBufferType is inherited + } - // DefaultInterpolation is inherited + // in-place compaction - } ); + if ( keep ) { - /** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + if ( i !== writeIndex ) { - function AnimationClip( name, duration, tracks ) { + times[ writeIndex ] = times[ i ]; - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : - 1; + var readOffset = i * stride, + writeOffset = writeIndex * stride; - this.uuid = _Math.generateUUID(); + for ( var j = 0; j !== stride; ++ j ) { - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { + values[ writeOffset + j ] = values[ readOffset + j ]; - this.resetDuration(); + } - } + } - } + ++ writeIndex; - function getTrackTypeForValueTypeName( typeName ) { + } - switch ( typeName.toLowerCase() ) { + } - case 'scalar': - case 'double': - case 'float': - case 'number': - case 'integer': + // flush last keyframe (compaction looks ahead) - return NumberKeyframeTrack; + if ( lastIndex > 0 ) { - case 'vector': - case 'vector2': - case 'vector3': - case 'vector4': + times[ writeIndex ] = times[ lastIndex ]; - return VectorKeyframeTrack; + for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { - case 'color': + values[ writeOffset + j ] = values[ readOffset + j ]; - return ColorKeyframeTrack; + } - case 'quaternion': + ++ writeIndex; - return QuaternionKeyframeTrack; + } - case 'bool': - case 'boolean': + if ( writeIndex !== times.length ) { - return BooleanKeyframeTrack; + this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - case 'string': + } else { - return StringKeyframeTrack; + this.times = times; + this.values = values; } - throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); + return this; - } + }, - function parseKeyframeTrack( json ) { + clone: function () { - if ( json.type === undefined ) { + var times = AnimationUtils.arraySlice( this.times, 0 ); + var values = AnimationUtils.arraySlice( this.values, 0 ); - throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); + var TypedKeyframeTrack = this.constructor; + var track = new TypedKeyframeTrack( this.name, times, values ); - } + // Interpolant argument to constructor is not saved, so copy the factory method directly. + track.createInterpolant = this.createInterpolant; - var trackType = getTrackTypeForValueTypeName( json.type ); + return track; - if ( json.times === undefined ) { + } - var times = [], values = []; +} ); - AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); +/** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - json.times = times; - json.values = values; +function BooleanKeyframeTrack( name, times, values ) { - } + KeyframeTrack.call( this, name, times, values ); - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { +} - return trackType.parse( json ); +BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - } else { + constructor: BooleanKeyframeTrack, - // by default, we assume a constructor compatible with the base - return new trackType( json.name, json.times, json.values, json.interpolation ); + ValueTypeName: 'bool', + ValueBufferType: Array, - } + DefaultInterpolation: InterpolateDiscrete, - } + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - Object.assign( AnimationClip, { + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - parse: function ( json ) { +} ); - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); +/** + * + * A Track of keyframe values that represent color. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { +function ColorKeyframeTrack( name, times, values, interpolation ) { - tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); + KeyframeTrack.call( this, name, times, values, interpolation ); - } +} - return new AnimationClip( json.name, json.duration, tracks ); +ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - }, + constructor: ColorKeyframeTrack, - toJSON: function ( clip ) { + ValueTypeName: 'color' - var tracks = [], - clipTracks = clip.tracks; + // ValueBufferType is inherited - var json = { + // DefaultInterpolation is inherited - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks, - 'uuid': clip.uuid + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. - }; +} ); - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { +/** + * + * A Track of numeric keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); +function NumberKeyframeTrack( name, times, values, interpolation ) { - } + KeyframeTrack.call( this, name, times, values, interpolation ); - return json; +} - }, +NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) { + constructor: NumberKeyframeTrack, - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + ValueTypeName: 'number' - for ( var i = 0; i < numMorphTargets; i ++ ) { + // ValueBufferType is inherited - var times = []; - var values = []; + // DefaultInterpolation is inherited - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); +} ); - values.push( 0, 1, 0 ); +/** + * Spherical linear unit quaternion interpolant. + * + * @author tschw + */ - var order = AnimationUtils.getKeyframeOrder( times ); - times = AnimationUtils.sortedArray( times, 1, order ); - values = AnimationUtils.sortedArray( values, 1, order ); +function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - // if there is a key at the first frame, duplicate it as the - // last frame as well for perfect loop. - if ( ! noLoop && times[ 0 ] === 0 ) { + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - times.push( numMorphTargets ); - values.push( values[ 0 ] ); +} - } +QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); + constructor: QuaternionLinearInterpolant, - } + interpolate_: function ( i1, t0, t, t1 ) { - return new AnimationClip( name, - 1, tracks ); + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - }, + offset = i1 * stride, - findByName: function ( objectOrClipArray, name ) { + alpha = ( t - t0 ) / ( t1 - t0 ); - var clipArray = objectOrClipArray; + for ( var end = offset + stride; offset !== end; offset += 4 ) { - if ( ! Array.isArray( objectOrClipArray ) ) { + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + } - } + return result; - for ( var i = 0; i < clipArray.length; i ++ ) { + } - if ( clipArray[ i ].name === name ) { +} ); - return clipArray[ i ]; +/** + * + * A Track of quaternion keyframe values. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } +function QuaternionKeyframeTrack( name, times, values, interpolation ) { - } + KeyframeTrack.call( this, name, times, values, interpolation ); - return null; +} - }, +QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) { + constructor: QuaternionKeyframeTrack, - var animationToMorphTargets = {}; + ValueTypeName: 'quaternion', - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; + // ValueBufferType is inherited - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { + DefaultInterpolation: InterpolateLinear, - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + InterpolantFactoryMethodLinear: function ( result ) { - if ( parts && parts.length > 1 ) { + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); - var name = parts[ 1 ]; + }, - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + InterpolantFactoryMethodSmooth: undefined // not yet implemented - animationToMorphTargets[ name ] = animationMorphTargets = []; +} ); - } +/** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - animationMorphTargets.push( morphTarget ); +function StringKeyframeTrack( name, times, values, interpolation ) { - } + KeyframeTrack.call( this, name, times, values, interpolation ); - } +} - var clips = []; +StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - for ( var name in animationToMorphTargets ) { + constructor: StringKeyframeTrack, - clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + ValueTypeName: 'string', + ValueBufferType: Array, - } + DefaultInterpolation: InterpolateDiscrete, - return clips; + InterpolantFactoryMethodLinear: undefined, - }, + InterpolantFactoryMethodSmooth: undefined - // parse the animation.hierarchy format - parseAnimation: function ( animation, bones ) { +} ); - if ( ! animation ) { +/** + * + * A Track of vectored keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); - return null; +function VectorKeyframeTrack( name, times, values, interpolation ) { - } + KeyframeTrack.call( this, name, times, values, interpolation ); - var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { +} - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { +VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - var times = []; - var values = []; + constructor: VectorKeyframeTrack, - AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); + ValueTypeName: 'vector' - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + // ValueBufferType is inherited - destTracks.push( new trackType( trackName, times, values ) ); + // DefaultInterpolation is inherited - } +} ); - } +/** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - }; +function AnimationClip( name, duration, tracks, blendMode ) { - var tracks = []; + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : - 1; + this.blendMode = ( blendMode !== undefined ) ? blendMode : NormalAnimationBlendMode; - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || - 1; - var fps = animation.fps || 30; + this.uuid = MathUtils.generateUUID(); - var hierarchyTracks = animation.hierarchy || []; + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + this.resetDuration(); - var animationKeys = hierarchyTracks[ h ].keys; + } - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) { continue; } +} - // process morph targets - if ( animationKeys[ 0 ].morphTargets ) { +function getTrackTypeForValueTypeName( typeName ) { - // figure out all morph targets used in this track - var morphTargetNames = {}; + switch ( typeName.toLowerCase() ) { - for ( var k = 0; k < animationKeys.length; k ++ ) { + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': - if ( animationKeys[ k ].morphTargets ) { + return NumberKeyframeTrack; - for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': - morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + return VectorKeyframeTrack; - } + case 'color': - } + return ColorKeyframeTrack; - } + case 'quaternion': - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( var morphTargetName in morphTargetNames ) { + return QuaternionKeyframeTrack; - var times = []; - var values = []; + case 'bool': + case 'boolean': - for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { + return BooleanKeyframeTrack; - var animationKey = animationKeys[ k ]; + case 'string': - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + return StringKeyframeTrack; - } + } - tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - } +} - duration = morphTargetNames.length * ( fps || 1.0 ); +function parseKeyframeTrack( json ) { - } else { + if ( json.type === undefined ) { - // ...assume skeletal animation + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); - var boneName = '.bones[' + bones[ h ].name + ']'; + } - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + var trackType = getTrackTypeForValueTypeName( json.type ); - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + if ( json.times === undefined ) { - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + var times = [], values = []; - } + AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - } + json.times = times; + json.values = values; - if ( tracks.length === 0 ) { + } - return null; + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - } + return trackType.parse( json ); - var clip = new AnimationClip( clipName, duration, tracks ); + } else { - return clip; + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); - } + } - } ); +} - Object.assign( AnimationClip.prototype, { +Object.assign( AnimationClip, { - resetDuration: function () { + parse: function ( json ) { - var tracks = this.tracks, duration = 0; + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - var track = this.tracks[ i ]; + tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); - duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + } - } + return new AnimationClip( json.name, json.duration, tracks, json.blendMode ); - this.duration = duration; + }, - return this; + toJSON: function ( clip ) { - }, + var tracks = [], + clipTracks = clip.tracks; - trim: function () { + var json = { - for ( var i = 0; i < this.tracks.length; i ++ ) { + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks, + 'uuid': clip.uuid, + 'blendMode': clip.blendMode - this.tracks[ i ].trim( 0, this.duration ); + }; - } + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - return this; + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - }, + } - validate: function () { + return json; - var valid = true; + }, - for ( var i = 0; i < this.tracks.length; i ++ ) { + CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) { - valid = valid && this.tracks[ i ].validate(); + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - } + for ( var i = 0; i < numMorphTargets; i ++ ) { - return valid; + var times = []; + var values = []; - }, + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); + + values.push( 0, 1, 0 ); - optimize: function () { + var order = AnimationUtils.getKeyframeOrder( times ); + times = AnimationUtils.sortedArray( times, 1, order ); + values = AnimationUtils.sortedArray( values, 1, order ); - for ( var i = 0; i < this.tracks.length; i ++ ) { + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { - this.tracks[ i ].optimize(); + times.push( numMorphTargets ); + values.push( values[ 0 ] ); } - return this; + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); - }, + } - clone: function () { + return new AnimationClip( name, - 1, tracks ); - var tracks = []; + }, - for ( var i = 0; i < this.tracks.length; i ++ ) { + findByName: function ( objectOrClipArray, name ) { - tracks.push( this.tracks[ i ].clone() ); + var clipArray = objectOrClipArray; - } + if ( ! Array.isArray( objectOrClipArray ) ) { - return new AnimationClip( this.name, this.duration, tracks ); + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; } - } ); + for ( var i = 0; i < clipArray.length; i ++ ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( clipArray[ i ].name === name ) { + + return clipArray[ i ]; - var Cache = { + } - enabled: false, + } - files: {}, + return null; - add: function ( key, file ) { + }, - if ( this.enabled === false ) { return; } + CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) { - // console.log( 'THREE.Cache', 'Adding key:', key ); + var animationToMorphTargets = {}; - this.files[ key ] = file; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - }, + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { - get: function ( key ) { + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - if ( this.enabled === false ) { return; } + if ( parts && parts.length > 1 ) { - // console.log( 'THREE.Cache', 'Checking key:', key ); + var name = parts[ 1 ]; - return this.files[ key ]; + var animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - }, + animationToMorphTargets[ name ] = animationMorphTargets = []; - remove: function ( key ) { + } - delete this.files[ key ]; + animationMorphTargets.push( morphTarget ); - }, + } + + } + + var clips = []; - clear: function () { + for ( var name in animationToMorphTargets ) { - this.files = {}; + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); } - }; + return clips; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function LoadingManager( onLoad, onProgress, onError ) { + // parse the animation.hierarchy format + parseAnimation: function ( animation, bones ) { - var scope = this; + if ( ! animation ) { - var isLoading = false; - var itemsLoaded = 0; - var itemsTotal = 0; - var urlModifier = undefined; - var handlers = []; + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; - // Refer to #5689 for the reason why we don't set .onStart - // in the constructor + } - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { - this.itemStart = function ( url ) { + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - itemsTotal ++; + var times = []; + var values = []; - if ( isLoading === false ) { + AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); - if ( scope.onStart !== undefined ) { + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - scope.onStart( url, itemsLoaded, itemsTotal ); + destTracks.push( new trackType( trackName, times, values ) ); } } - isLoading = true; - }; - this.itemEnd = function ( url ) { - - itemsLoaded ++; + var tracks = []; - if ( scope.onProgress !== undefined ) { + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || - 1; + var fps = animation.fps || 30; + var blendMode = animation.blendMode; - scope.onProgress( url, itemsLoaded, itemsTotal ); + var hierarchyTracks = animation.hierarchy || []; - } + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - if ( itemsLoaded === itemsTotal ) { + var animationKeys = hierarchyTracks[ h ].keys; - isLoading = false; + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - if ( scope.onLoad !== undefined ) { + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { - scope.onLoad(); + // figure out all morph targets used in this track + var morphTargetNames = {}; - } + for ( var k = 0; k < animationKeys.length; k ++ ) { - } + if ( animationKeys[ k ].morphTargets ) { - }; + for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { - this.itemError = function ( url ) { + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; - if ( scope.onError !== undefined ) { + } - scope.onError( url ); + } - } + } - }; + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( var morphTargetName in morphTargetNames ) { - this.resolveURL = function ( url ) { + var times = []; + var values = []; - if ( urlModifier ) { + for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { - return urlModifier( url ); + var animationKey = animationKeys[ k ]; - } + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - return url; + } - }; + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - this.setURLModifier = function ( transform ) { + } - urlModifier = transform; + duration = morphTargetNames.length * ( fps || 1.0 ); - return this; + } else { - }; + // ...assume skeletal animation - this.addHandler = function ( regex, loader ) { + var boneName = '.bones[' + bones[ h ].name + ']'; - handlers.push( regex, loader ); + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - return this; + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); - }; + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - this.removeHandler = function ( regex ) { + } - var index = handlers.indexOf( regex ); + } - if ( index !== - 1 ) { + if ( tracks.length === 0 ) { - handlers.splice( index, 2 ); + return null; - } + } - return this; + var clip = new AnimationClip( clipName, duration, tracks, blendMode ); - }; + return clip; - this.getHandler = function ( file ) { + } - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { +} ); - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; +Object.assign( AnimationClip.prototype, { - if ( regex.global ) { regex.lastIndex = 0; } // see #17920 + resetDuration: function () { - if ( regex.test( file ) ) { + var tracks = this.tracks, duration = 0; - return loader; + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { - } + var track = this.tracks[ i ]; - } + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); - return null; + } - }; + this.duration = duration; - } + return this; - var DefaultLoadingManager = new LoadingManager(); + }, - /** - * @author alteredq / http://alteredqualia.com/ - */ + trim: function () { - function Loader( manager ) { + for ( var i = 0; i < this.tracks.length; i ++ ) { - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + this.tracks[ i ].trim( 0, this.duration ); - this.crossOrigin = 'anonymous'; - this.path = ''; - this.resourcePath = ''; + } - } + return this; - Object.assign( Loader.prototype, { + }, - load: function ( /* url, onLoad, onProgress, onError */ ) {}, + validate: function () { - parse: function ( /* data */ ) {}, + var valid = true; - setCrossOrigin: function ( crossOrigin ) { + for ( var i = 0; i < this.tracks.length; i ++ ) { - this.crossOrigin = crossOrigin; - return this; + valid = valid && this.tracks[ i ].validate(); - }, + } - setPath: function ( path ) { + return valid; - this.path = path; - return this; + }, - }, + optimize: function () { - setResourcePath: function ( resourcePath ) { + for ( var i = 0; i < this.tracks.length; i ++ ) { - this.resourcePath = resourcePath; - return this; + this.tracks[ i ].optimize(); } - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - var loading = {}; + clone: function () { - function FileLoader( manager ) { + var tracks = []; - Loader.call( this, manager ); + for ( var i = 0; i < this.tracks.length; i ++ ) { - } + tracks.push( this.tracks[ i ].clone() ); - FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + } - constructor: FileLoader, + return new AnimationClip( this.name, this.duration, tracks, this.blendMode ); - load: function ( url, onLoad, onProgress, onError ) { + } - if ( url === undefined ) { url = ''; } +} ); - if ( this.path !== undefined ) { url = this.path + url; } +/** + * @author mrdoob / http://mrdoob.com/ + */ - url = this.manager.resolveURL( url ); +var Cache = { - var scope = this; + enabled: false, - var cached = Cache.get( url ); + files: {}, - if ( cached !== undefined ) { + add: function ( key, file ) { - scope.manager.itemStart( url ); + if ( this.enabled === false ) return; - setTimeout( function () { + // console.log( 'THREE.Cache', 'Adding key:', key ); - if ( onLoad ) { onLoad( cached ); } + this.files[ key ] = file; - scope.manager.itemEnd( url ); + }, - }, 0 ); + get: function ( key ) { - return cached; + if ( this.enabled === false ) return; - } + // console.log( 'THREE.Cache', 'Checking key:', key ); - // Check if request is duplicate + return this.files[ key ]; - if ( loading[ url ] !== undefined ) { + }, - loading[ url ].push( { + remove: function ( key ) { - onLoad: onLoad, - onProgress: onProgress, - onError: onError + delete this.files[ key ]; - } ); + }, - return; + clear: function () { - } + this.files = {}; - // Check for data: URI - var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; - var dataUriRegexResult = url.match( dataUriRegex ); + } - // Safari can not handle Data URIs through XMLHttpRequest so process manually - if ( dataUriRegexResult ) { +}; - var mimeType = dataUriRegexResult[ 1 ]; - var isBase64 = !! dataUriRegexResult[ 2 ]; - var data = dataUriRegexResult[ 3 ]; +/** + * @author mrdoob / http://mrdoob.com/ + */ - data = decodeURIComponent( data ); +function LoadingManager( onLoad, onProgress, onError ) { - if ( isBase64 ) { data = atob( data ); } + var scope = this; - try { + var isLoading = false; + var itemsLoaded = 0; + var itemsTotal = 0; + var urlModifier = undefined; + var handlers = []; - var response; - var responseType = ( this.responseType || '' ).toLowerCase(); + // Refer to #5689 for the reason why we don't set .onStart + // in the constructor - switch ( responseType ) { + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; - case 'arraybuffer': - case 'blob': + this.itemStart = function ( url ) { - var view = new Uint8Array( data.length ); + itemsTotal ++; - for ( var i = 0; i < data.length; i ++ ) { + if ( isLoading === false ) { - view[ i ] = data.charCodeAt( i ); + if ( scope.onStart !== undefined ) { - } + scope.onStart( url, itemsLoaded, itemsTotal ); - if ( responseType === 'blob' ) { + } - response = new Blob( [ view.buffer ], { type: mimeType } ); + } - } else { + isLoading = true; - response = view.buffer; + }; - } + this.itemEnd = function ( url ) { - break; + itemsLoaded ++; - case 'document': + if ( scope.onProgress !== undefined ) { - var parser = new DOMParser(); - response = parser.parseFromString( data, mimeType ); + scope.onProgress( url, itemsLoaded, itemsTotal ); - break; + } - case 'json': + if ( itemsLoaded === itemsTotal ) { - response = JSON.parse( data ); + isLoading = false; - break; + if ( scope.onLoad !== undefined ) { - default: // 'text' or other + scope.onLoad(); - response = data; + } - break; + } - } + }; - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + this.itemError = function ( url ) { - if ( onLoad ) { onLoad( response ); } + if ( scope.onError !== undefined ) { - scope.manager.itemEnd( url ); + scope.onError( url ); - }, 0 ); + } - } catch ( error ) { + }; - // Wait for next browser tick like standard XMLHttpRequest event dispatching does - setTimeout( function () { + this.resolveURL = function ( url ) { - if ( onError ) { onError( error ); } + if ( urlModifier ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + return urlModifier( url ); - }, 0 ); + } - } + return url; - } else { + }; - // Initialise array for duplicate requests + this.setURLModifier = function ( transform ) { - loading[ url ] = []; + urlModifier = transform; - loading[ url ].push( { + return this; - onLoad: onLoad, - onProgress: onProgress, - onError: onError + }; - } ); + this.addHandler = function ( regex, loader ) { - var request = new XMLHttpRequest(); + handlers.push( regex, loader ); - request.open( 'GET', url, true ); + return this; - request.addEventListener( 'load', function ( event ) { + }; - var response = this.response; + this.removeHandler = function ( regex ) { - var callbacks = loading[ url ]; + var index = handlers.indexOf( regex ); - delete loading[ url ]; + if ( index !== - 1 ) { - if ( this.status === 200 || this.status === 0 ) { + handlers.splice( index, 2 ); - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + } - if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); } + return this; - // Add to cache only on HTTP success, so that we do not cache - // error response bodies as proper responses to requests. - Cache.add( url, response ); + }; - for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + this.getHandler = function ( file ) { - var callback = callbacks[ i ]; - if ( callback.onLoad ) { callback.onLoad( response ); } + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - } + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - scope.manager.itemEnd( url ); + if ( regex.global ) regex.lastIndex = 0; // see #17920 - } else { + if ( regex.test( file ) ) { - for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + return loader; - var callback = callbacks[ i ]; - if ( callback.onError ) { callback.onError( event ); } + } - } + } - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + return null; - } + }; - }, false ); +} - request.addEventListener( 'progress', function ( event ) { +var DefaultLoadingManager = new LoadingManager(); - var callbacks = loading[ url ]; +/** + * @author alteredq / http://alteredqualia.com/ + */ - for ( var i = 0, il = callbacks.length; i < il; i ++ ) { +function Loader( manager ) { - var callback = callbacks[ i ]; - if ( callback.onProgress ) { callback.onProgress( event ); } + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; - } + this.crossOrigin = 'anonymous'; + this.path = ''; + this.resourcePath = ''; + this.requestHeader = {}; - }, false ); +} - request.addEventListener( 'error', function ( event ) { +Object.assign( Loader.prototype, { - var callbacks = loading[ url ]; + load: function ( /* url, onLoad, onProgress, onError */ ) {}, - delete loading[ url ]; + loadAsync: function ( url, onProgress ) { - for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + var scope = this; - var callback = callbacks[ i ]; - if ( callback.onError ) { callback.onError( event ); } + return new Promise( function ( resolve, reject ) { - } + scope.load( url, resolve, onProgress, reject ); - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + } ); - }, false ); + }, - request.addEventListener( 'abort', function ( event ) { + parse: function ( /* data */ ) {}, - var callbacks = loading[ url ]; + setCrossOrigin: function ( crossOrigin ) { - delete loading[ url ]; + this.crossOrigin = crossOrigin; + return this; - for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + }, - var callback = callbacks[ i ]; - if ( callback.onError ) { callback.onError( event ); } + setPath: function ( path ) { - } + this.path = path; + return this; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + }, - }, false ); + setResourcePath: function ( resourcePath ) { - if ( this.responseType !== undefined ) { request.responseType = this.responseType; } - if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; } + this.resourcePath = resourcePath; + return this; - if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); } + }, - for ( var header in this.requestHeader ) { + setRequestHeader: function ( requestHeader ) { - request.setRequestHeader( header, this.requestHeader[ header ] ); + this.requestHeader = requestHeader; + return this; - } + } - request.send( null ); +} ); - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - scope.manager.itemStart( url ); +var loading = {}; - return request; +function FileLoader( manager ) { - }, + Loader.call( this, manager ); - setResponseType: function ( value ) { +} - this.responseType = value; - return this; +FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - }, + constructor: FileLoader, - setWithCredentials: function ( value ) { + load: function ( url, onLoad, onProgress, onError ) { - this.withCredentials = value; - return this; + if ( url === undefined ) url = ''; - }, + if ( this.path !== undefined ) url = this.path + url; - setMimeType: function ( value ) { + url = this.manager.resolveURL( url ); - this.mimeType = value; - return this; + var scope = this; - }, + var cached = Cache.get( url ); - setRequestHeader: function ( value ) { + if ( cached !== undefined ) { - this.requestHeader = value; - return this; + scope.manager.itemStart( url ); - } + setTimeout( function () { - } ); + if ( onLoad ) onLoad( cached ); - /** - * @author bhouston / http://clara.io/ - */ + scope.manager.itemEnd( url ); - function AnimationLoader( manager ) { + }, 0 ); - Loader.call( this, manager ); + return cached; - } + } - AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + // Check if request is duplicate - constructor: AnimationLoader, + if ( loading[ url ] !== undefined ) { - load: function ( url, onLoad, onProgress, onError ) { + loading[ url ].push( { - var scope = this; + onLoad: onLoad, + onProgress: onProgress, + onError: onError - var loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.load( url, function ( text ) { + } ); - onLoad( scope.parse( JSON.parse( text ) ) ); + return; - }, onProgress, onError ); + } - }, + // Check for data: URI + var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; + var dataUriRegexResult = url.match( dataUriRegex ); - parse: function ( json ) { + // Safari can not handle Data URIs through XMLHttpRequest so process manually + if ( dataUriRegexResult ) { - var animations = []; + var mimeType = dataUriRegexResult[ 1 ]; + var isBase64 = !! dataUriRegexResult[ 2 ]; + var data = dataUriRegexResult[ 3 ]; - for ( var i = 0; i < json.length; i ++ ) { + data = decodeURIComponent( data ); - var clip = AnimationClip.parse( json[ i ] ); + if ( isBase64 ) data = atob( data ); - animations.push( clip ); + try { - } + var response; + var responseType = ( this.responseType || '' ).toLowerCase(); - return animations; + switch ( responseType ) { - } + case 'arraybuffer': + case 'blob': - } ); + var view = new Uint8Array( data.length ); - /** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ + for ( var i = 0; i < data.length; i ++ ) { - function CompressedTextureLoader( manager ) { + view[ i ] = data.charCodeAt( i ); - Loader.call( this, manager ); + } - } + if ( responseType === 'blob' ) { - CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + response = new Blob( [ view.buffer ], { type: mimeType } ); - constructor: CompressedTextureLoader, + } else { - load: function ( url, onLoad, onProgress, onError ) { + response = view.buffer; - var scope = this; + } - var images = []; + break; - var texture = new CompressedTexture(); - texture.image = images; + case 'document': - var loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + var parser = new DOMParser(); + response = parser.parseFromString( data, mimeType ); - function loadTexture( i ) { + break; - loader.load( url[ i ], function ( buffer ) { + case 'json': - var texDatas = scope.parse( buffer, true ); + response = JSON.parse( data ); - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + break; - loaded += 1; + default: // 'text' or other - if ( loaded === 6 ) { + response = data; - if ( texDatas.mipmapCount === 1 ) - { texture.minFilter = LinearFilter; } + break; - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) { onLoad( texture ); } + // Wait for next browser tick like standard XMLHttpRequest event dispatching does + setTimeout( function () { - } + if ( onLoad ) onLoad( response ); - }, onProgress, onError ); + scope.manager.itemEnd( url ); - } + }, 0 ); - if ( Array.isArray( url ) ) { + } catch ( error ) { - var loaded = 0; + // Wait for next browser tick like standard XMLHttpRequest event dispatching does + setTimeout( function () { - for ( var i = 0, il = url.length; i < il; ++ i ) { + if ( onError ) onError( error ); - loadTexture( i ); + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - } + }, 0 ); - } else { + } - // compressed cubemap texture stored in a single DDS file + } else { - loader.load( url, function ( buffer ) { + // Initialise array for duplicate requests - var texDatas = scope.parse( buffer, true ); + loading[ url ] = []; - if ( texDatas.isCubemap ) { + loading[ url ].push( { - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + onLoad: onLoad, + onProgress: onProgress, + onError: onError - for ( var f = 0; f < faces; f ++ ) { + } ); - images[ f ] = { mipmaps: [] }; + var request = new XMLHttpRequest(); - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + request.open( 'GET', url, true ); - images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); - images[ f ].format = texDatas.format; - images[ f ].width = texDatas.width; - images[ f ].height = texDatas.height; + request.addEventListener( 'load', function ( event ) { - } + var response = this.response; - } + var callbacks = loading[ url ]; - } else { + delete loading[ url ]; - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + if ( this.status === 200 || this.status === 0 ) { - } + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. - if ( texDatas.mipmapCount === 1 ) { + if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); - texture.minFilter = LinearFilter; + // Add to cache only on HTTP success, so that we do not cache + // error response bodies as proper responses to requests. + Cache.add( url, response ); - } + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { - texture.format = texDatas.format; - texture.needsUpdate = true; + var callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( response ); - if ( onLoad ) { onLoad( texture ); } + } - }, onProgress, onError ); + scope.manager.itemEnd( url ); - } + } else { - return texture; + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { - } + var callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); - } ); + } - /** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - * - * Sub classes have to implement the parse() method which will be used in load(). - */ + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - function DataTextureLoader( manager ) { + } - Loader.call( this, manager ); + }, false ); - } + request.addEventListener( 'progress', function ( event ) { - DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + var callbacks = loading[ url ]; - constructor: DataTextureLoader, + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { - load: function ( url, onLoad, onProgress, onError ) { + var callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); - var scope = this; + } - var texture = new DataTexture(); + }, false ); - var loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setPath( this.path ); - loader.load( url, function ( buffer ) { + request.addEventListener( 'error', function ( event ) { - var texData = scope.parse( buffer ); + var callbacks = loading[ url ]; - if ( ! texData ) { return; } + delete loading[ url ]; - if ( texData.image !== undefined ) { + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { - texture.image = texData.image; + var callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); - } else if ( texData.data !== undefined ) { + } - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - } + }, false ); - texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + request.addEventListener( 'abort', function ( event ) { - texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; - texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + var callbacks = loading[ url ]; - texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + delete loading[ url ]; - if ( texData.format !== undefined ) { + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { - texture.format = texData.format; + var callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); } - if ( texData.type !== undefined ) { - texture.type = texData.type; + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - } + }, false ); - if ( texData.mipmaps !== undefined ) { + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; - texture.mipmaps = texData.mipmaps; - texture.minFilter = LinearMipmapLinearFilter; // presumably... + if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); - } + for ( var header in this.requestHeader ) { - if ( texData.mipmapCount === 1 ) { + request.setRequestHeader( header, this.requestHeader[ header ] ); - texture.minFilter = LinearFilter; + } - } + request.send( null ); - texture.needsUpdate = true; + } - if ( onLoad ) { onLoad( texture, texData ); } + scope.manager.itemStart( url ); - }, onProgress, onError ); + return request; + }, - return texture; + setResponseType: function ( value ) { - } + this.responseType = value; + return this; - } ); + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + setWithCredentials: function ( value ) { - function ImageLoader( manager ) { + this.withCredentials = value; + return this; - Loader.call( this, manager ); + }, - } + setMimeType: function ( value ) { - ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + this.mimeType = value; + return this; - constructor: ImageLoader, + } - load: function ( url, onLoad, onProgress, onError ) { +} ); - if ( this.path !== undefined ) { url = this.path + url; } +/** + * @author bhouston / http://clara.io/ + */ - url = this.manager.resolveURL( url ); +function AnimationLoader( manager ) { - var scope = this; + Loader.call( this, manager ); - var cached = Cache.get( url ); +} - if ( cached !== undefined ) { +AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - scope.manager.itemStart( url ); + constructor: AnimationLoader, - setTimeout( function () { + load: function ( url, onLoad, onProgress, onError ) { - if ( onLoad ) { onLoad( cached ); } + var scope = this; - scope.manager.itemEnd( url ); + var loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.load( url, function ( text ) { - }, 0 ); + try { - return cached; + onLoad( scope.parse( JSON.parse( text ) ) ); - } + } catch ( e ) { - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + if ( onError ) { - function onImageLoad() { + onError( e ); - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + } else { - Cache.add( url, this ); + console.error( e ); - if ( onLoad ) { onLoad( this ); } + } - scope.manager.itemEnd( url ); + scope.manager.itemError( url ); } - function onImageError( event ) { + }, onProgress, onError ); - image.removeEventListener( 'load', onImageLoad, false ); - image.removeEventListener( 'error', onImageError, false ); + }, - if ( onError ) { onError( event ); } + parse: function ( json ) { - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + var animations = []; - } + for ( var i = 0; i < json.length; i ++ ) { - image.addEventListener( 'load', onImageLoad, false ); - image.addEventListener( 'error', onImageError, false ); + var clip = AnimationClip.parse( json[ i ] ); - if ( url.substr( 0, 5 ) !== 'data:' ) { + animations.push( clip ); - if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; } + } - } + return animations; - scope.manager.itemStart( url ); + } - image.src = url; +} ); - return image; +/** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - } +function CompressedTextureLoader( manager ) { - } ); + Loader.call( this, manager ); - /** - * @author mrdoob / http://mrdoob.com/ - */ +} +CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - function CubeTextureLoader( manager ) { + constructor: CompressedTextureLoader, - Loader.call( this, manager ); + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + var images = []; - constructor: CubeTextureLoader, + var texture = new CompressedTexture(); + texture.image = images; - load: function ( urls, onLoad, onProgress, onError ) { + var loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); - var texture = new CubeTexture(); + function loadTexture( i ) { - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + loader.load( url[ i ], function ( buffer ) { - var loaded = 0; + var texDatas = scope.parse( buffer, true ); - function loadTexture( i ) { + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; - loader.load( urls[ i ], function ( image ) { + loaded += 1; - texture.images[ i ] = image; + if ( loaded === 6 ) { - loaded ++; + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; - if ( loaded === 6 ) { + texture.format = texDatas.format; + texture.needsUpdate = true; - texture.needsUpdate = true; + if ( onLoad ) onLoad( texture ); - if ( onLoad ) { onLoad( texture ); } + } - } + }, onProgress, onError ); - }, undefined, onError ); + } - } + if ( Array.isArray( url ) ) { + + var loaded = 0; - for ( var i = 0; i < urls.length; ++ i ) { + for ( var i = 0, il = url.length; i < il; ++ i ) { loadTexture( i ); } - return texture; - - } + } else { - } ); + // compressed cubemap texture stored in a single DDS file - /** - * @author mrdoob / http://mrdoob.com/ - */ + loader.load( url, function ( buffer ) { - function TextureLoader( manager ) { + var texDatas = scope.parse( buffer, true ); - Loader.call( this, manager ); + if ( texDatas.isCubemap ) { - } + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; - TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + for ( var f = 0; f < faces; f ++ ) { - constructor: TextureLoader, + images[ f ] = { mipmaps: [] }; - load: function ( url, onLoad, onProgress, onError ) { + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { - var texture = new Texture(); + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + } - loader.load( url, function ( image ) { + } - texture.image = image; + } else { - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.needsUpdate = true; + } - if ( onLoad !== undefined ) { + if ( texDatas.mipmapCount === 1 ) { - onLoad( texture ); + texture.minFilter = LinearFilter; } - }, onProgress, onError ); + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); - return texture; + }, onProgress, onError ); } - } ); + return texture; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of curve methods: - * .getPoint( t, optionalTarget ), .getTangent( t ) - * .getPointAt( u, optionalTarget ), .getTangentAt( u ) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following curves inherit from THREE.Curve: - * - * -- 2D curves -- - * THREE.ArcCurve - * THREE.CubicBezierCurve - * THREE.EllipseCurve - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.SplineCurve - * - * -- 3D curves -- - * THREE.CatmullRomCurve3 - * THREE.CubicBezierCurve3 - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * - * A series of curves can be represented as a THREE.CurvePath. - * - **/ + } - /************************************************************** - * Abstract Curve base class - **************************************************************/ +} ); - function Curve() { +/** + * @author Nikos M. / https://github.com/foo123/ + * + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * + * Sub classes have to implement the parse() method which will be used in load(). + */ - this.type = 'Curve'; +function DataTextureLoader( manager ) { - this.arcLengthDivisions = 200; + Loader.call( this, manager ); - } +} - Object.assign( Curve.prototype, { +DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + constructor: DataTextureLoader, - getPoint: function ( /* t, optionalTarget */ ) { + load: function ( url, onLoad, onProgress, onError ) { - console.warn( 'THREE.Curve: .getPoint() not implemented.' ); - return null; + var scope = this; - }, + var texture = new DataTexture(); - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + var loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( this.path ); + loader.load( url, function ( buffer ) { - getPointAt: function ( u, optionalTarget ) { + var texData = scope.parse( buffer ); - var t = this.getUtoTmapping( u ); - return this.getPoint( t, optionalTarget ); + if ( ! texData ) return; - }, + if ( texData.image !== undefined ) { - // Get sequence of points using getPoint( t ) + texture.image = texData.image; - getPoints: function ( divisions ) { + } else if ( texData.data !== undefined ) { - if ( divisions === undefined ) { divisions = 5; } + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; - var points = []; + } - for ( var d = 0; d <= divisions; d ++ ) { + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; - points.push( this.getPoint( d / divisions ) ); + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; - } + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; - return points; + if ( texData.format !== undefined ) { - }, + texture.format = texData.format; - // Get sequence of points using getPointAt( u ) + } - getSpacedPoints: function ( divisions ) { + if ( texData.type !== undefined ) { - if ( divisions === undefined ) { divisions = 5; } + texture.type = texData.type; - var points = []; + } - for ( var d = 0; d <= divisions; d ++ ) { + if ( texData.mipmaps !== undefined ) { - points.push( this.getPointAt( d / divisions ) ); + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; // presumably... } - return points; + if ( texData.mipmapCount === 1 ) { - }, + texture.minFilter = LinearFilter; - // Get total curve arc length + } - getLength: function () { + texture.needsUpdate = true; - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + if ( onLoad ) onLoad( texture, texData ); - }, + }, onProgress, onError ); - // Get list of cumulative segment lengths - getLengths: function ( divisions ) { + return texture; - if ( divisions === undefined ) { divisions = this.arcLengthDivisions; } + } - if ( this.cacheArcLengths && - ( this.cacheArcLengths.length === divisions + 1 ) && - ! this.needsUpdate ) { +} ); - return this.cacheArcLengths; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function ImageLoader( manager ) { - this.needsUpdate = false; + Loader.call( this, manager ); - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; +} - cache.push( 0 ); +ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - for ( p = 1; p <= divisions; p ++ ) { + constructor: ImageLoader, - current = this.getPoint( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + load: function ( url, onLoad, onProgress, onError ) { - } + if ( this.path !== undefined ) url = this.path + url; - this.cacheArcLengths = cache; + url = this.manager.resolveURL( url ); - return cache; // { sums: cache, sum: sum }; Sum is in the last element. + var scope = this; - }, + var cached = Cache.get( url ); - updateArcLengths: function () { + if ( cached !== undefined ) { - this.needsUpdate = true; - this.getLengths(); + scope.manager.itemStart( url ); - }, + setTimeout( function () { - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + if ( onLoad ) onLoad( cached ); - getUtoTmapping: function ( u, distance ) { + scope.manager.itemEnd( url ); - var arcLengths = this.getLengths(); + }, 0 ); - var i = 0, il = arcLengths.length; + return cached; - var targetArcLength; // The targeted u distance value to get + } - if ( distance ) { + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - targetArcLength = distance; + function onImageLoad() { - } else { + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); - targetArcLength = u * arcLengths[ il - 1 ]; + Cache.add( url, this ); - } + if ( onLoad ) onLoad( this ); - // binary search for the index with largest value smaller than target u distance + scope.manager.itemEnd( url ); - var low = 0, high = il - 1, comparison; + } - while ( low <= high ) { + function onImageError( event ) { - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + image.removeEventListener( 'load', onImageLoad, false ); + image.removeEventListener( 'error', onImageError, false ); - comparison = arcLengths[ i ] - targetArcLength; + if ( onError ) onError( event ); - if ( comparison < 0 ) { + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - low = i + 1; + } - } else if ( comparison > 0 ) { + image.addEventListener( 'load', onImageLoad, false ); + image.addEventListener( 'error', onImageError, false ); - high = i - 1; + if ( url.substr( 0, 5 ) !== 'data:' ) { - } else { + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; - high = i; - break; + } - // DONE + scope.manager.itemStart( url ); - } + image.src = url; - } + return image; - i = high; + } - if ( arcLengths[ i ] === targetArcLength ) { +} ); - return i / ( il - 1 ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - } - // we could get finer grain at lengths, or use simple interpolation between two points +function CubeTextureLoader( manager ) { - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + Loader.call( this, manager ); - var segmentLength = lengthAfter - lengthBefore; +} - // determine where we are between the 'before' and 'after' points +CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + constructor: CubeTextureLoader, - // add that fractional amount to t + load: function ( urls, onLoad, onProgress, onError ) { - var t = ( i + segmentFraction ) / ( il - 1 ); + var texture = new CubeTexture(); - return t; + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - }, + var loaded = 0; - // Returns a unit vector tangent at t - // In case any sub curve does not implement its tangent derivation, - // 2 points a small delta apart will be used to find its gradient - // which seems to give a reasonable approximation + function loadTexture( i ) { - getTangent: function ( t ) { + loader.load( urls[ i ], function ( image ) { - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; + texture.images[ i ] = image; - // Capping in case of danger + loaded ++; - if ( t1 < 0 ) { t1 = 0; } - if ( t2 > 1 ) { t2 = 1; } + if ( loaded === 6 ) { - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + texture.needsUpdate = true; - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); + if ( onLoad ) onLoad( texture ); - }, + } + + }, undefined, onError ); - getTangentAt: function ( u ) { + } - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + for ( var i = 0; i < urls.length; ++ i ) { - }, + loadTexture( i ); - computeFrenetFrames: function ( segments, closed ) { + } - // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + return texture; - var normal = new Vector3(); + } - var tangents = []; - var normals = []; - var binormals = []; +} ); - var vec = new Vector3(); - var mat = new Matrix4(); +/** + * @author mrdoob / http://mrdoob.com/ + */ - var i, u, theta; +function TextureLoader( manager ) { - // compute the tangent vectors for each segment on the curve + Loader.call( this, manager ); - for ( i = 0; i <= segments; i ++ ) { +} - u = i / segments; +TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - tangents[ i ] = this.getTangentAt( u ); - tangents[ i ].normalize(); + constructor: TextureLoader, - } + load: function ( url, onLoad, onProgress, onError ) { - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the minimum tangent xyz component + var texture = new Texture(); - normals[ 0 ] = new Vector3(); - binormals[ 0 ] = new Vector3(); - var min = Number.MAX_VALUE; - var tx = Math.abs( tangents[ 0 ].x ); - var ty = Math.abs( tangents[ 0 ].y ); - var tz = Math.abs( tangents[ 0 ].z ); + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - if ( tx <= min ) { + loader.load( url, function ( image ) { - min = tx; - normal.set( 1, 0, 0 ); + texture.image = image; - } + // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. + var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - if ( ty <= min ) { + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.needsUpdate = true; - min = ty; - normal.set( 0, 1, 0 ); + if ( onLoad !== undefined ) { + + onLoad( texture ); } - if ( tz <= min ) { + }, onProgress, onError ); - normal.set( 0, 0, 1 ); + return texture; - } + } - vec.crossVectors( tangents[ 0 ], normal ).normalize(); +} ); - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object + * + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() + * + * This following curves inherit from THREE.Curve: + * + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve + * + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 + * + * A series of curves can be represented as a THREE.CurvePath. + * + **/ +/************************************************************** + * Abstract Curve base class + **************************************************************/ - // compute the slowly-varying normal and binormal vectors for each segment on the curve +function Curve() { - for ( i = 1; i <= segments; i ++ ) { + this.type = 'Curve'; - normals[ i ] = normals[ i - 1 ].clone(); + this.arcLengthDivisions = 200; - binormals[ i ] = binormals[ i - 1 ].clone(); +} - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); +Object.assign( Curve.prototype, { - if ( vec.length() > Number.EPSILON ) { + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - vec.normalize(); + getPoint: function ( /* t, optionalTarget */ ) { - theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + }, - } + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + getPointAt: function ( u, optionalTarget ) { - } + var t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + }, - if ( closed === true ) { + // Get sequence of points using getPoint( t ) - theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); - theta /= segments; + getPoints: function ( divisions ) { - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + if ( divisions === undefined ) divisions = 5; - theta = - theta; + var points = []; - } + for ( var d = 0; d <= divisions; d ++ ) { - for ( i = 1; i <= segments; i ++ ) { + points.push( this.getPoint( d / divisions ) ); - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + } - } + return points; - } + }, - return { - tangents: tangents, - normals: normals, - binormals: binormals - }; + // Get sequence of points using getPointAt( u ) - }, + getSpacedPoints: function ( divisions ) { - clone: function () { + if ( divisions === undefined ) divisions = 5; - return new this.constructor().copy( this ); + var points = []; - }, + for ( var d = 0; d <= divisions; d ++ ) { - copy: function ( source ) { + points.push( this.getPointAt( d / divisions ) ); - this.arcLengthDivisions = source.arcLengthDivisions; + } - return this; + return points; - }, + }, - toJSON: function () { + // Get total curve arc length - var data = { - metadata: { - version: 4.5, - type: 'Curve', - generator: 'Curve.toJSON' - } - }; + getLength: function () { - data.arcLengthDivisions = this.arcLengthDivisions; - data.type = this.type; + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - return data; + }, - }, + // Get list of cumulative segment lengths - fromJSON: function ( json ) { + getLengths: function ( divisions ) { - this.arcLengthDivisions = json.arcLengthDivisions; + if ( divisions === undefined ) divisions = this.arcLengthDivisions; - return this; + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { - } + return this.cacheArcLengths; - } ); + } - function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + this.needsUpdate = false; - Curve.call( this ); + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - this.type = 'EllipseCurve'; + cache.push( 0 ); - this.aX = aX || 0; - this.aY = aY || 0; + for ( p = 1; p <= divisions; p ++ ) { - this.xRadius = xRadius || 1; - this.yRadius = yRadius || 1; + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - this.aStartAngle = aStartAngle || 0; - this.aEndAngle = aEndAngle || 2 * Math.PI; + } - this.aClockwise = aClockwise || false; + this.cacheArcLengths = cache; - this.aRotation = aRotation || 0; + return cache; // { sums: cache, sum: sum }; Sum is in the last element. - } + }, - EllipseCurve.prototype = Object.create( Curve.prototype ); - EllipseCurve.prototype.constructor = EllipseCurve; + updateArcLengths: function () { - EllipseCurve.prototype.isEllipseCurve = true; + this.needsUpdate = true; + this.getLengths(); - EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) { + }, - var point = optionalTarget || new Vector2(); + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + getUtoTmapping: function ( u, distance ) { - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) { deltaAngle += twoPi; } - while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; } + var arcLengths = this.getLengths(); - if ( deltaAngle < Number.EPSILON ) { + var i = 0, il = arcLengths.length; - if ( samePoints ) { + var targetArcLength; // The targeted u distance value to get - deltaAngle = 0; + if ( distance ) { - } else { + targetArcLength = distance; - deltaAngle = twoPi; + } else { - } + targetArcLength = u * arcLengths[ il - 1 ]; } - if ( this.aClockwise === true && ! samePoints ) { + // binary search for the index with largest value smaller than target u distance - if ( deltaAngle === twoPi ) { + var low = 0, high = il - 1, comparison; - deltaAngle = - twoPi; + while ( low <= high ) { - } else { + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - deltaAngle = deltaAngle - twoPi; + comparison = arcLengths[ i ] - targetArcLength; - } + if ( comparison < 0 ) { - } + low = i + 1; - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + } else if ( comparison > 0 ) { - if ( this.aRotation !== 0 ) { + high = i - 1; + + } else { - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + high = i; + break; - var tx = x - this.aX; - var ty = y - this.aY; + // DONE - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + } } - return point.set( x, y ); + i = high; - }; + if ( arcLengths[ i ] === targetArcLength ) { - EllipseCurve.prototype.copy = function ( source ) { + return i / ( il - 1 ); - Curve.prototype.copy.call( this, source ); + } - this.aX = source.aX; - this.aY = source.aY; + // we could get finer grain at lengths, or use simple interpolation between two points - this.xRadius = source.xRadius; - this.yRadius = source.yRadius; + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - this.aStartAngle = source.aStartAngle; - this.aEndAngle = source.aEndAngle; + var segmentLength = lengthAfter - lengthBefore; - this.aClockwise = source.aClockwise; + // determine where we are between the 'before' and 'after' points - this.aRotation = source.aRotation; + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - return this; + // add that fractional amount to t - }; + var t = ( i + segmentFraction ) / ( il - 1 ); + return t; - EllipseCurve.prototype.toJSON = function () { + }, - var data = Curve.prototype.toJSON.call( this ); + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation - data.aX = this.aX; - data.aY = this.aY; + getTangent: function ( t, optionalTarget ) { - data.xRadius = this.xRadius; - data.yRadius = this.yRadius; + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - data.aStartAngle = this.aStartAngle; - data.aEndAngle = this.aEndAngle; + // Capping in case of danger - data.aClockwise = this.aClockwise; + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - data.aRotation = this.aRotation; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - return data; + var tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() ); - }; + tangent.copy( pt2 ).sub( pt1 ).normalize(); - EllipseCurve.prototype.fromJSON = function ( json ) { + return tangent; - Curve.prototype.fromJSON.call( this, json ); + }, - this.aX = json.aX; - this.aY = json.aY; + getTangentAt: function ( u, optionalTarget ) { - this.xRadius = json.xRadius; - this.yRadius = json.yRadius; + var t = this.getUtoTmapping( u ); + return this.getTangent( t, optionalTarget ); - this.aStartAngle = json.aStartAngle; - this.aEndAngle = json.aEndAngle; + }, - this.aClockwise = json.aClockwise; + computeFrenetFrames: function ( segments, closed ) { - this.aRotation = json.aRotation; + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf - return this; + var normal = new Vector3(); - }; + var tangents = []; + var normals = []; + var binormals = []; - function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + var vec = new Vector3(); + var mat = new Matrix4(); - EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + var i, u, theta; - this.type = 'ArcCurve'; + // compute the tangent vectors for each segment on the curve - } + for ( i = 0; i <= segments; i ++ ) { - ArcCurve.prototype = Object.create( EllipseCurve.prototype ); - ArcCurve.prototype.constructor = ArcCurve; + u = i / segments; - ArcCurve.prototype.isArcCurve = true; + tangents[ i ] = this.getTangentAt( u, new Vector3() ); + tangents[ i ].normalize(); - /** - * @author zz85 https://github.com/zz85 - * - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf - * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 - */ + } + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component - /* - Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + var min = Number.MAX_VALUE; + var tx = Math.abs( tangents[ 0 ].x ); + var ty = Math.abs( tangents[ 0 ].y ); + var tz = Math.abs( tangents[ 0 ].z ); - This CubicPoly class could be used for reusing some variables and calculations, - but for three.js curve use, it could be possible inlined and flatten into a single function call - which can be placed in CurveUtils. - */ + if ( tx <= min ) { - function CubicPoly() { + min = tx; + normal.set( 1, 0, 0 ); - var c0 = 0, c1 = 0, c2 = 0, c3 = 0; + } - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - function init( x0, x1, t0, t1 ) { + if ( ty <= min ) { - c0 = x0; - c1 = t0; - c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - c3 = 2 * x0 - 2 * x1 + t0 + t1; + min = ty; + normal.set( 0, 1, 0 ); } - return { + if ( tz <= min ) { - initCatmullRom: function ( x0, x1, x2, x3, tension ) { + normal.set( 0, 0, 1 ); - init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); + } - }, + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); - // compute tangents when parameterized in [t1,t2] - var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; + // compute the slowly-varying normal and binormal vectors for each segment on the curve - init( x1, x2, t1, t2 ); + for ( i = 1; i <= segments; i ++ ) { - }, + normals[ i ] = normals[ i - 1 ].clone(); - calc: function ( t ) { + binormals[ i ] = binormals[ i - 1 ].clone(); - var t2 = t * t; - var t3 = t2 * t; - return c0 + c1 * t + c2 * t2 + c3 * t3; + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); } - }; + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - } + } - // + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same - var tmp = new Vector3(); - var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); + if ( closed === true ) { - function CatmullRomCurve3( points, closed, curveType, tension ) { + theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; - Curve.call( this ); + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { - this.type = 'CatmullRomCurve3'; + theta = - theta; - this.points = points || []; - this.closed = closed || false; - this.curveType = curveType || 'centripetal'; - this.tension = tension || 0.5; + } - } + for ( i = 1; i <= segments; i ++ ) { - CatmullRomCurve3.prototype = Object.create( Curve.prototype ); - CatmullRomCurve3.prototype.constructor = CatmullRomCurve3; + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); - CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; + } - CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) { + } - var point = optionalTarget || new Vector3(); + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; - var points = this.points; - var l = points.length; + }, - var p = ( l - ( this.closed ? 0 : 1 ) ) * t; - var intPoint = Math.floor( p ); - var weight = p - intPoint; + clone: function () { - if ( this.closed ) { + return new this.constructor().copy( this ); - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; + }, - } else if ( weight === 0 && intPoint === l - 1 ) { + copy: function ( source ) { - intPoint = l - 2; - weight = 1; + this.arcLengthDivisions = source.arcLengthDivisions; - } + return this; - var p0, p1, p2, p3; // 4 points + }, - if ( this.closed || intPoint > 0 ) { + toJSON: function () { - p0 = points[ ( intPoint - 1 ) % l ]; + var data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; - } else { + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; + return data; - } + }, - p1 = points[ intPoint % l ]; - p2 = points[ ( intPoint + 1 ) % l ]; + fromJSON: function ( json ) { - if ( this.closed || intPoint + 2 < l ) { + this.arcLengthDivisions = json.arcLengthDivisions; - p3 = points[ ( intPoint + 2 ) % l ]; + return this; - } else { + } - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; +} ); - } +function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { + Curve.call( this ); - // init Centripetal / Chordal Catmull-Rom - var pow = this.curveType === 'chordal' ? 0.5 : 0.25; - var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); + this.type = 'EllipseCurve'; - // safety check for repeated points - if ( dt1 < 1e-4 ) { dt1 = 1.0; } - if ( dt0 < 1e-4 ) { dt0 = dt1; } - if ( dt2 < 1e-4 ) { dt2 = dt1; } + this.aX = aX || 0; + this.aY = aY || 0; - px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); - py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); - pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); + this.xRadius = xRadius || 1; + this.yRadius = yRadius || 1; - } else if ( this.curveType === 'catmullrom' ) { + this.aStartAngle = aStartAngle || 0; + this.aEndAngle = aEndAngle || 2 * Math.PI; - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); + this.aClockwise = aClockwise || false; - } + this.aRotation = aRotation || 0; - point.set( - px.calc( weight ), - py.calc( weight ), - pz.calc( weight ) - ); +} - return point; +EllipseCurve.prototype = Object.create( Curve.prototype ); +EllipseCurve.prototype.constructor = EllipseCurve; - }; +EllipseCurve.prototype.isEllipseCurve = true; - CatmullRomCurve3.prototype.copy = function ( source ) { +EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) { - Curve.prototype.copy.call( this, source ); + var point = optionalTarget || new Vector2(); - this.points = []; + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - for ( var i = 0, l = source.points.length; i < l; i ++ ) { + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - var point = source.points[ i ]; + if ( deltaAngle < Number.EPSILON ) { - this.points.push( point.clone() ); + if ( samePoints ) { - } + deltaAngle = 0; - this.closed = source.closed; - this.curveType = source.curveType; - this.tension = source.tension; + } else { - return this; + deltaAngle = twoPi; - }; + } + + } - CatmullRomCurve3.prototype.toJSON = function () { + if ( this.aClockwise === true && ! samePoints ) { - var data = Curve.prototype.toJSON.call( this ); + if ( deltaAngle === twoPi ) { - data.points = []; + deltaAngle = - twoPi; - for ( var i = 0, l = this.points.length; i < l; i ++ ) { + } else { - var point = this.points[ i ]; - data.points.push( point.toArray() ); + deltaAngle = deltaAngle - twoPi; } - data.closed = this.closed; - data.curveType = this.curveType; - data.tension = this.tension; + } - return data; + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - }; + if ( this.aRotation !== 0 ) { - CatmullRomCurve3.prototype.fromJSON = function ( json ) { + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - Curve.prototype.fromJSON.call( this, json ); + var tx = x - this.aX; + var ty = y - this.aY; - this.points = []; + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - for ( var i = 0, l = json.points.length; i < l; i ++ ) { + } - var point = json.points[ i ]; - this.points.push( new Vector3().fromArray( point ) ); + return point.set( x, y ); - } +}; - this.closed = json.closed; - this.curveType = json.curveType; - this.tension = json.tension; +EllipseCurve.prototype.copy = function ( source ) { - return this; + Curve.prototype.copy.call( this, source ); - }; + this.aX = source.aX; + this.aY = source.aY; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Bezier Curves formulas obtained from - * http://en.wikipedia.org/wiki/Bézier_curve - */ + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; - function CatmullRom( t, p0, p1, p2, p3 ) { + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + this.aClockwise = source.aClockwise; - } + this.aRotation = source.aRotation; - // + return this; - function QuadraticBezierP0( t, p ) { +}; - var k = 1 - t; - return k * k * p; - } +EllipseCurve.prototype.toJSON = function () { - function QuadraticBezierP1( t, p ) { + var data = Curve.prototype.toJSON.call( this ); - return 2 * ( 1 - t ) * t * p; + data.aX = this.aX; + data.aY = this.aY; - } + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; - function QuadraticBezierP2( t, p ) { + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; - return t * t * p; + data.aClockwise = this.aClockwise; - } + data.aRotation = this.aRotation; - function QuadraticBezier( t, p0, p1, p2 ) { + return data; - return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + - QuadraticBezierP2( t, p2 ); +}; - } +EllipseCurve.prototype.fromJSON = function ( json ) { - // + Curve.prototype.fromJSON.call( this, json ); - function CubicBezierP0( t, p ) { + this.aX = json.aX; + this.aY = json.aY; - var k = 1 - t; - return k * k * k * p; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; - } + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; - function CubicBezierP1( t, p ) { + this.aClockwise = json.aClockwise; - var k = 1 - t; - return 3 * k * k * t * p; + this.aRotation = json.aRotation; - } + return this; - function CubicBezierP2( t, p ) { +}; - return 3 * ( 1 - t ) * t * t * p; +function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - } + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - function CubicBezierP3( t, p ) { + this.type = 'ArcCurve'; - return t * t * t * p; +} - } +ArcCurve.prototype = Object.create( EllipseCurve.prototype ); +ArcCurve.prototype.constructor = ArcCurve; - function CubicBezier( t, p0, p1, p2, p3 ) { +ArcCurve.prototype.isArcCurve = true; - return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + - CubicBezierP3( t, p3 ); +/** + * @author zz85 https://github.com/zz85 + * + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ - } - function CubicBezierCurve( v0, v1, v2, v3 ) { +/* +Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM - Curve.call( this ); +This CubicPoly class could be used for reusing some variables and calculations, +but for three.js curve use, it could be possible inlined and flatten into a single function call +which can be placed in CurveUtils. +*/ - this.type = 'CubicBezierCurve'; +function CubicPoly() { - this.v0 = v0 || new Vector2(); - this.v1 = v1 || new Vector2(); - this.v2 = v2 || new Vector2(); - this.v3 = v3 || new Vector2(); + var c0 = 0, c1 = 0, c2 = 0, c3 = 0; + + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + function init( x0, x1, t0, t1 ) { + + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; } - CubicBezierCurve.prototype = Object.create( Curve.prototype ); - CubicBezierCurve.prototype.constructor = CubicBezierCurve; + return { - CubicBezierCurve.prototype.isCubicBezierCurve = true; + initCatmullRom: function ( x0, x1, x2, x3, tension ) { - CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - var point = optionalTarget || new Vector2(); + }, - var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) - ); + // compute tangents when parameterized in [t1,t2] + var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - return point; + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - }; + init( x1, x2, t1, t2 ); - CubicBezierCurve.prototype.copy = function ( source ) { + }, - Curve.prototype.copy.call( this, source ); + calc: function ( t ) { - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + var t2 = t * t; + var t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; - return this; + } }; - CubicBezierCurve.prototype.toJSON = function () { - - var data = Curve.prototype.toJSON.call( this ); +} - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); +// - return data; +var tmp = new Vector3(); +var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); - }; +function CatmullRomCurve3( points, closed, curveType, tension ) { - CubicBezierCurve.prototype.fromJSON = function ( json ) { + Curve.call( this ); - Curve.prototype.fromJSON.call( this, json ); + this.type = 'CatmullRomCurve3'; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + this.points = points || []; + this.closed = closed || false; + this.curveType = curveType || 'centripetal'; + this.tension = tension || 0.5; - return this; +} - }; +CatmullRomCurve3.prototype = Object.create( Curve.prototype ); +CatmullRomCurve3.prototype.constructor = CatmullRomCurve3; - function CubicBezierCurve3( v0, v1, v2, v3 ) { +CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - Curve.call( this ); +CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) { - this.type = 'CubicBezierCurve3'; + var point = optionalTarget || new Vector3(); - this.v0 = v0 || new Vector3(); - this.v1 = v1 || new Vector3(); - this.v2 = v2 || new Vector3(); - this.v3 = v3 || new Vector3(); + var points = this.points; + var l = points.length; - } + var p = ( l - ( this.closed ? 0 : 1 ) ) * t; + var intPoint = Math.floor( p ); + var weight = p - intPoint; - CubicBezierCurve3.prototype = Object.create( Curve.prototype ); - CubicBezierCurve3.prototype.constructor = CubicBezierCurve3; + if ( this.closed ) { - CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; - CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { + } else if ( weight === 0 && intPoint === l - 1 ) { - var point = optionalTarget || new Vector3(); + intPoint = l - 2; + weight = 1; - var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + } - point.set( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), - CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) - ); + var p0, p1, p2, p3; // 4 points - return point; + if ( this.closed || intPoint > 0 ) { - }; + p0 = points[ ( intPoint - 1 ) % l ]; - CubicBezierCurve3.prototype.copy = function ( source ) { + } else { - Curve.prototype.copy.call( this, source ); + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); - this.v3.copy( source.v3 ); + } - return this; + p1 = points[ intPoint % l ]; + p2 = points[ ( intPoint + 1 ) % l ]; - }; + if ( this.closed || intPoint + 2 < l ) { - CubicBezierCurve3.prototype.toJSON = function () { + p3 = points[ ( intPoint + 2 ) % l ]; - var data = Curve.prototype.toJSON.call( this ); + } else { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); - data.v3 = this.v3.toArray(); + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - return data; + } - }; + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { - CubicBezierCurve3.prototype.fromJSON = function ( json ) { + // init Centripetal / Chordal Catmull-Rom + var pow = this.curveType === 'chordal' ? 0.5 : 0.25; + var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - Curve.prototype.fromJSON.call( this, json ); + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); - this.v3.fromArray( json.v3 ); + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - return this; + } else if ( this.curveType === 'catmullrom' ) { - }; + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); - function LineCurve( v1, v2 ) { + } - Curve.call( this ); + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - this.type = 'LineCurve'; + return point; - this.v1 = v1 || new Vector2(); - this.v2 = v2 || new Vector2(); +}; - } +CatmullRomCurve3.prototype.copy = function ( source ) { - LineCurve.prototype = Object.create( Curve.prototype ); - LineCurve.prototype.constructor = LineCurve; + Curve.prototype.copy.call( this, source ); - LineCurve.prototype.isLineCurve = true; + this.points = []; - LineCurve.prototype.getPoint = function ( t, optionalTarget ) { + for ( var i = 0, l = source.points.length; i < l; i ++ ) { - var point = optionalTarget || new Vector2(); + var point = source.points[ i ]; - if ( t === 1 ) { + this.points.push( point.clone() ); - point.copy( this.v2 ); + } - } else { + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + return this; - } +}; - return point; +CatmullRomCurve3.prototype.toJSON = function () { - }; + var data = Curve.prototype.toJSON.call( this ); - // Line curve is linear, so we can overwrite default getPointAt + data.points = []; - LineCurve.prototype.getPointAt = function ( u, optionalTarget ) { + for ( var i = 0, l = this.points.length; i < l; i ++ ) { - return this.getPoint( u, optionalTarget ); + var point = this.points[ i ]; + data.points.push( point.toArray() ); - }; + } - LineCurve.prototype.getTangent = function ( /* t */ ) { + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; - var tangent = this.v2.clone().sub( this.v1 ); + return data; - return tangent.normalize(); +}; - }; +CatmullRomCurve3.prototype.fromJSON = function ( json ) { - LineCurve.prototype.copy = function ( source ) { + Curve.prototype.fromJSON.call( this, json ); - Curve.prototype.copy.call( this, source ); + this.points = []; - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + for ( var i = 0, l = json.points.length; i < l; i ++ ) { - return this; + var point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); - }; + } - LineCurve.prototype.toJSON = function () { + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; - var data = Curve.prototype.toJSON.call( this ); + return this; - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); +}; - return data; +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Bezier Curves formulas obtained from + * http://en.wikipedia.org/wiki/Bézier_curve + */ - }; +function CatmullRom( t, p0, p1, p2, p3 ) { - LineCurve.prototype.fromJSON = function ( json ) { + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - Curve.prototype.fromJSON.call( this, json ); +} - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); +// - return this; +function QuadraticBezierP0( t, p ) { - }; + var k = 1 - t; + return k * k * p; - function LineCurve3( v1, v2 ) { +} - Curve.call( this ); +function QuadraticBezierP1( t, p ) { - this.type = 'LineCurve3'; + return 2 * ( 1 - t ) * t * p; - this.v1 = v1 || new Vector3(); - this.v2 = v2 || new Vector3(); +} - } +function QuadraticBezierP2( t, p ) { - LineCurve3.prototype = Object.create( Curve.prototype ); - LineCurve3.prototype.constructor = LineCurve3; + return t * t * p; - LineCurve3.prototype.isLineCurve3 = true; +} - LineCurve3.prototype.getPoint = function ( t, optionalTarget ) { +function QuadraticBezier( t, p0, p1, p2 ) { - var point = optionalTarget || new Vector3(); + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); - if ( t === 1 ) { +} - point.copy( this.v2 ); +// - } else { +function CubicBezierP0( t, p ) { - point.copy( this.v2 ).sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + var k = 1 - t; + return k * k * k * p; - } +} - return point; +function CubicBezierP1( t, p ) { - }; + var k = 1 - t; + return 3 * k * k * t * p; - // Line curve is linear, so we can overwrite default getPointAt +} - LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) { +function CubicBezierP2( t, p ) { - return this.getPoint( u, optionalTarget ); + return 3 * ( 1 - t ) * t * t * p; - }; +} - LineCurve3.prototype.copy = function ( source ) { +function CubicBezierP3( t, p ) { - Curve.prototype.copy.call( this, source ); + return t * t * t * p; - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); +} - return this; +function CubicBezier( t, p0, p1, p2, p3 ) { - }; + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); - LineCurve3.prototype.toJSON = function () { +} - var data = Curve.prototype.toJSON.call( this ); +function CubicBezierCurve( v0, v1, v2, v3 ) { - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + Curve.call( this ); - return data; + this.type = 'CubicBezierCurve'; - }; + this.v0 = v0 || new Vector2(); + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); + this.v3 = v3 || new Vector2(); - LineCurve3.prototype.fromJSON = function ( json ) { +} - Curve.prototype.fromJSON.call( this, json ); +CubicBezierCurve.prototype = Object.create( Curve.prototype ); +CubicBezierCurve.prototype.constructor = CubicBezierCurve; - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); +CubicBezierCurve.prototype.isCubicBezierCurve = true; - return this; +CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { - }; + var point = optionalTarget || new Vector2(); - function QuadraticBezierCurve( v0, v1, v2 ) { + var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - Curve.call( this ); + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); - this.type = 'QuadraticBezierCurve'; + return point; - this.v0 = v0 || new Vector2(); - this.v1 = v1 || new Vector2(); - this.v2 = v2 || new Vector2(); +}; - } +CubicBezierCurve.prototype.copy = function ( source ) { - QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; + Curve.prototype.copy.call( this, source ); - QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { + return this; - var point = optionalTarget || new Vector2(); +}; - var v0 = this.v0, v1 = this.v1, v2 = this.v2; +CubicBezierCurve.prototype.toJSON = function () { - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ) - ); + var data = Curve.prototype.toJSON.call( this ); - return point; + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - }; + return data; - QuadraticBezierCurve.prototype.copy = function ( source ) { +}; - Curve.prototype.copy.call( this, source ); +CubicBezierCurve.prototype.fromJSON = function ( json ) { - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + Curve.prototype.fromJSON.call( this, json ); - return this; + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - }; + return this; - QuadraticBezierCurve.prototype.toJSON = function () { +}; - var data = Curve.prototype.toJSON.call( this ); +function CubicBezierCurve3( v0, v1, v2, v3 ) { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + Curve.call( this ); - return data; + this.type = 'CubicBezierCurve3'; - }; + this.v0 = v0 || new Vector3(); + this.v1 = v1 || new Vector3(); + this.v2 = v2 || new Vector3(); + this.v3 = v3 || new Vector3(); - QuadraticBezierCurve.prototype.fromJSON = function ( json ) { +} - Curve.prototype.fromJSON.call( this, json ); +CubicBezierCurve3.prototype = Object.create( Curve.prototype ); +CubicBezierCurve3.prototype.constructor = CubicBezierCurve3; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); +CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - return this; +CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { - }; + var point = optionalTarget || new Vector3(); - function QuadraticBezierCurve3( v0, v1, v2 ) { + var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - Curve.call( this ); + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); - this.type = 'QuadraticBezierCurve3'; + return point; - this.v0 = v0 || new Vector3(); - this.v1 = v1 || new Vector3(); - this.v2 = v2 || new Vector3(); +}; - } +CubicBezierCurve3.prototype.copy = function ( source ) { - QuadraticBezierCurve3.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3; + Curve.prototype.copy.call( this, source ); - QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { + return this; - var point = optionalTarget || new Vector3(); +}; - var v0 = this.v0, v1 = this.v1, v2 = this.v2; +CubicBezierCurve3.prototype.toJSON = function () { - point.set( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ), - QuadraticBezier( t, v0.z, v1.z, v2.z ) - ); + var data = Curve.prototype.toJSON.call( this ); - return point; + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - }; + return data; - QuadraticBezierCurve3.prototype.copy = function ( source ) { +}; - Curve.prototype.copy.call( this, source ); +CubicBezierCurve3.prototype.fromJSON = function ( json ) { - this.v0.copy( source.v0 ); - this.v1.copy( source.v1 ); - this.v2.copy( source.v2 ); + Curve.prototype.fromJSON.call( this, json ); - return this; + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - }; + return this; - QuadraticBezierCurve3.prototype.toJSON = function () { +}; - var data = Curve.prototype.toJSON.call( this ); +function LineCurve( v1, v2 ) { - data.v0 = this.v0.toArray(); - data.v1 = this.v1.toArray(); - data.v2 = this.v2.toArray(); + Curve.call( this ); - return data; + this.type = 'LineCurve'; - }; + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); - QuadraticBezierCurve3.prototype.fromJSON = function ( json ) { +} - Curve.prototype.fromJSON.call( this, json ); +LineCurve.prototype = Object.create( Curve.prototype ); +LineCurve.prototype.constructor = LineCurve; - this.v0.fromArray( json.v0 ); - this.v1.fromArray( json.v1 ); - this.v2.fromArray( json.v2 ); +LineCurve.prototype.isLineCurve = true; - return this; +LineCurve.prototype.getPoint = function ( t, optionalTarget ) { - }; + var point = optionalTarget || new Vector2(); - function SplineCurve( points /* array of Vector2 */ ) { + if ( t === 1 ) { - Curve.call( this ); + point.copy( this.v2 ); - this.type = 'SplineCurve'; + } else { - this.points = points || []; + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); } - SplineCurve.prototype = Object.create( Curve.prototype ); - SplineCurve.prototype.constructor = SplineCurve; + return point; - SplineCurve.prototype.isSplineCurve = true; +}; - SplineCurve.prototype.getPoint = function ( t, optionalTarget ) { +// Line curve is linear, so we can overwrite default getPointAt - var point = optionalTarget || new Vector2(); +LineCurve.prototype.getPointAt = function ( u, optionalTarget ) { - var points = this.points; - var p = ( points.length - 1 ) * t; + return this.getPoint( u, optionalTarget ); - var intPoint = Math.floor( p ); - var weight = p - intPoint; +}; - var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - var p1 = points[ intPoint ]; - var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; +LineCurve.prototype.getTangent = function ( t, optionalTarget ) { - point.set( - CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), - CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) - ); + var tangent = optionalTarget || new Vector2(); - return point; + var tangent = tangent.copy( this.v2 ).sub( this.v1 ).normalize(); - }; + return tangent; - SplineCurve.prototype.copy = function ( source ) { +}; - Curve.prototype.copy.call( this, source ); +LineCurve.prototype.copy = function ( source ) { - this.points = []; + Curve.prototype.copy.call( this, source ); - for ( var i = 0, l = source.points.length; i < l; i ++ ) { + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - var point = source.points[ i ]; + return this; - this.points.push( point.clone() ); +}; - } +LineCurve.prototype.toJSON = function () { - return this; + var data = Curve.prototype.toJSON.call( this ); - }; + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - SplineCurve.prototype.toJSON = function () { + return data; - var data = Curve.prototype.toJSON.call( this ); +}; - data.points = []; +LineCurve.prototype.fromJSON = function ( json ) { - for ( var i = 0, l = this.points.length; i < l; i ++ ) { + Curve.prototype.fromJSON.call( this, json ); - var point = this.points[ i ]; - data.points.push( point.toArray() ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - } + return this; - return data; +}; - }; +function LineCurve3( v1, v2 ) { - SplineCurve.prototype.fromJSON = function ( json ) { + Curve.call( this ); - Curve.prototype.fromJSON.call( this, json ); + this.type = 'LineCurve3'; - this.points = []; + this.v1 = v1 || new Vector3(); + this.v2 = v2 || new Vector3(); - for ( var i = 0, l = json.points.length; i < l; i ++ ) { +} - var point = json.points[ i ]; - this.points.push( new Vector2().fromArray( point ) ); +LineCurve3.prototype = Object.create( Curve.prototype ); +LineCurve3.prototype.constructor = LineCurve3; - } +LineCurve3.prototype.isLineCurve3 = true; - return this; +LineCurve3.prototype.getPoint = function ( t, optionalTarget ) { - }; + var point = optionalTarget || new Vector3(); + if ( t === 1 ) { + point.copy( this.v2 ); - var Curves = /*#__PURE__*/Object.freeze({ - __proto__: null, - ArcCurve: ArcCurve, - CatmullRomCurve3: CatmullRomCurve3, - CubicBezierCurve: CubicBezierCurve, - CubicBezierCurve3: CubicBezierCurve3, - EllipseCurve: EllipseCurve, - LineCurve: LineCurve, - LineCurve3: LineCurve3, - QuadraticBezierCurve: QuadraticBezierCurve, - QuadraticBezierCurve3: QuadraticBezierCurve3, - SplineCurve: SplineCurve - }); + } else { - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - /************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + } - function CurvePath() { + return point; - Curve.call( this ); +}; - this.type = 'CurvePath'; +// Line curve is linear, so we can overwrite default getPointAt - this.curves = []; - this.autoClose = false; // Automatically closes the path +LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) { - } + return this.getPoint( u, optionalTarget ); - CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { +}; - constructor: CurvePath, +LineCurve3.prototype.copy = function ( source ) { - add: function ( curve ) { + Curve.prototype.copy.call( this, source ); - this.curves.push( curve ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - }, + return this; - closePath: function () { +}; - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[ 0 ].getPoint( 0 ); - var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); +LineCurve3.prototype.toJSON = function () { - if ( ! startPoint.equals( endPoint ) ) { + var data = Curve.prototype.toJSON.call( this ); - this.curves.push( new LineCurve( endPoint, startPoint ) ); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - } + return data; - }, +}; - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: +LineCurve3.prototype.fromJSON = function ( json ) { - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + Curve.prototype.fromJSON.call( this, json ); - getPoint: function ( t ) { + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; + return this; - // To think about boundaries points. +}; - while ( i < curveLengths.length ) { +function QuadraticBezierCurve( v0, v1, v2 ) { - if ( curveLengths[ i ] >= d ) { + Curve.call( this ); - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; + this.type = 'QuadraticBezierCurve'; - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + this.v0 = v0 || new Vector2(); + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); - return curve.getPointAt( u ); +} - } +QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); +QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - i ++; +QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - } +QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { - return null; + var point = optionalTarget || new Vector2(); - // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { +}; - points.push( points[ 0 ] ); +function SplineCurve( points /* array of Vector2 */ ) { - } + Curve.call( this ); - return points; + this.type = 'SplineCurve'; - }, + this.points = points || []; - copy: function ( source ) { +} - Curve.prototype.copy.call( this, source ); +SplineCurve.prototype = Object.create( Curve.prototype ); +SplineCurve.prototype.constructor = SplineCurve; - this.curves = []; +SplineCurve.prototype.isSplineCurve = true; - for ( var i = 0, l = source.curves.length; i < l; i ++ ) { +SplineCurve.prototype.getPoint = function ( t, optionalTarget ) { - var curve = source.curves[ i ]; + var point = optionalTarget || new Vector2(); - this.curves.push( curve.clone() ); + var points = this.points; + var p = ( points.length - 1 ) * t; - } + var intPoint = Math.floor( p ); + var weight = p - intPoint; - this.autoClose = source.autoClose; + var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + var p1 = points[ intPoint ]; + var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - return this; + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); - }, + return point; - toJSON: function () { +}; - var data = Curve.prototype.toJSON.call( this ); +SplineCurve.prototype.copy = function ( source ) { - data.autoClose = this.autoClose; - data.curves = []; + Curve.prototype.copy.call( this, source ); - for ( var i = 0, l = this.curves.length; i < l; i ++ ) { + this.points = []; - var curve = this.curves[ i ]; - data.curves.push( curve.toJSON() ); + for ( var i = 0, l = source.points.length; i < l; i ++ ) { - } + var point = source.points[ i ]; - return data; + this.points.push( point.clone() ); - }, + } - fromJSON: function ( json ) { + return this; - Curve.prototype.fromJSON.call( this, json ); +}; - this.autoClose = json.autoClose; - this.curves = []; +SplineCurve.prototype.toJSON = function () { - for ( var i = 0, l = json.curves.length; i < l; i ++ ) { + var data = Curve.prototype.toJSON.call( this ); - var curve = json.curves[ i ]; - this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); + data.points = []; - } + for ( var i = 0, l = this.points.length; i < l; i ++ ) { - return this; + var point = this.points[ i ]; + data.points.push( point.toArray() ); - } + } - } ); + return data; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - **/ +}; - function Path( points ) { +SplineCurve.prototype.fromJSON = function ( json ) { - CurvePath.call( this ); + Curve.prototype.fromJSON.call( this, json ); - this.type = 'Path'; + this.points = []; - this.currentPoint = new Vector2(); + for ( var i = 0, l = json.points.length; i < l; i ++ ) { - if ( points ) { + var point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); - this.setFromPoints( points ); + } - } + return this; - } +}; - Path.prototype = Object.assign( Object.create( CurvePath.prototype ), { +var Curves = /*#__PURE__*/Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve +}); - constructor: Path, +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - setFromPoints: function ( points ) { +/************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - this.moveTo( points[ 0 ].x, points[ 0 ].y ); +function CurvePath() { - for ( var i = 1, l = points.length; i < l; i ++ ) { + Curve.call( this ); - this.lineTo( points[ i ].x, points[ i ].y ); + this.type = 'CurvePath'; - } + this.curves = []; + this.autoClose = false; // Automatically closes the path - return this; +} - }, +CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - moveTo: function ( x, y ) { + constructor: CurvePath, - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + add: function ( curve ) { - return this; + this.curves.push( curve ); - }, + }, - lineTo: function ( x, y ) { + closePath: function () { - var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[ 0 ].getPoint( 0 ); + var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - this.currentPoint.set( x, y ); + if ( ! startPoint.equals( endPoint ) ) { - return this; + this.curves.push( new LineCurve( endPoint, startPoint ) ); - }, + } - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + }, - var curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - this.curves.push( curve ); + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') - this.currentPoint.set( aX, aY ); + getPoint: function ( t ) { - return this; + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; - }, + // To think about boundaries points. - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + while ( i < curveLengths.length ) { - var curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + if ( curveLengths[ i ] >= d ) { - this.curves.push( curve ); + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - this.currentPoint.set( aX, aY ); + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - return this; + return curve.getPointAt( u ); - }, + } - splineThru: function ( pts /*Array of Vector*/ ) { + i ++; - var npts = [ this.currentPoint.clone() ].concat( pts ); + } - var curve = new SplineCurve( npts ); - this.curves.push( curve ); + return null; - this.currentPoint.copy( pts[ pts.length - 1 ] ); + // loop where sum != 0, sum > d , sum+1 0 ) { + } - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + this.cacheLengths = lengths; - if ( ! firstPoint.equals( this.currentPoint ) ) { + return lengths; - this.lineTo( firstPoint.x, firstPoint.y ); + }, - } + getSpacedPoints: function ( divisions ) { - } + if ( divisions === undefined ) divisions = 40; - this.curves.push( curve ); + var points = []; - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + for ( var i = 0; i <= divisions; i ++ ) { - return this; + points.push( this.getPoint( i / divisions ) ); - }, + } - copy: function ( source ) { + if ( this.autoClose ) { - CurvePath.prototype.copy.call( this, source ); + points.push( points[ 0 ] ); - this.currentPoint.copy( source.currentPoint ); + } - return this; + return points; - }, + }, - toJSON: function () { + getPoints: function ( divisions ) { - var data = CurvePath.prototype.toJSON.call( this ); + divisions = divisions || 12; - data.currentPoint = this.currentPoint.toArray(); + var points = [], last; - return data; + for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) { - }, + var curve = curves[ i ]; + var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2 + : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1 + : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length + : divisions; - fromJSON: function ( json ) { + var pts = curve.getPoints( resolution ); - CurvePath.prototype.fromJSON.call( this, json ); + for ( var j = 0; j < pts.length; j ++ ) { - this.currentPoint.fromArray( json.currentPoint ); + var point = pts[ j ]; - return this; + if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates - } + points.push( point ); + last = point; - } ); + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + } - // STEP 1 Create a path. - // STEP 2 Turn path into shape. - // STEP 3 ExtrudeGeometry takes in Shape/Shapes - // STEP 3a - Extract points from each shape, turn to vertices - // STEP 3b - Triangulate each shape, add faces. + if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { - function Shape( points ) { + points.push( points[ 0 ] ); - Path.call( this, points ); + } - this.uuid = _Math.generateUUID(); + return points; - this.type = 'Shape'; + }, - this.holes = []; + copy: function ( source ) { - } + Curve.prototype.copy.call( this, source ); - Shape.prototype = Object.assign( Object.create( Path.prototype ), { + this.curves = []; - constructor: Shape, + for ( var i = 0, l = source.curves.length; i < l; i ++ ) { - getPointsHoles: function ( divisions ) { + var curve = source.curves[ i ]; - var holesPts = []; + this.curves.push( curve.clone() ); - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + } - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + this.autoClose = source.autoClose; - } + return this; - return holesPts; + }, - }, + toJSON: function () { - // get points of shape and holes (keypoints based on segments parameter) + var data = Curve.prototype.toJSON.call( this ); - extractPoints: function ( divisions ) { + data.autoClose = this.autoClose; + data.curves = []; - return { + for ( var i = 0, l = this.curves.length; i < l; i ++ ) { - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + var curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); - }; + } - }, + return data; - copy: function ( source ) { + }, - Path.prototype.copy.call( this, source ); + fromJSON: function ( json ) { - this.holes = []; + Curve.prototype.fromJSON.call( this, json ); - for ( var i = 0, l = source.holes.length; i < l; i ++ ) { + this.autoClose = json.autoClose; + this.curves = []; - var hole = source.holes[ i ]; + for ( var i = 0, l = json.curves.length; i < l; i ++ ) { - this.holes.push( hole.clone() ); + var curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); - } + } - return this; + return this; - }, + } - toJSON: function () { +} ); - var data = Path.prototype.toJSON.call( this ); +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + **/ - data.uuid = this.uuid; - data.holes = []; +function Path( points ) { - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + CurvePath.call( this ); - var hole = this.holes[ i ]; - data.holes.push( hole.toJSON() ); + this.type = 'Path'; - } + this.currentPoint = new Vector2(); - return data; + if ( points ) { - }, + this.setFromPoints( points ); - fromJSON: function ( json ) { + } - Path.prototype.fromJSON.call( this, json ); +} - this.uuid = json.uuid; - this.holes = []; +Path.prototype = Object.assign( Object.create( CurvePath.prototype ), { - for ( var i = 0, l = json.holes.length; i < l; i ++ ) { + constructor: Path, - var hole = json.holes[ i ]; - this.holes.push( new Path().fromJSON( hole ) ); + setFromPoints: function ( points ) { - } + this.moveTo( points[ 0 ].x, points[ 0 ].y ); - return this; + for ( var i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); } - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + }, - function Light( color, intensity ) { + moveTo: function ( x, y ) { - Object3D.call( this ); + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - this.type = 'Light'; + return this; - this.color = new Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + }, - this.receiveShadow = undefined; + lineTo: function ( x, y ) { - } + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - Light.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.currentPoint.set( x, y ); - constructor: Light, + return this; - isLight: true, + }, - copy: function ( source ) { + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - Object3D.prototype.copy.call( this, source ); + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - this.color.copy( source.color ); - this.intensity = source.intensity; + this.curves.push( curve ); - return this; + this.currentPoint.set( aX, aY ); - }, + return this; - toJSON: function ( meta ) { + }, - var data = Object3D.prototype.toJSON.call( this, meta ); + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); } + this.curves.push( curve ); - if ( this.distance !== undefined ) { data.object.distance = this.distance; } - if ( this.angle !== undefined ) { data.object.angle = this.angle; } - if ( this.decay !== undefined ) { data.object.decay = this.decay; } - if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; } + this.currentPoint.set( aX, aY ); - if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); } + return this; - return data; + }, - } + splineThru: function ( pts /*Array of Vector*/ ) { - } ); + var npts = [ this.currentPoint.clone() ].concat( pts ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - function HemisphereLight( skyColor, groundColor, intensity ) { + this.currentPoint.copy( pts[ pts.length - 1 ] ); - Light.call( this, skyColor, intensity ); + return this; - this.type = 'HemisphereLight'; + }, - this.castShadow = undefined; + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - this.groundColor = new Color( groundColor ); + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - } + return this; - HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { + }, - constructor: HemisphereLight, + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - isHemisphereLight: true, + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - copy: function ( source ) { + return this; - Light.prototype.copy.call( this, source ); + }, - this.groundColor.copy( source.groundColor ); + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - return this; + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - } + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }, - function LightShadow( camera ) { + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - this.camera = camera; + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - this.bias = 0; - this.radius = 1; + if ( this.curves.length > 0 ) { - this.mapSize = new Vector2( 512, 512 ); + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - this.map = null; - this.mapPass = null; - this.matrix = new Matrix4(); + if ( ! firstPoint.equals( this.currentPoint ) ) { - this._frustum = new Frustum(); - this._frameExtents = new Vector2( 1, 1 ); + this.lineTo( firstPoint.x, firstPoint.y ); - this._viewportCount = 1; + } - this._viewports = [ + } - new Vector4( 0, 0, 1, 1 ) + this.curves.push( curve ); - ]; + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); - } + return this; - Object.assign( LightShadow.prototype, { + }, - _projScreenMatrix: new Matrix4(), + copy: function ( source ) { - _lightPositionWorld: new Vector3(), + CurvePath.prototype.copy.call( this, source ); - _lookTarget: new Vector3(), + this.currentPoint.copy( source.currentPoint ); - getViewportCount: function () { + return this; - return this._viewportCount; + }, - }, + toJSON: function () { - getFrustum: function () { + var data = CurvePath.prototype.toJSON.call( this ); - return this._frustum; + data.currentPoint = this.currentPoint.toArray(); - }, + return data; - updateMatrices: function ( light ) { + }, - var shadowCamera = this.camera, - shadowMatrix = this.matrix, - projScreenMatrix = this._projScreenMatrix, - lookTarget = this._lookTarget, - lightPositionWorld = this._lightPositionWorld; + fromJSON: function ( json ) { - lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( lightPositionWorld ); + CurvePath.prototype.fromJSON.call( this, json ); - lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( lookTarget ); - shadowCamera.updateMatrixWorld(); + this.currentPoint.fromArray( json.currentPoint ); - projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - this._frustum.setFromMatrix( projScreenMatrix ); + return this; - shadowMatrix.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 - ); + } - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); +} ); - }, +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - getViewport: function ( viewportIndex ) { +// STEP 1 Create a path. +// STEP 2 Turn path into shape. +// STEP 3 ExtrudeGeometry takes in Shape/Shapes +// STEP 3a - Extract points from each shape, turn to vertices +// STEP 3b - Triangulate each shape, add faces. - return this._viewports[ viewportIndex ]; +function Shape( points ) { - }, + Path.call( this, points ); - getFrameExtents: function () { + this.uuid = MathUtils.generateUUID(); - return this._frameExtents; + this.type = 'Shape'; - }, + this.holes = []; - copy: function ( source ) { +} - this.camera = source.camera.clone(); +Shape.prototype = Object.assign( Object.create( Path.prototype ), { - this.bias = source.bias; - this.radius = source.radius; + constructor: Shape, - this.mapSize.copy( source.mapSize ); + getPointsHoles: function ( divisions ) { - return this; + var holesPts = []; - }, + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - clone: function () { + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - return new this.constructor().copy( this ); + } - }, + return holesPts; - toJSON: function () { + }, - var object = {}; + // get points of shape and holes (keypoints based on segments parameter) - if ( this.bias !== 0 ) { object.bias = this.bias; } - if ( this.radius !== 1 ) { object.radius = this.radius; } - if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); } + extractPoints: function ( divisions ) { - object.camera = this.camera.toJSON( false ).object; - delete object.camera.matrix; + return { - return object; + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) - } + }; - } ); + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + copy: function ( source ) { - function SpotLightShadow() { + Path.prototype.copy.call( this, source ); - LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); + this.holes = []; - } + for ( var i = 0, l = source.holes.length; i < l; i ++ ) { - SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + var hole = source.holes[ i ]; - constructor: SpotLightShadow, + this.holes.push( hole.clone() ); - isSpotLightShadow: true, + } - updateMatrices: function ( light ) { + return this; - var camera = this.camera; + }, - var fov = _Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || camera.far; + toJSON: function () { - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + var data = Path.prototype.toJSON.call( this ); - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + data.uuid = this.uuid; + data.holes = []; - } + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - LightShadow.prototype.updateMatrices.call( this, light ); + var hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); } - } ); + return data; - /** - * @author alteredq / http://alteredqualia.com/ - */ + }, - function SpotLight( color, intensity, distance, angle, penumbra, decay ) { + fromJSON: function ( json ) { - Light.call( this, color, intensity ); + Path.prototype.fromJSON.call( this, json ); - this.type = 'SpotLight'; + this.uuid = json.uuid; + this.holes = []; - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + for ( var i = 0, l = json.holes.length; i < l; i ++ ) { - this.target = new Object3D(); + var hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); - Object.defineProperty( this, 'power', { - get: function () { + } - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * Math.PI; + return this; - }, - set: function ( power ) { + } - // intensity = power per solid angle. - // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / Math.PI; +} ); - } - } ); +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. +function Light( color, intensity ) { - this.shadow = new SpotLightShadow(); + Object3D.call( this ); - } + this.type = 'Light'; - SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; - constructor: SpotLight, + this.receiveShadow = undefined; - isSpotLight: true, +} - copy: function ( source ) { +Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - Light.prototype.copy.call( this, source ); + constructor: Light, - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + isLight: true, - this.target = source.target.clone(); + copy: function ( source ) { - this.shadow = source.shadow.clone(); + Object3D.prototype.copy.call( this, source ); - return this; + this.color.copy( source.color ); + this.intensity = source.intensity; - } + return this; - } ); + }, - function PointLightShadow() { + toJSON: function ( meta ) { - LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) ); + var data = Object3D.prototype.toJSON.call( this, meta ); - this._frameExtents = new Vector2( 4, 2 ); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - this._viewportCount = 6; + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - this._viewports = [ - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction - - // positive X - new Vector4( 2, 1, 1, 1 ), - // negative X - new Vector4( 0, 1, 1, 1 ), - // positive Z - new Vector4( 3, 1, 1, 1 ), - // negative Z - new Vector4( 1, 1, 1, 1 ), - // positive Y - new Vector4( 3, 0, 1, 1 ), - // negative Y - new Vector4( 1, 0, 1, 1 ) - ]; + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; - this._cubeDirections = [ - new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), - new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) - ]; + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); - this._cubeUps = [ - new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), - new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) - ]; + return data; } - PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { +} ); - constructor: PointLightShadow, +/** + * @author alteredq / http://alteredqualia.com/ + */ - isPointLightShadow: true, +function HemisphereLight( skyColor, groundColor, intensity ) { - updateMatrices: function ( light, viewportIndex ) { + Light.call( this, skyColor, intensity ); - if ( viewportIndex === undefined ) { viewportIndex = 0; } + this.type = 'HemisphereLight'; - var camera = this.camera, - shadowMatrix = this.matrix, - lightPositionWorld = this._lightPositionWorld, - lookTarget = this._lookTarget, - projScreenMatrix = this._projScreenMatrix; + this.castShadow = undefined; - lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - camera.position.copy( lightPositionWorld ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - lookTarget.copy( camera.position ); - lookTarget.add( this._cubeDirections[ viewportIndex ] ); - camera.up.copy( this._cubeUps[ viewportIndex ] ); - camera.lookAt( lookTarget ); - camera.updateMatrixWorld(); + this.groundColor = new Color( groundColor ); - shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z ); +} - projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - this._frustum.setFromMatrix( projScreenMatrix ); +HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - } + constructor: HemisphereLight, - } ); + isHemisphereLight: true, - /** - * @author mrdoob / http://mrdoob.com/ - */ + copy: function ( source ) { + Light.prototype.copy.call( this, source ); - function PointLight( color, intensity, distance, decay ) { + this.groundColor.copy( source.groundColor ); - Light.call( this, color, intensity ); + return this; - this.type = 'PointLight'; + } - Object.defineProperty( this, 'power', { - get: function () { +} ); - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - return this.intensity * 4 * Math.PI; +/** + * @author mrdoob / http://mrdoob.com/ + */ - }, - set: function ( power ) { +function LightShadow( camera ) { - // intensity = power per solid angle. - // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf - this.intensity = power / ( 4 * Math.PI ); + this.camera = camera; - } - } ); + this.bias = 0; + this.radius = 1; - this.distance = ( distance !== undefined ) ? distance : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + this.mapSize = new Vector2( 512, 512 ); - this.shadow = new PointLightShadow(); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); - } + this._frustum = new Frustum(); + this._frameExtents = new Vector2( 1, 1 ); - PointLight.prototype = Object.assign( Object.create( Light.prototype ), { + this._viewportCount = 1; - constructor: PointLight, + this._viewports = [ - isPointLight: true, + new Vector4( 0, 0, 1, 1 ) - copy: function ( source ) { + ]; - Light.prototype.copy.call( this, source ); +} - this.distance = source.distance; - this.decay = source.decay; +Object.assign( LightShadow.prototype, { - this.shadow = source.shadow.clone(); + _projScreenMatrix: new Matrix4(), - return this; + _lightPositionWorld: new Vector3(), - } + _lookTarget: new Vector3(), - } ); + getViewportCount: function () { - /** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + return this._viewportCount; - function OrthographicCamera( left, right, top, bottom, near, far ) { + }, - Camera.call( this ); + getFrustum: function () { - this.type = 'OrthographicCamera'; + return this._frustum; - this.zoom = 1; - this.view = null; + }, - this.left = ( left !== undefined ) ? left : - 1; - this.right = ( right !== undefined ) ? right : 1; - this.top = ( top !== undefined ) ? top : 1; - this.bottom = ( bottom !== undefined ) ? bottom : - 1; + updateMatrices: function ( light ) { - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + var shadowCamera = this.camera, + shadowMatrix = this.matrix, + projScreenMatrix = this._projScreenMatrix, + lookTarget = this._lookTarget, + lightPositionWorld = this._lightPositionWorld; - this.updateProjectionMatrix(); + lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( lightPositionWorld ); - } + lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( lookTarget ); + shadowCamera.updateMatrixWorld(); - OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( projScreenMatrix ); - constructor: OrthographicCamera, + shadowMatrix.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 + ); - isOrthographicCamera: true, + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - copy: function ( source, recursive ) { + }, - Camera.prototype.copy.call( this, source, recursive ); + getViewport: function ( viewportIndex ) { - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; + return this._viewports[ viewportIndex ]; - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + }, - return this; + getFrameExtents: function () { - }, + return this._frameExtents; - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + }, - if ( this.view === null ) { + copy: function ( source ) { - this.view = { - enabled: true, - fullWidth: 1, - fullHeight: 1, - offsetX: 0, - offsetY: 0, - width: 1, - height: 1 - }; + this.camera = source.camera.clone(); - } + this.bias = source.bias; + this.radius = source.radius; - this.view.enabled = true; - this.view.fullWidth = fullWidth; - this.view.fullHeight = fullHeight; - this.view.offsetX = x; - this.view.offsetY = y; - this.view.width = width; - this.view.height = height; + this.mapSize.copy( source.mapSize ); - this.updateProjectionMatrix(); + return this; - }, + }, - clearViewOffset: function () { + clone: function () { - if ( this.view !== null ) { + return new this.constructor().copy( this ); - this.view.enabled = false; + }, - } + toJSON: function () { - this.updateProjectionMatrix(); + var object = {}; - }, + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); - updateProjectionMatrix: function () { + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; - var dx = ( this.right - this.left ) / ( 2 * this.zoom ); - var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - var cx = ( this.right + this.left ) / 2; - var cy = ( this.top + this.bottom ) / 2; + return object; - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + } - if ( this.view !== null && this.view.enabled ) { +} ); - var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); - var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); - var scaleW = ( this.right - this.left ) / this.view.width; - var scaleH = ( this.top - this.bottom ) / this.view.height; +/** + * @author mrdoob / http://mrdoob.com/ + */ - left += scaleW * ( this.view.offsetX / zoomW ); - right = left + scaleW * ( this.view.width / zoomW ); - top -= scaleH * ( this.view.offsetY / zoomH ); - bottom = top - scaleH * ( this.view.height / zoomH ); +function SpotLightShadow() { - } + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); +} - this.projectionMatrixInverse.getInverse( this.projectionMatrix ); +SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - }, + constructor: SpotLightShadow, - toJSON: function ( meta ) { + isSpotLightShadow: true, - var data = Object3D.prototype.toJSON.call( this, meta ); + updateMatrices: function ( light ) { - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; + var camera = this.camera; - if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); } + var fov = MathUtils.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || camera.far; - return data; + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); } - } ); + LightShadow.prototype.updateMatrices.call( this, light ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function DirectionalLightShadow() { +} ); - LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - } +function SpotLight( color, intensity, distance, angle, penumbra, decay ) { - DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + Light.call( this, color, intensity ); - constructor: DirectionalLightShadow, + this.type = 'SpotLight'; - isDirectionalLightShadow: true, + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - updateMatrices: function ( light ) { + this.target = new Object3D(); - LightShadow.prototype.updateMatrices.call( this, light ); + Object.defineProperty( this, 'power', { + get: function () { - } + // intensity = power per solid angle. + // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + return this.intensity * Math.PI; - } ); + }, + set: function ( power ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + // intensity = power per solid angle. + // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + this.intensity = power / Math.PI; - function DirectionalLight( color, intensity ) { - - Light.call( this, color, intensity ); + } + } ); - this.type = 'DirectionalLight'; + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + this.shadow = new SpotLightShadow(); - this.target = new Object3D(); +} - this.shadow = new DirectionalLightShadow(); +SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - } + constructor: SpotLight, - DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { + isSpotLight: true, - constructor: DirectionalLight, + copy: function ( source ) { - isDirectionalLight: true, + Light.prototype.copy.call( this, source ); - copy: function ( source ) { + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - Light.prototype.copy.call( this, source ); + this.target = source.target.clone(); - this.target = source.target.clone(); + this.shadow = source.shadow.clone(); - this.shadow = source.shadow.clone(); + return this; - return this; + } - } +} ); - } ); +function PointLightShadow() { - /** - * @author mrdoob / http://mrdoob.com/ - */ + LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - function AmbientLight( color, intensity ) { + this._frameExtents = new Vector2( 4, 2 ); - Light.call( this, color, intensity ); + this._viewportCount = 6; - this.type = 'AmbientLight'; + this._viewports = [ + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction + + // positive X + new Vector4( 2, 1, 1, 1 ), + // negative X + new Vector4( 0, 1, 1, 1 ), + // positive Z + new Vector4( 3, 1, 1, 1 ), + // negative Z + new Vector4( 1, 1, 1, 1 ), + // positive Y + new Vector4( 3, 0, 1, 1 ), + // negative Y + new Vector4( 1, 0, 1, 1 ) + ]; - this.castShadow = undefined; + this._cubeDirections = [ + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) + ]; - } + this._cubeUps = [ + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) + ]; - AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { +} - constructor: AmbientLight, +PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - isAmbientLight: true + constructor: PointLightShadow, - } ); + isPointLightShadow: true, - /** - * @author abelnation / http://github.com/abelnation - */ + updateMatrices: function ( light, viewportIndex ) { - function RectAreaLight( color, intensity, width, height ) { + if ( viewportIndex === undefined ) viewportIndex = 0; - Light.call( this, color, intensity ); + var camera = this.camera, + shadowMatrix = this.matrix, + lightPositionWorld = this._lightPositionWorld, + lookTarget = this._lookTarget, + projScreenMatrix = this._projScreenMatrix; - this.type = 'RectAreaLight'; + lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + camera.position.copy( lightPositionWorld ); - this.width = ( width !== undefined ) ? width : 10; - this.height = ( height !== undefined ) ? height : 10; + lookTarget.copy( camera.position ); + lookTarget.add( this._cubeDirections[ viewportIndex ] ); + camera.up.copy( this._cubeUps[ viewportIndex ] ); + camera.lookAt( lookTarget ); + camera.updateMatrixWorld(); - } + shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z ); - RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { + projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + this._frustum.setFromProjectionMatrix( projScreenMatrix ); - constructor: RectAreaLight, + } - isRectAreaLight: true, +} ); - copy: function ( source ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - Light.prototype.copy.call( this, source ); - this.width = source.width; - this.height = source.height; +function PointLight( color, intensity, distance, decay ) { - return this; + Light.call( this, color, intensity ); - }, + this.type = 'PointLight'; - toJSON: function ( meta ) { + Object.defineProperty( this, 'power', { + get: function () { - var data = Light.prototype.toJSON.call( this, meta ); + // intensity = power per solid angle. + // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + return this.intensity * 4 * Math.PI; - data.object.width = this.width; - data.object.height = this.height; + }, + set: function ( power ) { - return data; + // intensity = power per solid angle. + // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + this.intensity = power / ( 4 * Math.PI ); } - } ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - function MaterialLoader( manager ) { + this.shadow = new PointLightShadow(); - Loader.call( this, manager ); +} - this.textures = {}; - - } +PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + constructor: PointLight, - constructor: MaterialLoader, + isPointLight: true, - load: function ( url, onLoad, onProgress, onError ) { + copy: function ( source ) { - var scope = this; + Light.prototype.copy.call( this, source ); - var loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.load( url, function ( text ) { + this.distance = source.distance; + this.decay = source.decay; - onLoad( scope.parse( JSON.parse( text ) ) ); + this.shadow = source.shadow.clone(); - }, onProgress, onError ); + return this; - }, + } - parse: function ( json ) { +} ); - var textures = this.textures; +/** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - function getTexture( name ) { +function OrthographicCamera( left, right, top, bottom, near, far ) { - if ( textures[ name ] === undefined ) { + Camera.call( this ); - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + this.type = 'OrthographicCamera'; - } + this.zoom = 1; + this.view = null; - return textures[ name ]; + this.left = ( left !== undefined ) ? left : - 1; + this.right = ( right !== undefined ) ? right : 1; + this.top = ( top !== undefined ) ? top : 1; + this.bottom = ( bottom !== undefined ) ? bottom : - 1; - } + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - var material = new Materials[ json.type ](); + this.updateProjectionMatrix(); - if ( json.uuid !== undefined ) { material.uuid = json.uuid; } - if ( json.name !== undefined ) { material.name = json.name; } - if ( json.color !== undefined ) { material.color.setHex( json.color ); } - if ( json.roughness !== undefined ) { material.roughness = json.roughness; } - if ( json.metalness !== undefined ) { material.metalness = json.metalness; } - if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); } - if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); } - if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); } - if ( json.shininess !== undefined ) { material.shininess = json.shininess; } - if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; } - if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; } - if ( json.vertexColors !== undefined ) { material.vertexColors = json.vertexColors; } - if ( json.fog !== undefined ) { material.fog = json.fog; } - if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; } - if ( json.blending !== undefined ) { material.blending = json.blending; } - if ( json.combine !== undefined ) { material.combine = json.combine; } - if ( json.side !== undefined ) { material.side = json.side; } - if ( json.opacity !== undefined ) { material.opacity = json.opacity; } - if ( json.transparent !== undefined ) { material.transparent = json.transparent; } - if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; } - if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; } - if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; } - if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; } +} - if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; } - if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; } - if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; } - if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; } - if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; } - if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; } - if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; } - if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; } +OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; } - if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; } - if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; } - if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; } + constructor: OrthographicCamera, - if ( json.rotation !== undefined ) { material.rotation = json.rotation; } + isOrthographicCamera: true, - if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; } - if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; } - if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; } - if ( json.scale !== undefined ) { material.scale = json.scale; } + copy: function ( source, recursive ) { - if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; } - if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; } - if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; } + Camera.prototype.copy.call( this, source, recursive ); - if ( json.skinning !== undefined ) { material.skinning = json.skinning; } - if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; } - if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; } - if ( json.dithering !== undefined ) { material.dithering = json.dithering; } + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - if ( json.visible !== undefined ) { material.visible = json.visible; } + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; } + return this; - if ( json.userData !== undefined ) { material.userData = json.userData; } + }, - // Shader Material + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { - if ( json.uniforms !== undefined ) { + if ( this.view === null ) { - for ( var name in json.uniforms ) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; - var uniform = json.uniforms[ name ]; + } - material.uniforms[ name ] = {}; + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - switch ( uniform.type ) { + this.updateProjectionMatrix(); - case 't': - material.uniforms[ name ].value = getTexture( uniform.value ); - break; + }, - case 'c': - material.uniforms[ name ].value = new Color().setHex( uniform.value ); - break; + clearViewOffset: function () { - case 'v2': - material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); - break; + if ( this.view !== null ) { - case 'v3': - material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); - break; + this.view.enabled = false; - case 'v4': - material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); - break; + } - case 'm3': - material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); + this.updateProjectionMatrix(); - case 'm4': - material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); - break; + }, - default: - material.uniforms[ name ].value = uniform.value; + updateProjectionMatrix: function () { - } + var dx = ( this.right - this.left ) / ( 2 * this.zoom ); + var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + var cx = ( this.right + this.left ) / 2; + var cy = ( this.top + this.bottom ) / 2; - } + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - } + if ( this.view !== null && this.view.enabled ) { - if ( json.defines !== undefined ) { material.defines = json.defines; } - if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; } - if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; } + var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; + var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; - if ( json.extensions !== undefined ) { + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; - for ( var key in json.extensions ) { + } - material.extensions[ key ] = json.extensions[ key ]; + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - } + this.projectionMatrixInverse.getInverse( this.projectionMatrix ); - } + }, - // Deprecated + toJSON: function ( meta ) { - if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading + var data = Object3D.prototype.toJSON.call( this, meta ); - // for PointsMaterial + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; - if ( json.size !== undefined ) { material.size = json.size; } - if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; } + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - // maps + return data; - if ( json.map !== undefined ) { material.map = getTexture( json.map ); } - if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); } + } - if ( json.alphaMap !== undefined ) { +} ); - material.alphaMap = getTexture( json.alphaMap ); - material.transparent = true; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function DirectionalLightShadow() { - if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); } - if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; } + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); } - if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; } - if ( json.normalScale !== undefined ) { +} - var normalScale = json.normalScale; +DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - if ( Array.isArray( normalScale ) === false ) { + constructor: DirectionalLightShadow, - // Blender exporter used to export a scalar. See #7459 + isDirectionalLightShadow: true, - normalScale = [ normalScale, normalScale ]; + updateMatrices: function ( light ) { - } + LightShadow.prototype.updateMatrices.call( this, light ); - material.normalScale = new Vector2().fromArray( normalScale ); + } - } +} ); - if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); } - if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; } - if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; } +/** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); } - if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); } +function DirectionalLight( color, intensity ) { - if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); } - if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; } + Light.call( this, color, intensity ); - if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); } + this.type = 'DirectionalLight'; - if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); } - if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; } + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; } - if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; } + this.target = new Object3D(); - if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); } - if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; } + this.shadow = new DirectionalLightShadow(); - if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); } - if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; } +} - if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); } +DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); } - if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); } + constructor: DirectionalLight, - return material; + isDirectionalLight: true, - }, + copy: function ( source ) { - setTextures: function ( value ) { + Light.prototype.copy.call( this, source ); - this.textures = value; - return this; + this.target = source.target.clone(); - } + this.shadow = source.shadow.clone(); - } ); + return this; - /** - * @author Don McCurdy / https://www.donmccurdy.com - */ + } - var LoaderUtils = { +} ); - decodeText: function ( array ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - if ( typeof TextDecoder !== 'undefined' ) { +function AmbientLight( color, intensity ) { - return new TextDecoder().decode( array ); + Light.call( this, color, intensity ); - } + this.type = 'AmbientLight'; - // Avoid the String.fromCharCode.apply(null, array) shortcut, which - // throws a "maximum call stack size exceeded" error for large arrays. + this.castShadow = undefined; - var s = ''; +} - for ( var i = 0, il = array.length; i < il; i ++ ) { +AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - // Implicitly assumes little-endian. - s += String.fromCharCode( array[ i ] ); + constructor: AmbientLight, - } + isAmbientLight: true - try { +} ); - // merges multi-byte utf-8 characters. +/** + * @author abelnation / http://github.com/abelnation + */ - return decodeURIComponent( escape( s ) ); +function RectAreaLight( color, intensity, width, height ) { - } catch ( e ) { // see #16358 + Light.call( this, color, intensity ); - return s; + this.type = 'RectAreaLight'; - } + this.width = ( width !== undefined ) ? width : 10; + this.height = ( height !== undefined ) ? height : 10; - }, +} - extractUrlBase: function ( url ) { +RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { - var index = url.lastIndexOf( '/' ); + constructor: RectAreaLight, - if ( index === - 1 ) { return './'; } + isRectAreaLight: true, - return url.substr( 0, index + 1 ); + copy: function ( source ) { - } + Light.prototype.copy.call( this, source ); - }; + this.width = source.width; + this.height = source.height; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + return this; - function InstancedBufferGeometry() { + }, - BufferGeometry.call( this ); + toJSON: function ( meta ) { - this.type = 'InstancedBufferGeometry'; - this.maxInstancedCount = undefined; + var data = Light.prototype.toJSON.call( this, meta ); - } + data.object.width = this.width; + data.object.height = this.height; - InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), { + return data; - constructor: InstancedBufferGeometry, + } - isInstancedBufferGeometry: true, +} ); - copy: function ( source ) { +/** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * Primary reference: + * https://graphics.stanford.edu/papers/envmap/envmap.pdf + * + * Secondary reference: + * https://www.ppsloan.org/publications/StupidSH36.pdf + */ - BufferGeometry.prototype.copy.call( this, source ); +// 3-band SH defined by 9 coefficients - this.maxInstancedCount = source.maxInstancedCount; +function SphericalHarmonics3() { - return this; + this.coefficients = []; - }, + for ( var i = 0; i < 9; i ++ ) { - clone: function () { + this.coefficients.push( new Vector3() ); - return new this.constructor().copy( this ); + } - }, +} - toJSON: function () { +Object.assign( SphericalHarmonics3.prototype, { - var data = BufferGeometry.prototype.toJSON.call( this ); + isSphericalHarmonics3: true, - data.maxInstancedCount = this.maxInstancedCount; + set: function ( coefficients ) { - data.isInstancedBufferGeometry = true; + for ( var i = 0; i < 9; i ++ ) { - return data; + this.coefficients[ i ].copy( coefficients[ i ] ); } - } ); + return this; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + }, - function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { + zero: function () { - if ( typeof ( normalized ) === 'number' ) { + for ( var i = 0; i < 9; i ++ ) { - meshPerAttribute = normalized; + this.coefficients[ i ].set( 0, 0, 0 ); - normalized = false; + } - console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); + return this; - } + }, - BufferAttribute.call( this, array, itemSize, normalized ); + // get the radiance in the direction of the normal + // target is a Vector3 + getAt: function ( normal, target ) { - this.meshPerAttribute = meshPerAttribute || 1; + // normal is assumed to be unit length - } + var x = normal.x, y = normal.y, z = normal.z; - InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), { + var coeff = this.coefficients; - constructor: InstancedBufferAttribute, + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); - isInstancedBufferAttribute: true, + // band 1 + target.addScaledVector( coeff[ 1 ], 0.488603 * y ); + target.addScaledVector( coeff[ 2 ], 0.488603 * z ); + target.addScaledVector( coeff[ 3 ], 0.488603 * x ); - copy: function ( source ) { + // band 2 + target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) ); + target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) ); + target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); + target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) ); + target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); - BufferAttribute.prototype.copy.call( this, source ); + return target; - this.meshPerAttribute = source.meshPerAttribute; + }, - return this; + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt: function ( normal, target ) { - }, + // normal is assumed to be unit length - toJSON: function () { + var x = normal.x, y = normal.y, z = normal.z; - var data = BufferAttribute.prototype.toJSON.call( this ); + var coeff = this.coefficients; - data.meshPerAttribute = this.meshPerAttribute; + // band 0 + target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 - data.isInstancedBufferAttribute = true; + // band 1 + target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 + target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z ); + target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x ); - return data; + // band 2 + target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 + target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z ); + target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 + target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z ); + target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 - } + return target; - } ); + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + add: function ( sh ) { - function BufferGeometryLoader( manager ) { + for ( var i = 0; i < 9; i ++ ) { - Loader.call( this, manager ); + this.coefficients[ i ].add( sh.coefficients[ i ] ); - } + } + + return this; - BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + }, - constructor: BufferGeometryLoader, + addScaledSH: function ( sh, s ) { - load: function ( url, onLoad, onProgress, onError ) { + for ( var i = 0; i < 9; i ++ ) { - var scope = this; + this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s ); - var loader = new FileLoader( scope.manager ); - loader.setPath( scope.path ); - loader.load( url, function ( text ) { + } - onLoad( scope.parse( JSON.parse( text ) ) ); + return this; - }, onProgress, onError ); + }, - }, + scale: function ( s ) { - parse: function ( json ) { + for ( var i = 0; i < 9; i ++ ) { - var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + this.coefficients[ i ].multiplyScalar( s ); - var index = json.data.index; + } - if ( index !== undefined ) { + return this; - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + }, - } + lerp: function ( sh, alpha ) { - var attributes = json.data.attributes; + for ( var i = 0; i < 9; i ++ ) { - for ( var key in attributes ) { + this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; - var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); - if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; } - geometry.setAttribute( key, bufferAttribute ); + } - } + return this; - var morphAttributes = json.data.morphAttributes; + }, - if ( morphAttributes ) { + equals: function ( sh ) { - for ( var key in morphAttributes ) { + for ( var i = 0; i < 9; i ++ ) { - var attributeArray = morphAttributes[ key ]; + if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { - var array = []; + return false; - for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { + } - var attribute = attributeArray[ i ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + } - var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); - if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; } - array.push( bufferAttribute ); + return true; - } + }, - geometry.morphAttributes[ key ] = array; + copy: function ( sh ) { - } + return this.set( sh.coefficients ); - } + }, - var morphTargetsRelative = json.data.morphTargetsRelative; + clone: function () { - if ( morphTargetsRelative ) { + return new this.constructor().copy( this ); - geometry.morphTargetsRelative = true; + }, - } + fromArray: function ( array, offset ) { - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if ( offset === undefined ) offset = 0; - if ( groups !== undefined ) { + var coefficients = this.coefficients; - for ( var i = 0, n = groups.length; i !== n; ++ i ) { + for ( var i = 0; i < 9; i ++ ) { - var group = groups[ i ]; + coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); - geometry.addGroup( group.start, group.count, group.materialIndex ); + } - } + return this; - } + }, - var boundingSphere = json.data.boundingSphere; + toArray: function ( array, offset ) { - if ( boundingSphere !== undefined ) { + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - var center = new Vector3(); + var coefficients = this.coefficients; - if ( boundingSphere.center !== undefined ) { + for ( var i = 0; i < 9; i ++ ) { - center.fromArray( boundingSphere.center ); + coefficients[ i ].toArray( array, offset + ( i * 3 ) ); - } + } - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + return array; - } + } - if ( json.name ) { geometry.name = json.name; } - if ( json.userData ) { geometry.userData = json.userData; } +} ); - return geometry; +Object.assign( SphericalHarmonics3, { - } + // evaluate the basis functions + // shBasis is an Array[ 9 ] + getBasisAt: function ( normal, shBasis ) { - } ); + // normal is assumed to be unit length - var TYPED_ARRAYS = { - Int8Array: Int8Array, - Uint8Array: Uint8Array, - // Workaround for IE11 pre KB2929437. See #11440 - Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, - Int16Array: Int16Array, - Uint16Array: Uint16Array, - Int32Array: Int32Array, - Uint32Array: Uint32Array, - Float32Array: Float32Array, - Float64Array: Float64Array - }; + var x = normal.x, y = normal.y, z = normal.z; - /** - * @author mrdoob / http://mrdoob.com/ - */ + // band 0 + shBasis[ 0 ] = 0.282095; - function ObjectLoader( manager ) { + // band 1 + shBasis[ 1 ] = 0.488603 * y; + shBasis[ 2 ] = 0.488603 * z; + shBasis[ 3 ] = 0.488603 * x; - Loader.call( this, manager ); + // band 2 + shBasis[ 4 ] = 1.092548 * x * y; + shBasis[ 5 ] = 1.092548 * y * z; + shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); + shBasis[ 7 ] = 1.092548 * x * z; + shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); } - ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), { +} ); - constructor: ObjectLoader, +/** + * @author WestLangley / http://github.com/WestLangley + * + * A LightProbe is a source of indirect-diffuse light + */ - load: function ( url, onLoad, onProgress, onError ) { +function LightProbe( sh, intensity ) { - var scope = this; + Light.call( this, undefined, intensity ); - var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; - this.resourcePath = this.resourcePath || path; + this.type = 'LightProbe'; - var loader = new FileLoader( scope.manager ); - loader.setPath( this.path ); - loader.load( url, function ( text ) { + this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3(); - var json = null; +} - try { +LightProbe.prototype = Object.assign( Object.create( Light.prototype ), { - json = JSON.parse( text ); + constructor: LightProbe, - } catch ( error ) { + isLightProbe: true, - if ( onError !== undefined ) { onError( error ); } + copy: function ( source ) { - console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + Light.prototype.copy.call( this, source ); - return; + this.sh.copy( source.sh ); - } + return this; - var metadata = json.metadata; + }, - if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + fromJSON: function ( json ) { - console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); - return; + this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON(); + this.sh.fromArray( json.sh ); - } + return this; - scope.parse( json, onLoad ); + }, - }, onProgress, onError ); + toJSON: function ( meta ) { - }, + var data = Light.prototype.toJSON.call( this, meta ); - parse: function ( json, onLoad ) { + data.object.sh = this.sh.toArray(); - var shapes = this.parseShape( json.shapes ); - var geometries = this.parseGeometries( json.geometries, shapes ); + return data; - var images = this.parseImages( json.images, function () { + } - if ( onLoad !== undefined ) { onLoad( object ); } +} ); - } ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); +function MaterialLoader( manager ) { - var object = this.parseObject( json.object, geometries, materials ); + Loader.call( this, manager ); - if ( json.animations ) { + this.textures = {}; - object.animations = this.parseAnimations( json.animations ); +} - } +MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - if ( json.images === undefined || json.images.length === 0 ) { + constructor: MaterialLoader, - if ( onLoad !== undefined ) { onLoad( object ); } + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - return object; + var loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.load( url, function ( text ) { - }, + try { - parseShape: function ( json ) { + onLoad( scope.parse( JSON.parse( text ) ) ); - var shapes = {}; + } catch ( e ) { - if ( json !== undefined ) { + if ( onError ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + onError( e ); - var shape = new Shape().fromJSON( json[ i ] ); + } else { - shapes[ shape.uuid ] = shape; + console.error( e ); } + scope.manager.itemError( url ); + } - return shapes; + }, onProgress, onError ); - }, + }, - parseGeometries: function ( json, shapes ) { + parse: function ( json ) { - var geometries = {}; + var textures = this.textures; - if ( json !== undefined ) { + function getTexture( name ) { - var bufferGeometryLoader = new BufferGeometryLoader(); + if ( textures[ name ] === undefined ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - var geometry; - var data = json[ i ]; + } - switch ( data.type ) { + return textures[ name ]; - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + var material = new Materials[ json.type ](); - break; + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.roughness !== undefined ) material.roughness = json.roughness; + if ( json.metalness !== undefined ) material.metalness = json.metalness; + if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen ); + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat; + if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness; + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.combine !== undefined ) material.combine = json.combine; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; + if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; + if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask; + if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc; + if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef; + if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask; + if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail; + if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail; + if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass; - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; - break; + if ( json.rotation !== undefined ) material.rotation = json.rotation; - case 'CircleGeometry': - case 'CircleBufferGeometry': + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; - geometry = new Geometries[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; - break; + if ( json.skinning !== undefined ) material.skinning = json.skinning; + if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; + if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals; + if ( json.dithering !== undefined ) material.dithering = json.dithering; - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents; - geometry = new Geometries[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + if ( json.visible !== undefined ) material.visible = json.visible; - break; + if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped; - case 'ConeGeometry': - case 'ConeBufferGeometry': + if ( json.userData !== undefined ) material.userData = json.userData; - geometry = new Geometries[ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + if ( json.vertexColors !== undefined ) { - break; + if ( typeof json.vertexColors === 'number' ) { - case 'SphereGeometry': - case 'SphereBufferGeometry': + material.vertexColors = ( json.vertexColors > 0 ) ? true : false; - geometry = new Geometries[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + } else { - break; + material.vertexColors = json.vertexColors; - case 'DodecahedronGeometry': - case 'DodecahedronBufferGeometry': - case 'IcosahedronGeometry': - case 'IcosahedronBufferGeometry': - case 'OctahedronGeometry': - case 'OctahedronBufferGeometry': - case 'TetrahedronGeometry': - case 'TetrahedronBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radius, - data.detail - ); + } - break; + // Shader Material - case 'RingGeometry': - case 'RingBufferGeometry': + if ( json.uniforms !== undefined ) { - geometry = new Geometries[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + for ( var name in json.uniforms ) { - break; + var uniform = json.uniforms[ name ]; - case 'TorusGeometry': - case 'TorusBufferGeometry': + material.uniforms[ name ] = {}; - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + switch ( uniform.type ) { - break; + case 't': + material.uniforms[ name ].value = getTexture( uniform.value ); + break; - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + case 'c': + material.uniforms[ name ].value = new Color().setHex( uniform.value ); + break; - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + case 'v2': + material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); + break; - break; + case 'v3': + material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); + break; - case 'TubeGeometry': - case 'TubeBufferGeometry': + case 'v4': + material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); + break; - // This only works for built-in curves (e.g. CatmullRomCurve3). - // User defined curves or instances of CurvePath will not be deserialized. - geometry = new Geometries[ data.type ]( - new Curves[ data.path.type ]().fromJSON( data.path ), - data.tubularSegments, - data.radius, - data.radialSegments, - data.closed - ); + case 'm3': + material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); - break; + case 'm4': + material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); + break; - case 'LatheGeometry': - case 'LatheBufferGeometry': + default: + material.uniforms[ name ].value = uniform.value; - geometry = new Geometries[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + } - break; + } - case 'PolyhedronGeometry': - case 'PolyhedronBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.vertices, - data.indices, - data.radius, - data.details - ); + if ( json.defines !== undefined ) material.defines = json.defines; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; - break; + if ( json.extensions !== undefined ) { - case 'ShapeGeometry': - case 'ShapeBufferGeometry': + for ( var key in json.extensions ) { - var geometryShapes = []; + material.extensions[ key ] = json.extensions[ key ]; - for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { + } - var shape = shapes[ data.shapes[ j ] ]; + } - geometryShapes.push( shape ); + // Deprecated - } + if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading - geometry = new Geometries[ data.type ]( - geometryShapes, - data.curveSegments - ); + // for PointsMaterial - break; + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + // maps - case 'ExtrudeGeometry': - case 'ExtrudeBufferGeometry': + if ( json.map !== undefined ) material.map = getTexture( json.map ); + if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap ); - var geometryShapes = []; + if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap ); - for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - var shape = shapes[ data.shapes[ j ] ]; + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType; + if ( json.normalScale !== undefined ) { - geometryShapes.push( shape ); + var normalScale = json.normalScale; - } + if ( Array.isArray( normalScale ) === false ) { - var extrudePath = data.options.extrudePath; + // Blender exporter used to export a scalar. See #7459 - if ( extrudePath !== undefined ) { + normalScale = [ normalScale, normalScale ]; - data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); + } - } + material.normalScale = new Vector2().fromArray( normalScale ); - geometry = new Geometries[ data.type ]( - geometryShapes, - data.options - ); + } - break; + if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - case 'BufferGeometry': - case 'InstancedBufferGeometry': + if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); - geometry = bufferGeometryLoader.parse( data ); + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - break; + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); - case 'Geometry': + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity; - if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) { + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio; - var geometryLoader = new THREE.LegacyJSONLoader(); - geometry = geometryLoader.parse( data, this.resourcePath ).geometry; + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - } else { + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); - console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' ); + if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap ); + if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap ); + if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); + if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); - } + return material; - break; + }, - default: + setTextures: function ( value ) { - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); + this.textures = value; + return this; - continue; + } - } +} ); - geometry.uuid = data.uuid; +/** + * @author Don McCurdy / https://www.donmccurdy.com + */ - if ( data.name !== undefined ) { geometry.name = data.name; } - if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; } +var LoaderUtils = { - geometries[ data.uuid ] = geometry; + decodeText: function ( array ) { - } + if ( typeof TextDecoder !== 'undefined' ) { - } + return new TextDecoder().decode( array ); - return geometries; + } - }, + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. - parseMaterials: function ( json, textures ) { + var s = ''; - var cache = {}; // MultiMaterial - var materials = {}; + for ( var i = 0, il = array.length; i < il; i ++ ) { - if ( json !== undefined ) { + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); - var loader = new MaterialLoader(); - loader.setTextures( textures ); + } - for ( var i = 0, l = json.length; i < l; i ++ ) { + try { - var data = json[ i ]; + // merges multi-byte utf-8 characters. - if ( data.type === 'MultiMaterial' ) { + return decodeURIComponent( escape( s ) ); - // Deprecated + } catch ( e ) { // see #16358 - var array = []; + return s; - for ( var j = 0; j < data.materials.length; j ++ ) { + } - var material = data.materials[ j ]; + }, - if ( cache[ material.uuid ] === undefined ) { + extractUrlBase: function ( url ) { - cache[ material.uuid ] = loader.parse( material ); + var index = url.lastIndexOf( '/' ); - } + if ( index === - 1 ) return './'; - array.push( cache[ material.uuid ] ); + return url.substr( 0, index + 1 ); - } + } - materials[ data.uuid ] = array; +}; - } else { +/** + * @author benaadams / https://twitter.com/ben_a_adams + */ - if ( cache[ data.uuid ] === undefined ) { +function InstancedBufferGeometry() { - cache[ data.uuid ] = loader.parse( data ); + BufferGeometry.call( this ); - } + this.type = 'InstancedBufferGeometry'; + this.instanceCount = Infinity; - materials[ data.uuid ] = cache[ data.uuid ]; +} - } +InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), { - } + constructor: InstancedBufferGeometry, - } + isInstancedBufferGeometry: true, - return materials; + copy: function ( source ) { - }, + BufferGeometry.prototype.copy.call( this, source ); - parseAnimations: function ( json ) { + this.instanceCount = source.instanceCount; - var animations = []; + return this; - for ( var i = 0; i < json.length; i ++ ) { + }, - var data = json[ i ]; + clone: function () { - var clip = AnimationClip.parse( data ); + return new this.constructor().copy( this ); - if ( data.uuid !== undefined ) { clip.uuid = data.uuid; } + }, - animations.push( clip ); + toJSON: function () { - } + var data = BufferGeometry.prototype.toJSON.call( this ); - return animations; + data.instanceCount = this.instanceCount; - }, + data.isInstancedBufferGeometry = true; - parseImages: function ( json, onLoad ) { + return data; - var scope = this; - var images = {}; + } - function loadImage( url ) { +} ); - scope.manager.itemStart( url ); +/** + * @author benaadams / https://twitter.com/ben_a_adams + */ - return loader.load( url, function () { +function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { - scope.manager.itemEnd( url ); + if ( typeof ( normalized ) === 'number' ) { - }, undefined, function () { + meshPerAttribute = normalized; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + normalized = false; - } ); + console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); - } + } - if ( json !== undefined && json.length > 0 ) { + BufferAttribute.call( this, array, itemSize, normalized ); - var manager = new LoadingManager( onLoad ); + this.meshPerAttribute = meshPerAttribute || 1; - var loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); +} - for ( var i = 0, il = json.length; i < il; i ++ ) { +InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), { - var image = json[ i ]; - var url = image.url; + constructor: InstancedBufferAttribute, - if ( Array.isArray( url ) ) { + isInstancedBufferAttribute: true, - // load array of images e.g CubeTexture + copy: function ( source ) { - images[ image.uuid ] = []; + BufferAttribute.prototype.copy.call( this, source ); - for ( var j = 0, jl = url.length; j < jl; j ++ ) { + this.meshPerAttribute = source.meshPerAttribute; - var currentUrl = url[ j ]; + return this; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl; + }, - images[ image.uuid ].push( loadImage( path ) ); + toJSON: function () { - } + var data = BufferAttribute.prototype.toJSON.call( this ); - } else { + data.meshPerAttribute = this.meshPerAttribute; - // load single image + data.isInstancedBufferAttribute = true; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url; + return data; - images[ image.uuid ] = loadImage( path ); + } - } +} ); - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function BufferGeometryLoader( manager ) { - return images; + Loader.call( this, manager ); - }, +} - parseTextures: function ( json, images ) { +BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - function parseConstant( value, type ) { + constructor: BufferGeometryLoader, - if ( typeof value === 'number' ) { return value; } + load: function ( url, onLoad, onProgress, onError ) { - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + var scope = this; - return type[ value ]; + var loader = new FileLoader( scope.manager ); + loader.setPath( scope.path ); + loader.load( url, function ( text ) { - } + try { - var textures = {}; + onLoad( scope.parse( JSON.parse( text ) ) ); - if ( json !== undefined ) { + } catch ( e ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + if ( onError ) { - var data = json[ i ]; + onError( e ); - if ( data.image === undefined ) { + } else { - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + console.error( e ); - } + } - if ( images[ data.image ] === undefined ) { + scope.manager.itemError( url ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + } - } + }, onProgress, onError ); - var texture; + }, - if ( Array.isArray( images[ data.image ] ) ) { + parse: function ( json ) { - texture = new CubeTexture( images[ data.image ] ); + var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); - } else { + var index = json.data.index; - texture = new Texture( images[ data.image ] ); + if ( index !== undefined ) { - } + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); - texture.needsUpdate = true; + } - texture.uuid = data.uuid; + var attributes = json.data.attributes; - if ( data.name !== undefined ) { texture.name = data.name; } + for ( var key in attributes ) { - if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); } + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + geometry.setAttribute( key, bufferAttribute ); - if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); } - if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); } - if ( data.center !== undefined ) { texture.center.fromArray( data.center ); } - if ( data.rotation !== undefined ) { texture.rotation = data.rotation; } + } - if ( data.wrap !== undefined ) { + var morphAttributes = json.data.morphAttributes; - texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); - texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + if ( morphAttributes ) { - } + for ( var key in morphAttributes ) { - if ( data.format !== undefined ) { texture.format = data.format; } - if ( data.type !== undefined ) { texture.type = data.type; } - if ( data.encoding !== undefined ) { texture.encoding = data.encoding; } + var attributeArray = morphAttributes[ key ]; - if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); } - if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); } - if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; } + var array = []; - if ( data.flipY !== undefined ) { texture.flipY = data.flipY; } + for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { - if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; } - if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; } + var attribute = attributeArray[ i ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - textures[ data.uuid ] = texture; + var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); + if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name; + array.push( bufferAttribute ); } + geometry.morphAttributes[ key ] = array; + } - return textures; + } - }, + var morphTargetsRelative = json.data.morphTargetsRelative; - parseObject: function ( data, geometries, materials ) { + if ( morphTargetsRelative ) { - var object; + geometry.morphTargetsRelative = true; - function getGeometry( name ) { + } - if ( geometries[ name ] === undefined ) { + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + if ( groups !== undefined ) { - } + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - return geometries[ name ]; + var group = groups[ i ]; - } + geometry.addGroup( group.start, group.count, group.materialIndex ); - function getMaterial( name ) { + } - if ( name === undefined ) { return undefined; } + } - if ( Array.isArray( name ) ) { + var boundingSphere = json.data.boundingSphere; - var array = []; + if ( boundingSphere !== undefined ) { - for ( var i = 0, l = name.length; i < l; i ++ ) { + var center = new Vector3(); - var uuid = name[ i ]; + if ( boundingSphere.center !== undefined ) { - if ( materials[ uuid ] === undefined ) { + center.fromArray( boundingSphere.center ); - console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + } - } + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - array.push( materials[ uuid ] ); + } - } + if ( json.name ) geometry.name = json.name; + if ( json.userData ) geometry.userData = json.userData; - return array; + return geometry; - } + } - if ( materials[ name ] === undefined ) { +} ); - console.warn( 'THREE.ObjectLoader: Undefined material', name ); +var TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + // Workaround for IE11 pre KB2929437. See #11440 + Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array +}; - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - return materials[ name ]; +function ObjectLoader( manager ) { - } + Loader.call( this, manager ); - switch ( data.type ) { +} - case 'Scene': +ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - object = new Scene(); + constructor: ObjectLoader, - if ( data.background !== undefined ) { + load: function ( url, onLoad, onProgress, onError ) { - if ( Number.isInteger( data.background ) ) { + var scope = this; - object.background = new Color( data.background ); + var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; + this.resourcePath = this.resourcePath || path; - } + var loader = new FileLoader( scope.manager ); + loader.setPath( this.path ); + loader.load( url, function ( text ) { - } + var json = null; - if ( data.fog !== undefined ) { + try { - if ( data.fog.type === 'Fog' ) { + json = JSON.parse( text ); - object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + } catch ( error ) { - } else if ( data.fog.type === 'FogExp2' ) { + if ( onError !== undefined ) onError( error ); - object.fog = new FogExp2( data.fog.color, data.fog.density ); + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); - } + return; - } + } - break; + var metadata = json.metadata; - case 'PerspectiveCamera': + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); + return; - if ( data.focus !== undefined ) { object.focus = data.focus; } - if ( data.zoom !== undefined ) { object.zoom = data.zoom; } - if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; } - if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; } - if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); } + } - break; + scope.parse( json, onLoad ); - case 'OrthographicCamera': + }, onProgress, onError ); - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); + }, - if ( data.zoom !== undefined ) { object.zoom = data.zoom; } - if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); } + parse: function ( json, onLoad ) { - break; + var shapes = this.parseShape( json.shapes ); + var geometries = this.parseGeometries( json.geometries, shapes ); - case 'AmbientLight': + var images = this.parseImages( json.images, function () { - object = new AmbientLight( data.color, data.intensity ); + if ( onLoad !== undefined ) onLoad( object ); - break; + } ); - case 'DirectionalLight': + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - object = new DirectionalLight( data.color, data.intensity ); + var object = this.parseObject( json.object, geometries, materials ); - break; + if ( json.animations ) { - case 'PointLight': + object.animations = this.parseAnimations( json.animations ); - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); + } - break; + if ( json.images === undefined || json.images.length === 0 ) { - case 'RectAreaLight': + if ( onLoad !== undefined ) onLoad( object ); - object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + } - break; + return object; - case 'SpotLight': + }, - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + parseShape: function ( json ) { - break; + var shapes = {}; - case 'HemisphereLight': + if ( json !== undefined ) { - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + for ( var i = 0, l = json.length; i < l; i ++ ) { - break; + var shape = new Shape().fromJSON( json[ i ] ); - case 'SkinnedMesh': + shapes[ shape.uuid ] = shape; - console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' ); + } - case 'Mesh': + } - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + return shapes; - if ( geometry.bones && geometry.bones.length > 0 ) { + }, - object = new SkinnedMesh( geometry, material ); + parseGeometries: function ( json, shapes ) { - } else { + var geometries = {}; - object = new Mesh( geometry, material ); + if ( json !== undefined ) { - } + var bufferGeometryLoader = new BufferGeometryLoader(); - break; + for ( var i = 0, l = json.length; i < l; i ++ ) { - case 'InstancedMesh': + var geometry; + var data = json[ i ]; - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); - var count = data.count; - var instanceMatrix = data.instanceMatrix; + switch ( data.type ) { - object = new InstancedMesh( geometry, material, count ); - object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - case 'LOD': + break; - object = new LOD(); + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - break; + geometry = new Geometries[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - case 'Line': + break; - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + case 'CircleGeometry': + case 'CircleBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); - case 'LineLoop': + break; - object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - case 'LineSegments': + break; - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + case 'ConeGeometry': + case 'ConeBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.radius, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - case 'PointCloud': - case 'Points': + break; - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + case 'SphereGeometry': + case 'SphereBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - case 'Sprite': + break; - object = new Sprite( getMaterial( data.material ) ); + case 'DodecahedronGeometry': + case 'DodecahedronBufferGeometry': + case 'IcosahedronGeometry': + case 'IcosahedronBufferGeometry': + case 'OctahedronGeometry': + case 'OctahedronBufferGeometry': + case 'TetrahedronGeometry': + case 'TetrahedronBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.radius, + data.detail + ); - case 'Group': + break; - object = new Group(); + case 'RingGeometry': + case 'RingBufferGeometry': - break; + geometry = new Geometries[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - default: + break; - object = new Object3D(); + case 'TorusGeometry': + case 'TorusBufferGeometry': - } + geometry = new Geometries[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - object.uuid = data.uuid; + break; - if ( data.name !== undefined ) { object.name = data.name; } + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - if ( data.matrix !== undefined ) { + geometry = new Geometries[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - object.matrix.fromArray( data.matrix ); + break; - if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; } - if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); } + case 'TubeGeometry': + case 'TubeBufferGeometry': - } else { + // This only works for built-in curves (e.g. CatmullRomCurve3). + // User defined curves or instances of CurvePath will not be deserialized. + geometry = new Geometries[ data.type ]( + new Curves[ data.path.type ]().fromJSON( data.path ), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); - if ( data.position !== undefined ) { object.position.fromArray( data.position ); } - if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); } - if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); } - if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); } + break; - } + case 'LatheGeometry': + case 'LatheBufferGeometry': - if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; } - if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; } + geometry = new Geometries[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - if ( data.shadow ) { + break; - if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; } - if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; } - if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); } - if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); } + case 'PolyhedronGeometry': + case 'PolyhedronBufferGeometry': - } + geometry = new Geometries[ data.type ]( + data.vertices, + data.indices, + data.radius, + data.details + ); - if ( data.visible !== undefined ) { object.visible = data.visible; } - if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; } - if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; } - if ( data.userData !== undefined ) { object.userData = data.userData; } - if ( data.layers !== undefined ) { object.layers.mask = data.layers; } + break; - if ( data.drawMode !== undefined ) { object.setDrawMode( data.drawMode ); } + case 'ShapeGeometry': + case 'ShapeBufferGeometry': - if ( data.children !== undefined ) { + var geometryShapes = []; - var children = data.children; + for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { - for ( var i = 0; i < children.length; i ++ ) { + var shape = shapes[ data.shapes[ j ] ]; - object.add( this.parseObject( children[ i ], geometries, materials ) ); + geometryShapes.push( shape ); - } + } - } + geometry = new Geometries[ data.type ]( + geometryShapes, + data.curveSegments + ); - if ( data.type === 'LOD' ) { + break; - if ( data.autoUpdate !== undefined ) { object.autoUpdate = data.autoUpdate; } - var levels = data.levels; + case 'ExtrudeGeometry': + case 'ExtrudeBufferGeometry': - for ( var l = 0; l < levels.length; l ++ ) { + var geometryShapes = []; - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { - if ( child !== undefined ) { + var shape = shapes[ data.shapes[ j ] ]; - object.addLevel( child, level.distance ); + geometryShapes.push( shape ); - } + } - } + var extrudePath = data.options.extrudePath; - } + if ( extrudePath !== undefined ) { - return object; + data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); - } + } - } ); + geometry = new Geometries[ data.type ]( + geometryShapes, + data.options + ); - var TEXTURE_MAPPING = { - UVMapping: UVMapping, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - SphericalReflectionMapping: SphericalReflectionMapping, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping - }; + break; - var TEXTURE_WRAPPING = { - RepeatWrapping: RepeatWrapping, - ClampToEdgeWrapping: ClampToEdgeWrapping, - MirroredRepeatWrapping: MirroredRepeatWrapping - }; + case 'BufferGeometry': + case 'InstancedBufferGeometry': - var TEXTURE_FILTER = { - NearestFilter: NearestFilter, - NearestMipmapNearestFilter: NearestMipmapNearestFilter, - NearestMipmapLinearFilter: NearestMipmapLinearFilter, - LinearFilter: LinearFilter, - LinearMipmapNearestFilter: LinearMipmapNearestFilter, - LinearMipmapLinearFilter: LinearMipmapLinearFilter - }; + geometry = bufferGeometryLoader.parse( data ); - /** - * @author thespite / http://clicktorelease.com/ - */ + break; + case 'Geometry': - function ImageBitmapLoader( manager ) { + console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' ); - if ( typeof createImageBitmap === 'undefined' ) { + break; - console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); + default: - } + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - if ( typeof fetch === 'undefined' ) { + continue; - console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); + } - } + geometry.uuid = data.uuid; - Loader.call( this, manager ); + if ( data.name !== undefined ) geometry.name = data.name; + if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData; - this.options = undefined; + geometries[ data.uuid ] = geometry; - } + } - ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + } - constructor: ImageBitmapLoader, + return geometries; - setOptions: function setOptions( options ) { + }, - this.options = options; + parseMaterials: function ( json, textures ) { - return this; + var cache = {}; // MultiMaterial + var materials = {}; - }, + if ( json !== undefined ) { - load: function ( url, onLoad, onProgress, onError ) { + var loader = new MaterialLoader(); + loader.setTextures( textures ); - if ( url === undefined ) { url = ''; } + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( this.path !== undefined ) { url = this.path + url; } + var data = json[ i ]; - url = this.manager.resolveURL( url ); + if ( data.type === 'MultiMaterial' ) { - var scope = this; + // Deprecated - var cached = Cache.get( url ); + var array = []; - if ( cached !== undefined ) { + for ( var j = 0; j < data.materials.length; j ++ ) { - scope.manager.itemStart( url ); + var material = data.materials[ j ]; - setTimeout( function () { + if ( cache[ material.uuid ] === undefined ) { - if ( onLoad ) { onLoad( cached ); } + cache[ material.uuid ] = loader.parse( material ); - scope.manager.itemEnd( url ); + } - }, 0 ); + array.push( cache[ material.uuid ] ); - return cached; + } - } + materials[ data.uuid ] = array; - fetch( url ).then( function ( res ) { + } else { - return res.blob(); + if ( cache[ data.uuid ] === undefined ) { - } ).then( function ( blob ) { + cache[ data.uuid ] = loader.parse( data ); - if ( scope.options === undefined ) { + } - // Workaround for FireFox. It causes an error if you pass options. - return createImageBitmap( blob ); + materials[ data.uuid ] = cache[ data.uuid ]; - } else { + } - return createImageBitmap( blob, scope.options ); + } - } + } - } ).then( function ( imageBitmap ) { + return materials; - Cache.add( url, imageBitmap ); + }, - if ( onLoad ) { onLoad( imageBitmap ); } + parseAnimations: function ( json ) { - scope.manager.itemEnd( url ); + var animations = []; - } ).catch( function ( e ) { + for ( var i = 0; i < json.length; i ++ ) { - if ( onError ) { onError( e ); } + var data = json[ i ]; - scope.manager.itemError( url ); - scope.manager.itemEnd( url ); + var clip = AnimationClip.parse( data ); - } ); + if ( data.uuid !== undefined ) clip.uuid = data.uuid; - scope.manager.itemStart( url ); + animations.push( clip ); } - } ); + return animations; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * minimal class for proxing functions to Path. Replaces old "extractSubpaths()" - **/ + }, - function ShapePath() { + parseImages: function ( json, onLoad ) { - this.type = 'ShapePath'; + var scope = this; + var images = {}; - this.color = new Color(); + function loadImage( url ) { - this.subPaths = []; - this.currentPath = null; + scope.manager.itemStart( url ); - } + return loader.load( url, function () { - Object.assign( ShapePath.prototype, { + scope.manager.itemEnd( url ); - moveTo: function ( x, y ) { + }, undefined, function () { - this.currentPath = new Path(); - this.subPaths.push( this.currentPath ); - this.currentPath.moveTo( x, y ); + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - return this; + } ); - }, + } - lineTo: function ( x, y ) { + if ( json !== undefined && json.length > 0 ) { - this.currentPath.lineTo( x, y ); + var manager = new LoadingManager( onLoad ); - return this; + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - }, + for ( var i = 0, il = json.length; i < il; i ++ ) { - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + var image = json[ i ]; + var url = image.url; - this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); + if ( Array.isArray( url ) ) { - return this; + // load array of images e.g CubeTexture - }, + images[ image.uuid ] = []; - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + for ( var j = 0, jl = url.length; j < jl; j ++ ) { - this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); + var currentUrl = url[ j ]; - return this; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl; - }, + images[ image.uuid ].push( loadImage( path ) ); - splineThru: function ( pts ) { + } - this.currentPath.splineThru( pts ); + } else { - return this; + // load single image - }, + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url; - toShapes: function ( isCCW, noHoles ) { + images[ image.uuid ] = loadImage( path ); - function toShapesNoHoles( inSubpaths ) { + } - var shapes = []; + } - for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { + } - var tmpPath = inSubpaths[ i ]; + return images; - var tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; + }, - shapes.push( tmpShape ); + parseTextures: function ( json, images ) { - } + function parseConstant( value, type ) { - return shapes; + if ( typeof value === 'number' ) return value; - } + console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); - function isPointInsidePolygon( inPt, inPolygon ) { + return type[ value ]; - var polyLen = inPolygon.length; + } - // inPt on polygon contour => immediate success or - // toggling of inside/outside at every single! intersection point of an edge - // with the horizontal line through inPt, left of inPt - // not counting lowerY endpoints of edges and whole edges on that line - var inside = false; - for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { + var textures = {}; - var edgeLowPt = inPolygon[ p ]; - var edgeHighPt = inPolygon[ q ]; + if ( json !== undefined ) { - var edgeDx = edgeHighPt.x - edgeLowPt.x; - var edgeDy = edgeHighPt.y - edgeLowPt.y; + for ( var i = 0, l = json.length; i < l; i ++ ) { - if ( Math.abs( edgeDy ) > Number.EPSILON ) { + var data = json[ i ]; - // not parallel - if ( edgeDy < 0 ) { + if ( data.image === undefined ) { - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; - edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; + console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); - } - if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) { continue; } + } - if ( inPt.y === edgeLowPt.y ) { + if ( images[ data.image ] === undefined ) { - if ( inPt.x === edgeLowPt.x ) { return true; } // inPt is on contour ? - // continue; // no intersection or edgeLowPt => doesn't count !!! + console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); - } else { + } - var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); - if ( perpEdge === 0 ) { return true; } // inPt is on contour ? - if ( perpEdge < 0 ) { continue; } - inside = ! inside; // true intersection left of inPt + var texture; - } + if ( Array.isArray( images[ data.image ] ) ) { - } else { + texture = new CubeTexture( images[ data.image ] ); - // parallel or collinear - if ( inPt.y !== edgeLowPt.y ) { continue; } // parallel - // edge lies on the same horizontal line as inPt - if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || - ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) { return true; } // inPt: Point on contour ! - // continue; + } else { - } + texture = new Texture( images[ data.image ] ); } - return inside; - - } + texture.needsUpdate = true; - var isClockWise = ShapeUtils.isClockWise; + texture.uuid = data.uuid; - var subPaths = this.subPaths; - if ( subPaths.length === 0 ) { return []; } + if ( data.name !== undefined ) texture.name = data.name; - if ( noHoles === true ) { return toShapesNoHoles( subPaths ); } + if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); + if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); + if ( data.center !== undefined ) texture.center.fromArray( data.center ); + if ( data.rotation !== undefined ) texture.rotation = data.rotation; - var solid, tmpPath, tmpShape, shapes = []; + if ( data.wrap !== undefined ) { - if ( subPaths.length === 1 ) { + texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); + texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); - tmpPath = subPaths[ 0 ]; - tmpShape = new Shape(); - tmpShape.curves = tmpPath.curves; - shapes.push( tmpShape ); - return shapes; + } - } + if ( data.format !== undefined ) texture.format = data.format; + if ( data.type !== undefined ) texture.type = data.type; + if ( data.encoding !== undefined ) texture.encoding = data.encoding; - var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); - holesFirst = isCCW ? ! holesFirst : holesFirst; + if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); + if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); + if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; - // console.log("Holes first", holesFirst); + if ( data.flipY !== undefined ) texture.flipY = data.flipY; - var betterShapeHoles = []; - var newShapes = []; - var newShapeHoles = []; - var mainIdx = 0; - var tmpPoints; + if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha; + if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment; - newShapes[ mainIdx ] = undefined; - newShapeHoles[ mainIdx ] = []; + textures[ data.uuid ] = texture; - for ( var i = 0, l = subPaths.length; i < l; i ++ ) { + } - tmpPath = subPaths[ i ]; - tmpPoints = tmpPath.getPoints(); - solid = isClockWise( tmpPoints ); - solid = isCCW ? ! solid : solid; + } - if ( solid ) { + return textures; - if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) { mainIdx ++; } + }, - newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; - newShapes[ mainIdx ].s.curves = tmpPath.curves; + parseObject: function ( data, geometries, materials ) { - if ( holesFirst ) { mainIdx ++; } - newShapeHoles[ mainIdx ] = []; + var object; - //console.log('cw', i); + function getGeometry( name ) { - } else { + if ( geometries[ name ] === undefined ) { - newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); + console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); - //console.log('ccw', i); + } - } + return geometries[ name ]; - } + } - // only Holes? -> probably all Shapes with wrong orientation - if ( ! newShapes[ 0 ] ) { return toShapesNoHoles( subPaths ); } + function getMaterial( name ) { + if ( name === undefined ) return undefined; - if ( newShapes.length > 1 ) { + if ( Array.isArray( name ) ) { - var ambiguous = false; - var toChange = []; + var array = []; - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + for ( var i = 0, l = name.length; i < l; i ++ ) { - betterShapeHoles[ sIdx ] = []; + var uuid = name[ i ]; - } + if ( materials[ uuid ] === undefined ) { - for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); - var sho = newShapeHoles[ sIdx ]; + } - for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { + array.push( materials[ uuid ] ); - var ho = sho[ hIdx ]; - var hole_unassigned = true; + } - for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { + return array; - if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { + } - if ( sIdx !== s2Idx ) { toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); } - if ( hole_unassigned ) { + if ( materials[ name ] === undefined ) { - hole_unassigned = false; - betterShapeHoles[ s2Idx ].push( ho ); + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - } else { + } - ambiguous = true; + return materials[ name ]; - } + } - } + switch ( data.type ) { - } - if ( hole_unassigned ) { + case 'Scene': - betterShapeHoles[ sIdx ].push( ho ); + object = new Scene(); - } + if ( data.background !== undefined ) { - } + if ( Number.isInteger( data.background ) ) { - } - // console.log("ambiguous: ", ambiguous); - if ( toChange.length > 0 ) { + object.background = new Color( data.background ); - // console.log("to change: ", toChange); - if ( ! ambiguous ) { newShapeHoles = betterShapeHoles; } + } } - } + if ( data.fog !== undefined ) { - var tmpHoles; + if ( data.fog.type === 'Fog' ) { - for ( var i = 0, il = newShapes.length; i < il; i ++ ) { + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); - tmpShape = newShapes[ i ].s; - shapes.push( tmpShape ); - tmpHoles = newShapeHoles[ i ]; + } else if ( data.fog.type === 'FogExp2' ) { - for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { + object.fog = new FogExp2( data.fog.color, data.fog.density ); - tmpShape.holes.push( tmpHoles[ j ].h ); + } } - } + break; - //console.log("shape", shapes); + case 'PerspectiveCamera': - return shapes; + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - } + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - } ); + break; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author mrdoob / http://mrdoob.com/ - */ + case 'OrthographicCamera': + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - function Font( data ) { + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - this.type = 'Font'; + break; - this.data = data; + case 'AmbientLight': - } + object = new AmbientLight( data.color, data.intensity ); - Object.assign( Font.prototype, { + break; - isFont: true, + case 'DirectionalLight': - generateShapes: function ( text, size ) { + object = new DirectionalLight( data.color, data.intensity ); - if ( size === undefined ) { size = 100; } + break; - var shapes = []; - var paths = createPaths( text, size, this.data ); + case 'PointLight': - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + break; - } + case 'RectAreaLight': - return shapes; + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); - } + break; - } ); + case 'SpotLight': - function createPaths( text, size, data ) { + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988 - var scale = size / data.resolution; - var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; + break; - var paths = []; + case 'HemisphereLight': - var offsetX = 0, offsetY = 0; + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - for ( var i = 0; i < chars.length; i ++ ) { + break; - var char = chars[ i ]; + case 'LightProbe': - if ( char === '\n' ) { + object = new LightProbe().fromJSON( data ); - offsetX = 0; - offsetY -= line_height; + break; - } else { + case 'SkinnedMesh': - var ret = createPath( char, scale, offsetX, offsetY, data ); - offsetX += ret.offsetX; - paths.push( ret.path ); + console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' ); - } + case 'Mesh': - } + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - return paths; + object = new Mesh( geometry, material ); - } + break; - function createPath( char, scale, offsetX, offsetY, data ) { + case 'InstancedMesh': - var glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); + var count = data.count; + var instanceMatrix = data.instanceMatrix; - if ( ! glyph ) { + object = new InstancedMesh( geometry, material, count ); + object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); - console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); + break; - return; + case 'LOD': - } + object = new LOD(); - var path = new ShapePath(); + break; - var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; + case 'Line': - if ( glyph.o ) { + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - - for ( var i = 0, l = outline.length; i < l; ) { - - var action = outline[ i ++ ]; + break; - switch ( action ) { + case 'LineLoop': - case 'm': // moveTo + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + break; - path.moveTo( x, y ); + case 'LineSegments': - break; + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - case 'l': // lineTo + break; - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + case 'PointCloud': + case 'Points': - path.lineTo( x, y ); + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - break; + break; - case 'q': // quadraticCurveTo + case 'Sprite': - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; + object = new Sprite( getMaterial( data.material ) ); - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + break; - break; + case 'Group': - case 'b': // bezierCurveTo + object = new Group(); - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; - cpx2 = outline[ i ++ ] * scale + offsetX; - cpy2 = outline[ i ++ ] * scale + offsetY; + break; - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + default: - break; + object = new Object3D(); - } + } - } + object.uuid = data.uuid; - } + if ( data.name !== undefined ) object.name = data.name; - return { offsetX: glyph.ha * scale, path: path }; + if ( data.matrix !== undefined ) { - } + object.matrix.fromArray( data.matrix ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate; + if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale ); - function FontLoader( manager ) { + } else { - Loader.call( this, manager ); + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - } + } - FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - constructor: FontLoader, + if ( data.shadow ) { - load: function ( url, onLoad, onProgress, onError ) { + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); - var scope = this; + } - var loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.load( url, function ( text ) { + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; + if ( data.layers !== undefined ) object.layers.mask = data.layers; - var json; + if ( data.children !== undefined ) { - try { + var children = data.children; - json = JSON.parse( text ); + for ( var i = 0; i < children.length; i ++ ) { - } catch ( e ) { + object.add( this.parseObject( children[ i ], geometries, materials ) ); - console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); - json = JSON.parse( text.substring( 65, text.length - 2 ) ); + } - } + } - var font = scope.parse( json ); + if ( data.type === 'LOD' ) { - if ( onLoad ) { onLoad( font ); } + if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate; - }, onProgress, onError ); + var levels = data.levels; - }, + for ( var l = 0; l < levels.length; l ++ ) { - parse: function ( json ) { + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - return new Font( json ); + if ( child !== undefined ) { - } + object.addLevel( child, level.distance ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - var _context; + } - var AudioContext = { + return object; - getContext: function () { + } - if ( _context === undefined ) { +} ); - _context = new ( window.AudioContext || window.webkitAudioContext )(); +var TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + SphericalReflectionMapping: SphericalReflectionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping, + CubeUVRefractionMapping: CubeUVRefractionMapping +}; - } +var TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping +}; - return _context; +var TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipmapNearestFilter: NearestMipmapNearestFilter, + NearestMipmapLinearFilter: NearestMipmapLinearFilter, + LinearFilter: LinearFilter, + LinearMipmapNearestFilter: LinearMipmapNearestFilter, + LinearMipmapLinearFilter: LinearMipmapLinearFilter +}; - }, +/** + * @author thespite / http://clicktorelease.com/ + */ - setContext: function ( value ) { - _context = value; +function ImageBitmapLoader( manager ) { - } + if ( typeof createImageBitmap === 'undefined' ) { - }; + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); - /** - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ + } - function AudioLoader( manager ) { + if ( typeof fetch === 'undefined' ) { - Loader.call( this, manager ); + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); } - AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), { + Loader.call( this, manager ); - constructor: AudioLoader, + this.options = undefined; - load: function ( url, onLoad, onProgress, onError ) { +} - var loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); - loader.setPath( this.path ); - loader.load( url, function ( buffer ) { +ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - // Create a copy of the buffer. The `decodeAudioData` method - // detaches the buffer when complete, preventing reuse. - var bufferCopy = buffer.slice( 0 ); + constructor: ImageBitmapLoader, - var context = AudioContext.getContext(); - context.decodeAudioData( bufferCopy, function ( audioBuffer ) { + setOptions: function setOptions( options ) { - onLoad( audioBuffer ); + this.options = options; - } ); + return this; - }, onProgress, onError ); + }, - } + load: function ( url, onLoad, onProgress, onError ) { - } ); + if ( url === undefined ) url = ''; - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * Primary reference: - * https://graphics.stanford.edu/papers/envmap/envmap.pdf - * - * Secondary reference: - * https://www.ppsloan.org/publications/StupidSH36.pdf - */ + if ( this.path !== undefined ) url = this.path + url; - // 3-band SH defined by 9 coefficients + url = this.manager.resolveURL( url ); - function SphericalHarmonics3() { + var scope = this; - this.coefficients = []; + var cached = Cache.get( url ); - for ( var i = 0; i < 9; i ++ ) { + if ( cached !== undefined ) { - this.coefficients.push( new Vector3() ); + scope.manager.itemStart( url ); - } + setTimeout( function () { - } + if ( onLoad ) onLoad( cached ); - Object.assign( SphericalHarmonics3.prototype, { + scope.manager.itemEnd( url ); - isSphericalHarmonics3: true, + }, 0 ); - set: function ( coefficients ) { + return cached; - for ( var i = 0; i < 9; i ++ ) { + } - this.coefficients[ i ].copy( coefficients[ i ] ); + fetch( url ).then( function ( res ) { - } + return res.blob(); - return this; + } ).then( function ( blob ) { - }, + if ( scope.options === undefined ) { - zero: function () { + // Workaround for FireFox. It causes an error if you pass options. + return createImageBitmap( blob ); - for ( var i = 0; i < 9; i ++ ) { + } else { - this.coefficients[ i ].set( 0, 0, 0 ); + return createImageBitmap( blob, scope.options ); } - return this; + } ).then( function ( imageBitmap ) { - }, + Cache.add( url, imageBitmap ); - // get the radiance in the direction of the normal - // target is a Vector3 - getAt: function ( normal, target ) { + if ( onLoad ) onLoad( imageBitmap ); - // normal is assumed to be unit length + scope.manager.itemEnd( url ); - var x = normal.x, y = normal.y, z = normal.z; + } ).catch( function ( e ) { - var coeff = this.coefficients; + if ( onError ) onError( e ); - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); - // band 1 - target.addScale( coeff[ 1 ], 0.488603 * y ); - target.addScale( coeff[ 2 ], 0.488603 * z ); - target.addScale( coeff[ 3 ], 0.488603 * x ); + } ); - // band 2 - target.addScale( coeff[ 4 ], 1.092548 * ( x * y ) ); - target.addScale( coeff[ 5 ], 1.092548 * ( y * z ) ); - target.addScale( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); - target.addScale( coeff[ 7 ], 1.092548 * ( x * z ) ); - target.addScale( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); + scope.manager.itemStart( url ); - return target; + } - }, +} ); - // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal - // target is a Vector3 - // https://graphics.stanford.edu/papers/envmap/envmap.pdf - getIrradianceAt: function ( normal, target ) { +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * minimal class for proxing functions to Path. Replaces old "extractSubpaths()" + **/ - // normal is assumed to be unit length +function ShapePath() { - var x = normal.x, y = normal.y, z = normal.z; + this.type = 'ShapePath'; - var coeff = this.coefficients; + this.color = new Color(); - // band 0 - target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 + this.subPaths = []; + this.currentPath = null; - // band 1 - target.addScale( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 - target.addScale( coeff[ 2 ], 2.0 * 0.511664 * z ); - target.addScale( coeff[ 3 ], 2.0 * 0.511664 * x ); +} - // band 2 - target.addScale( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 - target.addScale( coeff[ 5 ], 2.0 * 0.429043 * y * z ); - target.addScale( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 - target.addScale( coeff[ 7 ], 2.0 * 0.429043 * x * z ); - target.addScale( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 +Object.assign( ShapePath.prototype, { - return target; + moveTo: function ( x, y ) { - }, + this.currentPath = new Path(); + this.subPaths.push( this.currentPath ); + this.currentPath.moveTo( x, y ); - add: function ( sh ) { + return this; - for ( var i = 0; i < 9; i ++ ) { + }, - this.coefficients[ i ].add( sh.coefficients[ i ] ); + lineTo: function ( x, y ) { - } + this.currentPath.lineTo( x, y ); - return this; + return this; - }, + }, + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - scale: function ( s ) { + this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); - for ( var i = 0; i < 9; i ++ ) { + return this; - this.coefficients[ i ].multiplyScalar( s ); + }, - } + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - return this; + this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); - }, + return this; - lerp: function ( sh, alpha ) { + }, - for ( var i = 0; i < 9; i ++ ) { + splineThru: function ( pts ) { - this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); + this.currentPath.splineThru( pts ); - } + return this; - return this; + }, - }, + toShapes: function ( isCCW, noHoles ) { - equals: function ( sh ) { + function toShapesNoHoles( inSubpaths ) { - for ( var i = 0; i < 9; i ++ ) { + var shapes = []; - if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { + for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { - return false; + var tmpPath = inSubpaths[ i ]; - } + var tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; - } + shapes.push( tmpShape ); - return true; + } - }, + return shapes; - copy: function ( sh ) { + } - return this.set( sh.coefficients ); + function isPointInsidePolygon( inPt, inPolygon ) { - }, + var polyLen = inPolygon.length; - clone: function () { + // inPt on polygon contour => immediate success or + // toggling of inside/outside at every single! intersection point of an edge + // with the horizontal line through inPt, left of inPt + // not counting lowerY endpoints of edges and whole edges on that line + var inside = false; + for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { - return new this.constructor().copy( this ); + var edgeLowPt = inPolygon[ p ]; + var edgeHighPt = inPolygon[ q ]; - }, + var edgeDx = edgeHighPt.x - edgeLowPt.x; + var edgeDy = edgeHighPt.y - edgeLowPt.y; - fromArray: function ( array, offset ) { + if ( Math.abs( edgeDy ) > Number.EPSILON ) { - if ( offset === undefined ) { offset = 0; } + // not parallel + if ( edgeDy < 0 ) { - var coefficients = this.coefficients; + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; - for ( var i = 0; i < 9; i ++ ) { + } - coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); + if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue; - } + if ( inPt.y === edgeLowPt.y ) { - return this; + if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ? + // continue; // no intersection or edgeLowPt => doesn't count !!! - }, + } else { - toArray: function ( array, offset ) { + var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); + if ( perpEdge === 0 ) return true; // inPt is on contour ? + if ( perpEdge < 0 ) continue; + inside = ! inside; // true intersection left of inPt - if ( array === undefined ) { array = []; } - if ( offset === undefined ) { offset = 0; } + } - var coefficients = this.coefficients; + } else { - for ( var i = 0; i < 9; i ++ ) { + // parallel or collinear + if ( inPt.y !== edgeLowPt.y ) continue; // parallel + // edge lies on the same horizontal line as inPt + if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || + ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour ! + // continue; - coefficients[ i ].toArray( array, offset + ( i * 3 ) ); + } } - return array; + return inside; } - } ); - - Object.assign( SphericalHarmonics3, { + var isClockWise = ShapeUtils.isClockWise; - // evaluate the basis functions - // shBasis is an Array[ 9 ] - getBasisAt: function ( normal, shBasis ) { + var subPaths = this.subPaths; + if ( subPaths.length === 0 ) return []; - // normal is assumed to be unit length + if ( noHoles === true ) return toShapesNoHoles( subPaths ); - var x = normal.x, y = normal.y, z = normal.z; - // band 0 - shBasis[ 0 ] = 0.282095; + var solid, tmpPath, tmpShape, shapes = []; - // band 1 - shBasis[ 1 ] = 0.488603 * y; - shBasis[ 2 ] = 0.488603 * z; - shBasis[ 3 ] = 0.488603 * x; + if ( subPaths.length === 1 ) { - // band 2 - shBasis[ 4 ] = 1.092548 * x * y; - shBasis[ 5 ] = 1.092548 * y * z; - shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); - shBasis[ 7 ] = 1.092548 * x * z; - shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); + tmpPath = subPaths[ 0 ]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push( tmpShape ); + return shapes; } - } ); + var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); + holesFirst = isCCW ? ! holesFirst : holesFirst; - /** - * @author WestLangley / http://github.com/WestLangley - * - * A LightProbe is a source of indirect-diffuse light - */ + // console.log("Holes first", holesFirst); - function LightProbe( sh, intensity ) { + var betterShapeHoles = []; + var newShapes = []; + var newShapeHoles = []; + var mainIdx = 0; + var tmpPoints; - Light.call( this, undefined, intensity ); + newShapes[ mainIdx ] = undefined; + newShapeHoles[ mainIdx ] = []; - this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3(); + for ( var i = 0, l = subPaths.length; i < l; i ++ ) { - } + tmpPath = subPaths[ i ]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise( tmpPoints ); + solid = isCCW ? ! solid : solid; - LightProbe.prototype = Object.assign( Object.create( Light.prototype ), { + if ( solid ) { - constructor: LightProbe, + if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++; - isLightProbe: true, + newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; + newShapes[ mainIdx ].s.curves = tmpPath.curves; - copy: function ( source ) { + if ( holesFirst ) mainIdx ++; + newShapeHoles[ mainIdx ] = []; - Light.prototype.copy.call( this, source ); + //console.log('cw', i); - this.sh.copy( source.sh ); - this.intensity = source.intensity; + } else { - return this; + newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); - }, + //console.log('ccw', i); + + } - toJSON: function ( meta ) { + } - var data = Light.prototype.toJSON.call( this, meta ); + // only Holes? -> probably all Shapes with wrong orientation + if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths ); - // data.sh = this.sh.toArray(); // todo - return data; + if ( newShapes.length > 1 ) { - } + var ambiguous = false; + var toChange = []; - } ); + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - /** - * @author WestLangley / http://github.com/WestLangley - */ + betterShapeHoles[ sIdx ] = []; - function HemisphereLightProbe( skyColor, groundColor, intensity ) { + } - LightProbe.call( this, undefined, intensity ); + for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { - var color1 = new Color().set( skyColor ); - var color2 = new Color().set( groundColor ); + var sho = newShapeHoles[ sIdx ]; - var sky = new Vector3( color1.r, color1.g, color1.b ); - var ground = new Vector3( color2.r, color2.g, color2.b ); + for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { - // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); - var c0 = Math.sqrt( Math.PI ); - var c1 = c0 * Math.sqrt( 0.75 ); + var ho = sho[ hIdx ]; + var hole_unassigned = true; - this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); - this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); + for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { - } + if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { - HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { + if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); + if ( hole_unassigned ) { - constructor: HemisphereLightProbe, + hole_unassigned = false; + betterShapeHoles[ s2Idx ].push( ho ); - isHemisphereLightProbe: true, + } else { - copy: function ( source ) { // modifying colors not currently supported + ambiguous = true; - LightProbe.prototype.copy.call( this, source ); + } - return this; + } - }, + } - toJSON: function ( meta ) { + if ( hole_unassigned ) { - var data = LightProbe.prototype.toJSON.call( this, meta ); + betterShapeHoles[ sIdx ].push( ho ); - // data.sh = this.sh.toArray(); // todo + } - return data; + } - } + } + // console.log("ambiguous: ", ambiguous); - } ); + if ( toChange.length > 0 ) { - /** - * @author WestLangley / http://github.com/WestLangley - */ + // console.log("to change: ", toChange); + if ( ! ambiguous ) newShapeHoles = betterShapeHoles; - function AmbientLightProbe( color, intensity ) { + } - LightProbe.call( this, undefined, intensity ); + } - var color1 = new Color().set( color ); + var tmpHoles; - // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); - this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); + for ( var i = 0, il = newShapes.length; i < il; i ++ ) { - } + tmpShape = newShapes[ i ].s; + shapes.push( tmpShape ); + tmpHoles = newShapeHoles[ i ]; - AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { + for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { - constructor: AmbientLightProbe, + tmpShape.holes.push( tmpHoles[ j ].h ); - isAmbientLightProbe: true, + } - copy: function ( source ) { // modifying color not currently supported + } - LightProbe.prototype.copy.call( this, source ); + //console.log("shape", shapes); - return this; + return shapes; - }, + } - toJSON: function ( meta ) { +} ); - var data = LightProbe.prototype.toJSON.call( this, meta ); +/** + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author mrdoob / http://mrdoob.com/ + */ - // data.sh = this.sh.toArray(); // todo - return data; +function Font( data ) { - } + this.type = 'Font'; - } ); + this.data = data; - var _eyeRight = new Matrix4(); - var _eyeLeft = new Matrix4(); +} - /** - * @author mrdoob / http://mrdoob.com/ - */ +Object.assign( Font.prototype, { - function StereoCamera() { + isFont: true, - this.type = 'StereoCamera'; + generateShapes: function ( text, size ) { - this.aspect = 1; + if ( size === undefined ) size = 100; - this.eyeSep = 0.064; + var shapes = []; + var paths = createPaths( text, size, this.data ); - this.cameraL = new PerspectiveCamera(); - this.cameraL.layers.enable( 1 ); - this.cameraL.matrixAutoUpdate = false; + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - this.cameraR = new PerspectiveCamera(); - this.cameraR.layers.enable( 2 ); - this.cameraR.matrixAutoUpdate = false; + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); - this._cache = { - focus: null, - fov: null, - aspect: null, - near: null, - far: null, - zoom: null, - eyeSep: null - }; + } + + return shapes; } - Object.assign( StereoCamera.prototype, { +} ); - update: function ( camera ) { +function createPaths( text, size, data ) { - var cache = this._cache; + var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988 + var scale = size / data.resolution; + var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; - var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || - cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || - cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + var paths = []; - if ( needsUpdate ) { + var offsetX = 0, offsetY = 0; - cache.focus = camera.focus; - cache.fov = camera.fov; - cache.aspect = camera.aspect * this.aspect; - cache.near = camera.near; - cache.far = camera.far; - cache.zoom = camera.zoom; - cache.eyeSep = this.eyeSep; + for ( var i = 0; i < chars.length; i ++ ) { - // Off-axis stereoscopic effect based on - // http://paulbourke.net/stereographics/stereorender/ + var char = chars[ i ]; - var projectionMatrix = camera.projectionMatrix.clone(); - var eyeSepHalf = cache.eyeSep / 2; - var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; - var ymax = ( cache.near * Math.tan( _Math.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; - var xmin, xmax; + if ( char === '\n' ) { - // translate xOffset + offsetX = 0; + offsetY -= line_height; - _eyeLeft.elements[ 12 ] = - eyeSepHalf; - _eyeRight.elements[ 12 ] = eyeSepHalf; + } else { - // for left eye + var ret = createPath( char, scale, offsetX, offsetY, data ); + offsetX += ret.offsetX; + paths.push( ret.path ); - xmin = - ymax * cache.aspect + eyeSepOnProjection; - xmax = ymax * cache.aspect + eyeSepOnProjection; + } - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + } - this.cameraL.projectionMatrix.copy( projectionMatrix ); + return paths; - // for right eye +} - xmin = - ymax * cache.aspect - eyeSepOnProjection; - xmax = ymax * cache.aspect - eyeSepOnProjection; +function createPath( char, scale, offsetX, offsetY, data ) { - projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); - projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); + var glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; - this.cameraR.projectionMatrix.copy( projectionMatrix ); + if ( ! glyph ) { - } + console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); - this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); - this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); + return; - } + } - } ); + var path = new ShapePath(); - /** - * @author alteredq / http://alteredqualia.com/ - */ + var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; - function Clock( autoStart ) { + if ( glyph.o ) { - this.autoStart = ( autoStart !== undefined ) ? autoStart : true; + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - this.startTime = 0; - this.oldTime = 0; - this.elapsedTime = 0; + for ( var i = 0, l = outline.length; i < l; ) { - this.running = false; + var action = outline[ i ++ ]; - } + switch ( action ) { - Object.assign( Clock.prototype, { + case 'm': // moveTo - start: function () { + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; - this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 + path.moveTo( x, y ); - this.oldTime = this.startTime; - this.elapsedTime = 0; - this.running = true; + break; - }, + case 'l': // lineTo - stop: function () { + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; - this.getElapsedTime(); - this.running = false; - this.autoStart = false; + path.lineTo( x, y ); - }, + break; - getElapsedTime: function () { + case 'q': // quadraticCurveTo - this.getDelta(); - return this.elapsedTime; + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; - }, + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - getDelta: function () { + break; - var diff = 0; + case 'b': // bezierCurveTo - if ( this.autoStart && ! this.running ) { + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; + cpx2 = outline[ i ++ ] * scale + offsetX; + cpy2 = outline[ i ++ ] * scale + offsetY; - this.start(); - return 0; + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - } + break; - if ( this.running ) { + } - var newTime = ( typeof performance === 'undefined' ? Date : performance ).now(); + } - diff = ( newTime - this.oldTime ) / 1000; - this.oldTime = newTime; + } - this.elapsedTime += diff; + return { offsetX: glyph.ha * scale, path: path }; - } +} - return diff; +/** + * @author mrdoob / http://mrdoob.com/ + */ - } +function FontLoader( manager ) { - } ); + Loader.call( this, manager ); - /** - * @author mrdoob / http://mrdoob.com/ - */ +} - var _position$2 = new Vector3(); - var _quaternion$3 = new Quaternion(); - var _scale$1 = new Vector3(); - var _orientation = new Vector3(); +FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - function AudioListener() { + constructor: FontLoader, - Object3D.call( this ); + load: function ( url, onLoad, onProgress, onError ) { - this.type = 'AudioListener'; + var scope = this; - this.context = AudioContext.getContext(); + var loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.load( url, function ( text ) { - this.gain = this.context.createGain(); - this.gain.connect( this.context.destination ); + var json; - this.filter = null; + try { - this.timeDelta = 0; + json = JSON.parse( text ); - // private + } catch ( e ) { - this._clock = new Clock(); + console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); + json = JSON.parse( text.substring( 65, text.length - 2 ) ); - } + } - AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { + var font = scope.parse( json ); - constructor: AudioListener, + if ( onLoad ) onLoad( font ); - getInput: function () { + }, onProgress, onError ); - return this.gain; + }, - }, + parse: function ( json ) { - removeFilter: function ( ) { + return new Font( json ); - if ( this.filter !== null ) { + } - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); - this.gain.connect( this.context.destination ); - this.filter = null; +} ); - } +/** + * @author mrdoob / http://mrdoob.com/ + */ - return this; +var _context; - }, +var AudioContext = { - getFilter: function () { + getContext: function () { - return this.filter; + if ( _context === undefined ) { - }, + _context = new ( window.AudioContext || window.webkitAudioContext )(); - setFilter: function ( value ) { + } - if ( this.filter !== null ) { + return _context; - this.gain.disconnect( this.filter ); - this.filter.disconnect( this.context.destination ); + }, - } else { + setContext: function ( value ) { - this.gain.disconnect( this.context.destination ); + _context = value; - } + } - this.filter = value; - this.gain.connect( this.filter ); - this.filter.connect( this.context.destination ); +}; - return this; +/** + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - }, +function AudioLoader( manager ) { - getMasterVolume: function () { + Loader.call( this, manager ); - return this.gain.gain.value; +} - }, +AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), { - setMasterVolume: function ( value ) { + constructor: AudioLoader, - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + load: function ( url, onLoad, onProgress, onError ) { - return this; + var scope = this; - }, + var loader = new FileLoader( scope.manager ); + loader.setResponseType( 'arraybuffer' ); + loader.setPath( scope.path ); + loader.load( url, function ( buffer ) { - updateMatrixWorld: function ( force ) { + try { - Object3D.prototype.updateMatrixWorld.call( this, force ); + // Create a copy of the buffer. The `decodeAudioData` method + // detaches the buffer when complete, preventing reuse. + var bufferCopy = buffer.slice( 0 ); - var listener = this.context.listener; - var up = this.up; + var context = AudioContext.getContext(); + context.decodeAudioData( bufferCopy, function ( audioBuffer ) { - this.timeDelta = this._clock.getDelta(); + onLoad( audioBuffer ); - this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 ); + } ); - _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 ); + } catch ( e ) { - if ( listener.positionX ) { + if ( onError ) { - // code path for Chrome (see #14393) + onError( e ); - var endTime = this.context.currentTime + this.timeDelta; + } else { - listener.positionX.linearRampToValueAtTime( _position$2.x, endTime ); - listener.positionY.linearRampToValueAtTime( _position$2.y, endTime ); - listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime ); - listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime ); - listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime ); - listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime ); - listener.upX.linearRampToValueAtTime( up.x, endTime ); - listener.upY.linearRampToValueAtTime( up.y, endTime ); - listener.upZ.linearRampToValueAtTime( up.z, endTime ); + console.error( e ); - } else { + } - listener.setPosition( _position$2.x, _position$2.y, _position$2.z ); - listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z ); + scope.manager.itemError( url ); } - } + }, onProgress, onError ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author Reece Aaron Lecrivain / http://reecenotes.com/ - */ +} ); - function Audio( listener ) { +/** + * @author WestLangley / http://github.com/WestLangley + */ - Object3D.call( this ); +function HemisphereLightProbe( skyColor, groundColor, intensity ) { - this.type = 'Audio'; + LightProbe.call( this, undefined, intensity ); - this.listener = listener; - this.context = listener.context; + var color1 = new Color().set( skyColor ); + var color2 = new Color().set( groundColor ); - this.gain = this.context.createGain(); - this.gain.connect( listener.getInput() ); + var sky = new Vector3( color1.r, color1.g, color1.b ); + var ground = new Vector3( color2.r, color2.g, color2.b ); - this.autoplay = false; + // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); + var c0 = Math.sqrt( Math.PI ); + var c1 = c0 * Math.sqrt( 0.75 ); - this.buffer = null; - this.detune = 0; - this.loop = false; - this.loopStart = 0; - this.loopEnd = 0; - this.offset = 0; - this.duration = undefined; - this.playbackRate = 1; - this.isPlaying = false; - this.hasPlaybackControl = true; - this.sourceType = 'empty'; + this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); + this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); - this._startedAt = 0; - this._pausedAt = 0; +} - this.filters = []; +HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { - } + constructor: HemisphereLightProbe, - Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { + isHemisphereLightProbe: true, - constructor: Audio, + copy: function ( source ) { // modifying colors not currently supported - getOutput: function () { + LightProbe.prototype.copy.call( this, source ); - return this.gain; + return this; - }, + }, - setNodeSource: function ( audioNode ) { + toJSON: function ( meta ) { - this.hasPlaybackControl = false; - this.sourceType = 'audioNode'; - this.source = audioNode; - this.connect(); + var data = LightProbe.prototype.toJSON.call( this, meta ); - return this; + // data.sh = this.sh.toArray(); // todo - }, + return data; - setMediaElementSource: function ( mediaElement ) { + } - this.hasPlaybackControl = false; - this.sourceType = 'mediaNode'; - this.source = this.context.createMediaElementSource( mediaElement ); - this.connect(); +} ); - return this; +/** + * @author WestLangley / http://github.com/WestLangley + */ - }, +function AmbientLightProbe( color, intensity ) { - setMediaStreamSource: function ( mediaStream ) { + LightProbe.call( this, undefined, intensity ); - this.hasPlaybackControl = false; - this.sourceType = 'mediaStreamNode'; - this.source = this.context.createMediaStreamSource( mediaStream ); - this.connect(); + var color1 = new Color().set( color ); - return this; + // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); + this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); - }, +} - setBuffer: function ( audioBuffer ) { +AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { - this.buffer = audioBuffer; - this.sourceType = 'buffer'; + constructor: AmbientLightProbe, - if ( this.autoplay ) { this.play(); } + isAmbientLightProbe: true, - return this; + copy: function ( source ) { // modifying color not currently supported - }, + LightProbe.prototype.copy.call( this, source ); - play: function ( delay ) { + return this; - if ( delay === undefined ) { delay = 0; } + }, - if ( this.isPlaying === true ) { + toJSON: function ( meta ) { - console.warn( 'THREE.Audio: Audio is already playing.' ); - return; + var data = LightProbe.prototype.toJSON.call( this, meta ); - } + // data.sh = this.sh.toArray(); // todo - if ( this.hasPlaybackControl === false ) { + return data; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + } - } +} ); - this._startedAt = this.context.currentTime + delay; +var _eyeRight = new Matrix4(); +var _eyeLeft = new Matrix4(); - var source = this.context.createBufferSource(); - source.buffer = this.buffer; - source.loop = this.loop; - source.loopStart = this.loopStart; - source.loopEnd = this.loopEnd; - source.onended = this.onEnded.bind( this ); - source.start( this._startedAt, this._pausedAt + this.offset, this.duration ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.isPlaying = true; +function StereoCamera() { - this.source = source; + this.type = 'StereoCamera'; - this.setDetune( this.detune ); - this.setPlaybackRate( this.playbackRate ); + this.aspect = 1; - return this.connect(); + this.eyeSep = 0.064; - }, + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable( 1 ); + this.cameraL.matrixAutoUpdate = false; - pause: function () { + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable( 2 ); + this.cameraR.matrixAutoUpdate = false; - if ( this.hasPlaybackControl === false ) { + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; +} - } +Object.assign( StereoCamera.prototype, { - if ( this.isPlaying === true ) { + update: function ( camera ) { - this._pausedAt = ( this.context.currentTime - this._startedAt ) * this.playbackRate; + var cache = this._cache; - this.source.stop(); - this.source.onended = null; + var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || + cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || + cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; - this.isPlaying = false; + if ( needsUpdate ) { - } + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; - return this; + // Off-axis stereoscopic effect based on + // http://paulbourke.net/stereographics/stereorender/ - }, + var projectionMatrix = camera.projectionMatrix.clone(); + var eyeSepHalf = cache.eyeSep / 2; + var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; + var xmin, xmax; - stop: function () { + // translate xOffset - if ( this.hasPlaybackControl === false ) { + _eyeLeft.elements[ 12 ] = - eyeSepHalf; + _eyeRight.elements[ 12 ] = eyeSepHalf; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + // for left eye - } + xmin = - ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; - this._pausedAt = 0; + projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - this.source.stop(); - this.source.onended = null; - this.isPlaying = false; + this.cameraL.projectionMatrix.copy( projectionMatrix ); - return this; + // for right eye - }, + xmin = - ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; - connect: function () { + projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); + projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); - if ( this.filters.length > 0 ) { + this.cameraR.projectionMatrix.copy( projectionMatrix ); - this.source.connect( this.filters[ 0 ] ); + } - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); + this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); - this.filters[ i - 1 ].connect( this.filters[ i ] ); + } - } +} ); - this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); +/** + * @author alteredq / http://alteredqualia.com/ + */ - } else { +function Clock( autoStart ) { - this.source.connect( this.getOutput() ); + this.autoStart = ( autoStart !== undefined ) ? autoStart : true; - } + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; - return this; + this.running = false; - }, +} - disconnect: function () { +Object.assign( Clock.prototype, { - if ( this.filters.length > 0 ) { + start: function () { - this.source.disconnect( this.filters[ 0 ] ); + this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 - for ( var i = 1, l = this.filters.length; i < l; i ++ ) { + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; - this.filters[ i - 1 ].disconnect( this.filters[ i ] ); + }, - } + stop: function () { - this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); + this.getElapsedTime(); + this.running = false; + this.autoStart = false; - } else { + }, - this.source.disconnect( this.getOutput() ); + getElapsedTime: function () { - } + this.getDelta(); + return this.elapsedTime; - return this; + }, - }, + getDelta: function () { - getFilters: function () { + var diff = 0; - return this.filters; + if ( this.autoStart && ! this.running ) { - }, + this.start(); + return 0; - setFilters: function ( value ) { + } - if ( ! value ) { value = []; } + if ( this.running ) { - if ( this.isPlaying === true ) { + var newTime = ( typeof performance === 'undefined' ? Date : performance ).now(); - this.disconnect(); - this.filters = value; - this.connect(); + diff = ( newTime - this.oldTime ) / 1000; + this.oldTime = newTime; - } else { + this.elapsedTime += diff; - this.filters = value; + } - } + return diff; - return this; + } - }, +} ); - setDetune: function ( value ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.detune = value; +var _position$2 = new Vector3(); +var _quaternion$3 = new Quaternion(); +var _scale$1 = new Vector3(); +var _orientation = new Vector3(); - if ( this.source.detune === undefined ) { return; } // only set detune when available +function AudioListener() { - if ( this.isPlaying === true ) { + Object3D.call( this ); - this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); + this.type = 'AudioListener'; - } + this.context = AudioContext.getContext(); - return this; + this.gain = this.context.createGain(); + this.gain.connect( this.context.destination ); - }, + this.filter = null; - getDetune: function () { + this.timeDelta = 0; - return this.detune; + // private - }, + this._clock = new Clock(); - getFilter: function () { +} - return this.getFilters()[ 0 ]; +AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { - }, + constructor: AudioListener, - setFilter: function ( filter ) { + getInput: function () { - return this.setFilters( filter ? [ filter ] : [] ); + return this.gain; - }, + }, - setPlaybackRate: function ( value ) { + removeFilter: function ( ) { - if ( this.hasPlaybackControl === false ) { + if ( this.filter !== null ) { - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); + this.gain.connect( this.context.destination ); + this.filter = null; - } + } - this.playbackRate = value; + return this; - if ( this.isPlaying === true ) { + }, - this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); + getFilter: function () { - } + return this.filter; - return this; + }, - }, + setFilter: function ( value ) { - getPlaybackRate: function () { + if ( this.filter !== null ) { - return this.playbackRate; + this.gain.disconnect( this.filter ); + this.filter.disconnect( this.context.destination ); - }, + } else { - onEnded: function () { + this.gain.disconnect( this.context.destination ); - this.isPlaying = false; + } - }, + this.filter = value; + this.gain.connect( this.filter ); + this.filter.connect( this.context.destination ); - getLoop: function () { + return this; - if ( this.hasPlaybackControl === false ) { + }, - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return false; + getMasterVolume: function () { - } + return this.gain.gain.value; - return this.loop; + }, - }, + setMasterVolume: function ( value ) { - setLoop: function ( value ) { + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - if ( this.hasPlaybackControl === false ) { + return this; - console.warn( 'THREE.Audio: this Audio has no playback control.' ); - return; + }, - } + updateMatrixWorld: function ( force ) { - this.loop = value; + Object3D.prototype.updateMatrixWorld.call( this, force ); - if ( this.isPlaying === true ) { + var listener = this.context.listener; + var up = this.up; - this.source.loop = this.loop; + this.timeDelta = this._clock.getDelta(); - } + this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 ); - return this; + _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 ); - }, + if ( listener.positionX ) { - setLoopStart: function ( value ) { + // code path for Chrome (see #14393) - this.loopStart = value; + var endTime = this.context.currentTime + this.timeDelta; - return this; + listener.positionX.linearRampToValueAtTime( _position$2.x, endTime ); + listener.positionY.linearRampToValueAtTime( _position$2.y, endTime ); + listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime ); + listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime ); + listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime ); + listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime ); + listener.upX.linearRampToValueAtTime( up.x, endTime ); + listener.upY.linearRampToValueAtTime( up.y, endTime ); + listener.upZ.linearRampToValueAtTime( up.z, endTime ); - }, + } else { - setLoopEnd: function ( value ) { + listener.setPosition( _position$2.x, _position$2.y, _position$2.z ); + listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z ); - this.loopEnd = value; + } - return this; + } - }, +} ); - getVolume: function () { +/** + * @author mrdoob / http://mrdoob.com/ + * @author Reece Aaron Lecrivain / http://reecenotes.com/ + */ - return this.gain.gain.value; +function Audio( listener ) { - }, + Object3D.call( this ); - setVolume: function ( value ) { + this.type = 'Audio'; - this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); + this.listener = listener; + this.context = listener.context; - return this; + this.gain = this.context.createGain(); + this.gain.connect( listener.getInput() ); - } + this.autoplay = false; - } ); + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.sourceType = 'empty'; - /** - * @author mrdoob / http://mrdoob.com/ - */ + this._startedAt = 0; + this._progress = 0; - var _position$3 = new Vector3(); - var _quaternion$4 = new Quaternion(); - var _scale$2 = new Vector3(); - var _orientation$1 = new Vector3(); + this.filters = []; - function PositionalAudio( listener ) { +} - Audio.call( this, listener ); +Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.panner = this.context.createPanner(); - this.panner.panningModel = 'HRTF'; - this.panner.connect( this.gain ); + constructor: Audio, - } + getOutput: function () { - PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { + return this.gain; - constructor: PositionalAudio, + }, - getOutput: function () { + setNodeSource: function ( audioNode ) { - return this.panner; + this.hasPlaybackControl = false; + this.sourceType = 'audioNode'; + this.source = audioNode; + this.connect(); - }, + return this; - getRefDistance: function () { + }, - return this.panner.refDistance; + setMediaElementSource: function ( mediaElement ) { - }, + this.hasPlaybackControl = false; + this.sourceType = 'mediaNode'; + this.source = this.context.createMediaElementSource( mediaElement ); + this.connect(); - setRefDistance: function ( value ) { + return this; - this.panner.refDistance = value; + }, - return this; + setMediaStreamSource: function ( mediaStream ) { - }, + this.hasPlaybackControl = false; + this.sourceType = 'mediaStreamNode'; + this.source = this.context.createMediaStreamSource( mediaStream ); + this.connect(); - getRolloffFactor: function () { + return this; - return this.panner.rolloffFactor; + }, - }, + setBuffer: function ( audioBuffer ) { - setRolloffFactor: function ( value ) { + this.buffer = audioBuffer; + this.sourceType = 'buffer'; - this.panner.rolloffFactor = value; + if ( this.autoplay ) this.play(); - return this; + return this; - }, + }, - getDistanceModel: function () { + play: function ( delay ) { - return this.panner.distanceModel; + if ( delay === undefined ) delay = 0; - }, + if ( this.isPlaying === true ) { - setDistanceModel: function ( value ) { + console.warn( 'THREE.Audio: Audio is already playing.' ); + return; - this.panner.distanceModel = value; + } - return this; + if ( this.hasPlaybackControl === false ) { - }, + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - getMaxDistance: function () { + } - return this.panner.maxDistance; + this._startedAt = this.context.currentTime + delay; - }, + var source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind( this ); + source.start( this._startedAt, this._progress + this.offset, this.duration ); - setMaxDistance: function ( value ) { + this.isPlaying = true; - this.panner.maxDistance = value; + this.source = source; - return this; + this.setDetune( this.detune ); + this.setPlaybackRate( this.playbackRate ); - }, + return this.connect(); - setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { + }, - this.panner.coneInnerAngle = coneInnerAngle; - this.panner.coneOuterAngle = coneOuterAngle; - this.panner.coneOuterGain = coneOuterGain; + pause: function () { - return this; + if ( this.hasPlaybackControl === false ) { - }, + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - updateMatrixWorld: function ( force ) { + } - Object3D.prototype.updateMatrixWorld.call( this, force ); + if ( this.isPlaying === true ) { - if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; } + // update current progress - this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 ); + this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate; - _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 ); + if ( this.loop === true ) { - var panner = this.panner; + // ensure _progress does not exceed duration with looped audios - if ( panner.positionX ) { + this._progress = this._progress % ( this.duration || this.buffer.duration ); - // code path for Chrome and Firefox (see #14393) + } - var endTime = this.context.currentTime + this.listener.timeDelta; + this.source.stop(); + this.source.onended = null; - panner.positionX.linearRampToValueAtTime( _position$3.x, endTime ); - panner.positionY.linearRampToValueAtTime( _position$3.y, endTime ); - panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime ); - panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime ); - panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime ); - panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime ); + this.isPlaying = false; - } else { + } - panner.setPosition( _position$3.x, _position$3.y, _position$3.z ); - panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z ); + return this; - } + }, - } + stop: function () { - } ); + if ( this.hasPlaybackControl === false ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - function AudioAnalyser( audio, fftSize ) { + } - this.analyser = audio.context.createAnalyser(); - this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; + this._progress = 0; - this.data = new Uint8Array( this.analyser.frequencyBinCount ); + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; - audio.getOutput().connect( this.analyser ); + return this; - } + }, - Object.assign( AudioAnalyser.prototype, { + connect: function () { - getFrequencyData: function () { + if ( this.filters.length > 0 ) { - this.analyser.getByteFrequencyData( this.data ); + this.source.connect( this.filters[ 0 ] ); - return this.data; + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - }, + this.filters[ i - 1 ].connect( this.filters[ i ] ); - getAverageFrequency: function () { + } - var value = 0, data = this.getFrequencyData(); + this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); - for ( var i = 0; i < data.length; i ++ ) { + } else { - value += data[ i ]; + this.source.connect( this.getOutput() ); - } + } - return value / data.length; + return this; - } + }, - } ); + disconnect: function () { - /** - * - * Buffered scene graph property that allows weighted accumulation. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + if ( this.filters.length > 0 ) { - function PropertyMixer( binding, typeName, valueSize ) { + this.source.disconnect( this.filters[ 0 ] ); - this.binding = binding; - this.valueSize = valueSize; + for ( var i = 1, l = this.filters.length; i < l; i ++ ) { - var bufferType = Float64Array, - mixFunction; + this.filters[ i - 1 ].disconnect( this.filters[ i ] ); - switch ( typeName ) { + } - case 'quaternion': - mixFunction = this._slerp; - break; + this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); - case 'string': - case 'bool': - bufferType = Array; - mixFunction = this._select; - break; + } else { - default: - mixFunction = this._lerp; + this.source.disconnect( this.getOutput() ); } - this.buffer = new bufferType( valueSize * 4 ); - // layout: [ incoming | accu0 | accu1 | orig ] - // - // interpolators can use .buffer as their .result - // the data then goes to 'incoming' - // - // 'accu0' and 'accu1' are used frame-interleaved for - // the cumulative result and are compared to detect - // changes - // - // 'orig' stores the original state of the property - - this._mixBufferRegion = mixFunction; + return this; - this.cumulativeWeight = 0; + }, - this.useCount = 0; - this.referenceCount = 0; + getFilters: function () { - } + return this.filters; - Object.assign( PropertyMixer.prototype, { + }, - // accumulate data in the 'incoming' region into 'accu' - accumulate: function ( accuIndex, weight ) { + setFilters: function ( value ) { - // note: happily accumulating nothing when weight = 0, the caller knows - // the weight and shouldn't have made the call in the first place + if ( ! value ) value = []; - var buffer = this.buffer, - stride = this.valueSize, - offset = accuIndex * stride + stride, + if ( this.isPlaying === true ) { - currentWeight = this.cumulativeWeight; + this.disconnect(); + this.filters = value; + this.connect(); - if ( currentWeight === 0 ) { + } else { - // accuN := incoming * weight + this.filters = value; - for ( var i = 0; i !== stride; ++ i ) { + } - buffer[ offset + i ] = buffer[ i ]; + return this; - } + }, - currentWeight = weight; + setDetune: function ( value ) { - } else { + this.detune = value; - // accuN := accuN + incoming * weight + if ( this.source.detune === undefined ) return; // only set detune when available - currentWeight += weight; - var mix = weight / currentWeight; - this._mixBufferRegion( buffer, offset, 0, mix, stride ); + if ( this.isPlaying === true ) { - } + this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); - this.cumulativeWeight = currentWeight; + } - }, + return this; - // apply the state of 'accu' to the binding when accus differ - apply: function ( accuIndex ) { + }, - var stride = this.valueSize, - buffer = this.buffer, - offset = accuIndex * stride + stride, + getDetune: function () { - weight = this.cumulativeWeight, + return this.detune; - binding = this.binding; + }, - this.cumulativeWeight = 0; + getFilter: function () { - if ( weight < 1 ) { + return this.getFilters()[ 0 ]; - // accuN := accuN + original * ( 1 - cumulativeWeight ) + }, - var originalValueOffset = stride * 3; + setFilter: function ( filter ) { - this._mixBufferRegion( - buffer, offset, originalValueOffset, 1 - weight, stride ); + return this.setFilters( filter ? [ filter ] : [] ); - } + }, - for ( var i = stride, e = stride + stride; i !== e; ++ i ) { + setPlaybackRate: function ( value ) { - if ( buffer[ i ] !== buffer[ i + stride ] ) { + if ( this.hasPlaybackControl === false ) { - // value has changed -> update scene graph + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - binding.setValue( buffer, offset ); - break; + } - } + this.playbackRate = value; - } + if ( this.isPlaying === true ) { - }, + this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); - // remember the state of the bound property and copy it to both accus - saveOriginalState: function () { + } - var binding = this.binding; + return this; - var buffer = this.buffer, - stride = this.valueSize, + }, - originalValueOffset = stride * 3; + getPlaybackRate: function () { - binding.getValue( buffer, originalValueOffset ); + return this.playbackRate; - // accu[0..1] := orig -- initially detect changes against the original - for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { + }, - buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; + onEnded: function () { - } + this.isPlaying = false; - this.cumulativeWeight = 0; + }, - }, + getLoop: function () { - // apply the state previously taken via 'saveOriginalState' to the binding - restoreOriginalState: function () { + if ( this.hasPlaybackControl === false ) { - var originalValueOffset = this.valueSize * 3; - this.binding.setValue( this.buffer, originalValueOffset ); + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return false; - }, + } + return this.loop; - // mix functions + }, - _select: function ( buffer, dstOffset, srcOffset, t, stride ) { + setLoop: function ( value ) { - if ( t >= 0.5 ) { + if ( this.hasPlaybackControl === false ) { - for ( var i = 0; i !== stride; ++ i ) { + console.warn( 'THREE.Audio: this Audio has no playback control.' ); + return; - buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; + } - } + this.loop = value; - } + if ( this.isPlaying === true ) { - }, + this.source.loop = this.loop; - _slerp: function ( buffer, dstOffset, srcOffset, t ) { + } - Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); + return this; - }, + }, - _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) { + setLoopStart: function ( value ) { - var s = 1 - t; + this.loopStart = value; - for ( var i = 0; i !== stride; ++ i ) { + return this; - var j = dstOffset + i; + }, - buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; + setLoopEnd: function ( value ) { - } + this.loopEnd = value; - } + return this; - } ); + }, - /** - * - * A reference to a real property in the scene graph. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + getVolume: function () { - // Characters [].:/ are reserved for track binding syntax. - var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; - var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); - - // Attempts to allow node names from any language. ES5's `\w` regexp matches - // only latin characters, and the unicode \p{L} is not yet supported. So - // instead, we exclude reserved characters and match everything else. - var _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; - var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; - - // Parent directories, delimited by '/' or ':'. Currently unused, but must - // be matched to parse the rest of the track name. - var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); - - // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. - var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); - - // Object on target node, and accessor. May not contain reserved - // characters. Accessor may contain any character except closing bracket. - var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); - - // Property and accessor. May not contain reserved characters. Accessor may - // contain any non-bracket characters. - var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); - - var _trackRe = new RegExp( '' - + '^' - + _directoryRe - + _nodeRe - + _objectRe - + _propertyRe - + '$' - ); + return this.gain.gain.value; - var _supportedObjectNames = [ 'material', 'materials', 'bones' ]; + }, - function Composite( targetGroup, path, optionalParsedPath ) { + setVolume: function ( value ) { - var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); + this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); - this._targetGroup = targetGroup; - this._bindings = targetGroup.subscribe_( path, parsedPath ); + return this; } - Object.assign( Composite.prototype, { +} ); - getValue: function ( array, offset ) { +/** + * @author mrdoob / http://mrdoob.com/ + */ - this.bind(); // bind all binding +var _position$3 = new Vector3(); +var _quaternion$4 = new Quaternion(); +var _scale$2 = new Vector3(); +var _orientation$1 = new Vector3(); - var firstValidIndex = this._targetGroup.nCachedObjects_, - binding = this._bindings[ firstValidIndex ]; +function PositionalAudio( listener ) { - // and only call .getValue on the first - if ( binding !== undefined ) { binding.getValue( array, offset ); } + Audio.call( this, listener ); - }, + this.panner = this.context.createPanner(); + this.panner.panningModel = 'HRTF'; + this.panner.connect( this.gain ); - setValue: function ( array, offset ) { +} - var bindings = this._bindings; +PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { - for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + constructor: PositionalAudio, - bindings[ i ].setValue( array, offset ); + getOutput: function () { - } + return this.panner; - }, + }, - bind: function () { + getRefDistance: function () { - var bindings = this._bindings; + return this.panner.refDistance; - for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + }, - bindings[ i ].bind(); + setRefDistance: function ( value ) { - } + this.panner.refDistance = value; - }, + return this; - unbind: function () { + }, - var bindings = this._bindings; + getRolloffFactor: function () { - for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { + return this.panner.rolloffFactor; - bindings[ i ].unbind(); + }, - } + setRolloffFactor: function ( value ) { - } + this.panner.rolloffFactor = value; - } ); + return this; + }, - function PropertyBinding( rootNode, path, parsedPath ) { + getDistanceModel: function () { - this.path = path; - this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); + return this.panner.distanceModel; - this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; + }, - this.rootNode = rootNode; + setDistanceModel: function ( value ) { - } + this.panner.distanceModel = value; - Object.assign( PropertyBinding, { + return this; - Composite: Composite, + }, - create: function ( root, path, parsedPath ) { + getMaxDistance: function () { - if ( ! ( root && root.isAnimationObjectGroup ) ) { + return this.panner.maxDistance; - return new PropertyBinding( root, path, parsedPath ); + }, - } else { + setMaxDistance: function ( value ) { - return new PropertyBinding.Composite( root, path, parsedPath ); + this.panner.maxDistance = value; - } + return this; - }, + }, - /** - * Replaces spaces with underscores and removes unsupported characters from - * node names, to ensure compatibility with parseTrackName(). - * - * @param {string} name Node name to be sanitized. - * @return {string} - */ - sanitizeNodeName: function ( name ) { + setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { - return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; - }, + return this; - parseTrackName: function ( trackName ) { + }, - var matches = _trackRe.exec( trackName ); + updateMatrixWorld: function ( force ) { - if ( ! matches ) { + Object3D.prototype.updateMatrixWorld.call( this, force ); - throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + if ( this.hasPlaybackControl === true && this.isPlaying === false ) return; - } + this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 ); - var results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 2 ], - objectName: matches[ 3 ], - objectIndex: matches[ 4 ], - propertyName: matches[ 5 ], // required - propertyIndex: matches[ 6 ] - }; + _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 ); - var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + var panner = this.panner; - if ( lastDot !== undefined && lastDot !== - 1 ) { + if ( panner.positionX ) { - var objectName = results.nodeName.substring( lastDot + 1 ); + // code path for Chrome and Firefox (see #14393) - // Object names must be checked against a whitelist. Otherwise, there - // is no way to parse 'foo.bar.baz': 'baz' must be a property, but - // 'bar' could be the objectName, or part of a nodeName (which can - // include '.' characters). - if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { + var endTime = this.context.currentTime + this.listener.timeDelta; - results.nodeName = results.nodeName.substring( 0, lastDot ); - results.objectName = objectName; + panner.positionX.linearRampToValueAtTime( _position$3.x, endTime ); + panner.positionY.linearRampToValueAtTime( _position$3.y, endTime ); + panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime ); + panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime ); + panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime ); + panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime ); - } + } else { - } + panner.setPosition( _position$3.x, _position$3.y, _position$3.z ); + panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z ); - if ( results.propertyName === null || results.propertyName.length === 0 ) { + } - throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + } - } +} ); - return results; +/** + * @author mrdoob / http://mrdoob.com/ + */ - }, +function AudioAnalyser( audio, fftSize ) { - findNode: function ( root, nodeName ) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; - if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { + this.data = new Uint8Array( this.analyser.frequencyBinCount ); - return root; + audio.getOutput().connect( this.analyser ); - } +} - // search into skeleton bones. - if ( root.skeleton ) { +Object.assign( AudioAnalyser.prototype, { - var bone = root.skeleton.getBoneByName( nodeName ); + getFrequencyData: function () { - if ( bone !== undefined ) { + this.analyser.getByteFrequencyData( this.data ); - return bone; + return this.data; - } + }, - } + getAverageFrequency: function () { - // search into node subtree. - if ( root.children ) { + var value = 0, data = this.getFrequencyData(); - var searchNodeSubtree = function ( children ) { + for ( var i = 0; i < data.length; i ++ ) { - for ( var i = 0; i < children.length; i ++ ) { + value += data[ i ]; - var childNode = children[ i ]; + } - if ( childNode.name === nodeName || childNode.uuid === nodeName ) { + return value / data.length; - return childNode; + } - } +} ); - var result = searchNodeSubtree( childNode.children ); +/** + * + * Buffered scene graph property that allows weighted accumulation. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - if ( result ) { return result; } +function PropertyMixer( binding, typeName, valueSize ) { - } + this.binding = binding; + this.valueSize = valueSize; - return null; + var mixFunction, + mixFunctionAdditive, + setIdentity; - }; + // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ] + // + // interpolators can use .buffer as their .result + // the data then goes to 'incoming' + // + // 'accu0' and 'accu1' are used frame-interleaved for + // the cumulative result and are compared to detect + // changes + // + // 'orig' stores the original state of the property + // + // 'add' is used for additive cumulative results + // + // 'work' is optional and is only present for quaternion types. It is used + // to store intermediate quaternion multiplication results - var subTreeNode = searchNodeSubtree( root.children ); + switch ( typeName ) { - if ( subTreeNode ) { + case 'quaternion': + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; - return subTreeNode; + this.buffer = new Float64Array( valueSize * 6 ); + this._workIndex = 5; + break; - } + case 'string': + case 'bool': + mixFunction = this._select; - } + // Use the regular mix function and for additive on these types, + // additive is not relevant for non-numeric types + mixFunctionAdditive = this._select; - return null; + setIdentity = this._setAdditiveIdentityOther; - } + this.buffer = new Array( valueSize * 5 ); + break; - } ); + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; - Object.assign( PropertyBinding.prototype, { // prototype, continued + this.buffer = new Float64Array( valueSize * 5 ); - // these are used to "bind" a nonexistent property - _getValue_unavailable: function () {}, - _setValue_unavailable: function () {}, + } - BindingType: { - Direct: 0, - EntireArray: 1, - ArrayElement: 2, - HasFromToArray: 3 - }, + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; - Versioning: { - None: 0, - NeedsUpdate: 1, - MatrixWorldNeedsUpdate: 2 - }, + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - GetterByBindingType: [ + this.useCount = 0; + this.referenceCount = 0; - function getValue_direct( buffer, offset ) { +} - buffer[ offset ] = this.node[ this.propertyName ]; +Object.assign( PropertyMixer.prototype, { - }, + // accumulate data in the 'incoming' region into 'accu' + accumulate: function ( accuIndex, weight ) { - function getValue_array( buffer, offset ) { + // note: happily accumulating nothing when weight = 0, the caller knows + // the weight and shouldn't have made the call in the first place - var source = this.resolvedProperty; + var buffer = this.buffer, + stride = this.valueSize, + offset = accuIndex * stride + stride, - for ( var i = 0, n = source.length; i !== n; ++ i ) { + currentWeight = this.cumulativeWeight; - buffer[ offset ++ ] = source[ i ]; + if ( currentWeight === 0 ) { - } + // accuN := incoming * weight - }, + for ( var i = 0; i !== stride; ++ i ) { - function getValue_arrayElement( buffer, offset ) { + buffer[ offset + i ] = buffer[ i ]; - buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; + } - }, + currentWeight = weight; - function getValue_toArray( buffer, offset ) { - - this.resolvedProperty.toArray( buffer, offset ); - - } - - ], + } else { - SetterByBindingTypeAndVersioning: [ + // accuN := accuN + incoming * weight - [ - // Direct + currentWeight += weight; + var mix = weight / currentWeight; + this._mixBufferRegion( buffer, offset, 0, mix, stride ); - function setValue_direct( buffer, offset ) { + } - this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.cumulativeWeight = currentWeight; - }, + }, - function setValue_direct_setNeedsUpdate( buffer, offset ) { + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive: function ( weight ) { - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + var buffer = this.buffer, + stride = this.valueSize, + offset = stride * this._addIndex; - }, + if ( this.cumulativeWeightAdditive === 0 ) { - function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { + // add = identity - this.targetObject[ this.propertyName ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + this._setIdentity(); - } + } - ], [ + // add := add + incoming * weight - // EntireArray + this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride ); + this.cumulativeWeightAdditive += weight; - function setValue_array( buffer, offset ) { + }, - var dest = this.resolvedProperty; + // apply the state of 'accu' to the binding when accus differ + apply: function ( accuIndex ) { - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + var stride = this.valueSize, + buffer = this.buffer, + offset = accuIndex * stride + stride, - dest[ i ] = buffer[ offset ++ ]; + weight = this.cumulativeWeight, + weightAdditive = this.cumulativeWeightAdditive, - } + binding = this.binding; - }, + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - function setValue_array_setNeedsUpdate( buffer, offset ) { + if ( weight < 1 ) { - var dest = this.resolvedProperty; + // accuN := accuN + original * ( 1 - cumulativeWeight ) - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + var originalValueOffset = stride * this._origIndex; - dest[ i ] = buffer[ offset ++ ]; + this._mixBufferRegion( + buffer, offset, originalValueOffset, 1 - weight, stride ); - } + } - this.targetObject.needsUpdate = true; + if ( weightAdditive > 0 ) { - }, + // accuN := accuN + additive accuN - function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { + this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride ); - var dest = this.resolvedProperty; + } - for ( var i = 0, n = dest.length; i !== n; ++ i ) { + for ( var i = stride, e = stride + stride; i !== e; ++ i ) { - dest[ i ] = buffer[ offset ++ ]; + if ( buffer[ i ] !== buffer[ i + stride ] ) { - } + // value has changed -> update scene graph - this.targetObject.matrixWorldNeedsUpdate = true; + binding.setValue( buffer, offset ); + break; - } + } - ], [ + } - // ArrayElement + }, - function setValue_arrayElement( buffer, offset ) { + // remember the state of the bound property and copy it to both accus + saveOriginalState: function () { - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + var binding = this.binding; - }, + var buffer = this.buffer, + stride = this.valueSize, - function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { + originalValueOffset = stride * this._origIndex; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.needsUpdate = true; + binding.getValue( buffer, originalValueOffset ); - }, + // accu[0..1] := orig -- initially detect changes against the original + for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { - function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { + buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; - this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - this.targetObject.matrixWorldNeedsUpdate = true; + } - } + // Add to identity for additive + this._setIdentity(); - ], [ + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; - // HasToFromArray + }, - function setValue_fromArray( buffer, offset ) { + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState: function () { - this.resolvedProperty.fromArray( buffer, offset ); + var originalValueOffset = this.valueSize * 3; + this.binding.setValue( this.buffer, originalValueOffset ); - }, + }, - function setValue_fromArray_setNeedsUpdate( buffer, offset ) { + _setAdditiveIdentityNumeric: function () { - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.needsUpdate = true; + var startIndex = this._addIndex * this.valueSize; + var endIndex = startIndex + this.valueSize; - }, + for ( var i = startIndex; i < endIndex; i ++ ) { - function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { + this.buffer[ i ] = 0; - this.resolvedProperty.fromArray( buffer, offset ); - this.targetObject.matrixWorldNeedsUpdate = true; + } - } + }, - ] + _setAdditiveIdentityQuaternion: function () { - ], + this._setAdditiveIdentityNumeric(); + this.buffer[ this._addIndex * 4 + 3 ] = 1; - getValue: function getValue_unbound( targetArray, offset ) { + }, - this.bind(); - this.getValue( targetArray, offset ); + _setAdditiveIdentityOther: function () { - // Note: This class uses a State pattern on a per-method basis: - // 'bind' sets 'this.getValue' / 'setValue' and shadows the - // prototype version of these methods with one that represents - // the bound state. When the property is not found, the methods - // become no-ops. + var startIndex = this._origIndex * this.valueSize; + var targetIndex = this._addIndex * this.valueSize; - }, + for ( var i = 0; i < this.valueSize; i ++ ) { - setValue: function getValue_unbound( sourceArray, offset ) { + this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ]; - this.bind(); - this.setValue( sourceArray, offset ); + } - }, + }, - // create getter / setter pair for a property in the scene graph - bind: function () { - var targetObject = this.node, - parsedPath = this.parsedPath, + // mix functions - objectName = parsedPath.objectName, - propertyName = parsedPath.propertyName, - propertyIndex = parsedPath.propertyIndex; + _select: function ( buffer, dstOffset, srcOffset, t, stride ) { - if ( ! targetObject ) { + if ( t >= 0.5 ) { - targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; + for ( var i = 0; i !== stride; ++ i ) { - this.node = targetObject; + buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; } - // set fail state so we can just 'return' on error - this.getValue = this._getValue_unavailable; - this.setValue = this._setValue_unavailable; + } - // ensure there is a value node - if ( ! targetObject ) { + }, - console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); - return; + _slerp: function ( buffer, dstOffset, srcOffset, t ) { - } + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); - if ( objectName ) { + }, - var objectIndex = parsedPath.objectIndex; + _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) { - // special cases were we need to reach deeper into the hierarchy to get the face materials.... - switch ( objectName ) { + var workOffset = this._workIndex * stride; - case 'materials': + // Store result in intermediate buffer offset + Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset ); - if ( ! targetObject.material ) { + // Slerp to the intermediate result + Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t ); - console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); - return; + }, - } + _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) { - if ( ! targetObject.material.materials ) { + var s = 1 - t; - console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); - return; + for ( var i = 0; i !== stride; ++ i ) { - } + var j = dstOffset + i; - targetObject = targetObject.material.materials; + buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; - break; + } - case 'bones': + }, - if ( ! targetObject.skeleton ) { + _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) { - console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); - return; + for ( var i = 0; i !== stride; ++ i ) { - } + var j = dstOffset + i; - // potential future optimization: skip this if propertyIndex is already an integer - // and convert the integer string to a true integer. + buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t; - targetObject = targetObject.skeleton.bones; + } - // support resolving morphTarget names into indices. - for ( var i = 0; i < targetObject.length; i ++ ) { + } - if ( targetObject[ i ].name === objectIndex ) { +} ); - objectIndex = i; - break; +/** + * + * A reference to a real property in the scene graph. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } +// Characters [].:/ are reserved for track binding syntax. +var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; +var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); - } +// Attempts to allow node names from any language. ES5's `\w` regexp matches +// only latin characters, and the unicode \p{L} is not yet supported. So +// instead, we exclude reserved characters and match everything else. +var _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; +var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; - break; +// Parent directories, delimited by '/' or ':'. Currently unused, but must +// be matched to parse the rest of the track name. +var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); - default: +// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. +var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); - if ( targetObject[ objectName ] === undefined ) { +// Object on target node, and accessor. May not contain reserved +// characters. Accessor may contain any character except closing bracket. +var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); - console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); - return; +// Property and accessor. May not contain reserved characters. Accessor may +// contain any non-bracket characters. +var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); - } +var _trackRe = new RegExp( '' + + '^' + + _directoryRe + + _nodeRe + + _objectRe + + _propertyRe + + '$' +); - targetObject = targetObject[ objectName ]; +var _supportedObjectNames = [ 'material', 'materials', 'bones' ]; - } +function Composite( targetGroup, path, optionalParsedPath ) { + var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); - if ( objectIndex !== undefined ) { + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_( path, parsedPath ); - if ( targetObject[ objectIndex ] === undefined ) { +} - console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); - return; +Object.assign( Composite.prototype, { - } + getValue: function ( array, offset ) { - targetObject = targetObject[ objectIndex ]; + this.bind(); // bind all binding - } + var firstValidIndex = this._targetGroup.nCachedObjects_, + binding = this._bindings[ firstValidIndex ]; - } + // and only call .getValue on the first + if ( binding !== undefined ) binding.getValue( array, offset ); - // resolve property - var nodeProperty = targetObject[ propertyName ]; + }, - if ( nodeProperty === undefined ) { + setValue: function ( array, offset ) { - var nodeName = parsedPath.nodeName; + var bindings = this._bindings; - console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + - '.' + propertyName + ' but it wasn\'t found.', targetObject ); - return; + for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - } + bindings[ i ].setValue( array, offset ); - // determine versioning scheme - var versioning = this.Versioning.None; + } - this.targetObject = targetObject; + }, - if ( targetObject.needsUpdate !== undefined ) { // material + bind: function () { - versioning = this.Versioning.NeedsUpdate; + var bindings = this._bindings; - } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform + for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - versioning = this.Versioning.MatrixWorldNeedsUpdate; + bindings[ i ].bind(); - } + } - // determine how the property gets bound - var bindingType = this.BindingType.Direct; + }, - if ( propertyIndex !== undefined ) { + unbind: function () { - // access a sub element of the property array (only primitives are supported right now) + var bindings = this._bindings; - if ( propertyName === "morphTargetInfluences" ) { + for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { - // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. + bindings[ i ].unbind(); - // support resolving morphTarget names into indices. - if ( ! targetObject.geometry ) { + } - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); - return; + } - } +} ); - if ( targetObject.geometry.isBufferGeometry ) { - if ( ! targetObject.geometry.morphAttributes ) { +function PropertyBinding( rootNode, path, parsedPath ) { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); - return; + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); - } + this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; - for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) { + this.rootNode = rootNode; - if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) { +} - propertyIndex = i; - break; +Object.assign( PropertyBinding, { - } + Composite: Composite, - } + create: function ( root, path, parsedPath ) { + if ( ! ( root && root.isAnimationObjectGroup ) ) { - } else { + return new PropertyBinding( root, path, parsedPath ); - if ( ! targetObject.geometry.morphTargets ) { + } else { - console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this ); - return; + return new PropertyBinding.Composite( root, path, parsedPath ); - } + } - for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { + }, - if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + sanitizeNodeName: function ( name ) { - propertyIndex = i; - break; + return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); - } + }, - } + parseTrackName: function ( trackName ) { - } + var matches = _trackRe.exec( trackName ); - } + if ( ! matches ) { - bindingType = this.BindingType.ArrayElement; + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); - this.resolvedProperty = nodeProperty; - this.propertyIndex = propertyIndex; + } - } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { + var results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; - // must use copy for Object3D.Euler/Quaternion + var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); - bindingType = this.BindingType.HasFromToArray; + if ( lastDot !== undefined && lastDot !== - 1 ) { - this.resolvedProperty = nodeProperty; + var objectName = results.nodeName.substring( lastDot + 1 ); - } else if ( Array.isArray( nodeProperty ) ) { + // Object names must be checked against a whitelist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { - bindingType = this.BindingType.EntireArray; + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; - this.resolvedProperty = nodeProperty; + } - } else { + } - this.propertyName = propertyName; + if ( results.propertyName === null || results.propertyName.length === 0 ) { - } + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); - // select getter / setter - this.getValue = this.GetterByBindingType[ bindingType ]; - this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; + } - }, + return results; - unbind: function () { + }, - this.node = null; + findNode: function ( root, nodeName ) { - // back to the prototype version of getValue / setValue - // note: avoiding to mutate the shape of 'this' via 'delete' - this.getValue = this._getValue_unbound; - this.setValue = this._setValue_unbound; + if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { - } + return root; - } ); + } - //!\ DECLARE ALIAS AFTER assign prototype ! - Object.assign( PropertyBinding.prototype, { + // search into skeleton bones. + if ( root.skeleton ) { - // initial state of these methods that calls 'bind' - _getValue_unbound: PropertyBinding.prototype.getValue, - _setValue_unbound: PropertyBinding.prototype.setValue, + var bone = root.skeleton.getBoneByName( nodeName ); - } ); + if ( bone !== undefined ) { - /** - * - * A group of objects that receives a shared animation state. - * - * Usage: - * - * - Add objects you would otherwise pass as 'root' to the - * constructor or the .clipAction method of AnimationMixer. - * - * - Instead pass this object as 'root'. - * - * - You can also add and remove objects later when the mixer - * is running. - * - * Note: - * - * Objects of this class appear as one object to the mixer, - * so cache control of the individual objects must be done - * on the group. - * - * Limitation: - * - * - The animated properties must be compatible among the - * all objects in the group. - * - * - A single property can either be controlled through a - * target group or directly, but not both. - * - * @author tschw - */ + return bone; - function AnimationObjectGroup() { + } - this.uuid = _Math.generateUUID(); + } - // cached objects followed by the active ones - this._objects = Array.prototype.slice.call( arguments ); + // search into node subtree. + if ( root.children ) { - this.nCachedObjects_ = 0; // threshold - // note: read by PropertyBinding.Composite + var searchNodeSubtree = function ( children ) { - var indices = {}; - this._indicesByUUID = indices; // for bookkeeping + for ( var i = 0; i < children.length; i ++ ) { - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + var childNode = children[ i ]; - indices[ arguments[ i ].uuid ] = i; + if ( childNode.name === nodeName || childNode.uuid === nodeName ) { - } + return childNode; - this._paths = []; // inside: string - this._parsedPaths = []; // inside: { we don't care, here } - this._bindings = []; // inside: Array< PropertyBinding > - this._bindingsIndicesByPath = {}; // inside: indices in these arrays + } - var scope = this; + var result = searchNodeSubtree( childNode.children ); - this.stats = { + if ( result ) return result; - objects: { - get total() { + } - return scope._objects.length; + return null; - }, - get inUse() { + }; - return this.total - scope.nCachedObjects_; + var subTreeNode = searchNodeSubtree( root.children ); - } - }, - get bindingsPerObject() { + if ( subTreeNode ) { - return scope._bindings.length; + return subTreeNode; } - }; + } + + return null; } - Object.assign( AnimationObjectGroup.prototype, { +} ); - isAnimationObjectGroup: true, +Object.assign( PropertyBinding.prototype, { // prototype, continued - add: function () { + // these are used to "bind" a nonexistent property + _getValue_unavailable: function () {}, + _setValue_unavailable: function () {}, - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - nBindings = bindings.length, - knownObject = undefined; + BindingType: { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }, - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + Versioning: { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }, - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + GetterByBindingType: [ - if ( index === undefined ) { + function getValue_direct( buffer, offset ) { - // unknown object -> add it to the ACTIVE region + buffer[ offset ] = this.node[ this.propertyName ]; - index = nObjects ++; - indicesByUUID[ uuid ] = index; - objects.push( object ); + }, - // accounting is done, now do the same for all bindings + function getValue_array( buffer, offset ) { - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + var source = this.resolvedProperty; - bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); + for ( var i = 0, n = source.length; i !== n; ++ i ) { - } + buffer[ offset ++ ] = source[ i ]; - } else if ( index < nCachedObjects ) { + } - knownObject = objects[ index ]; + }, - // move existing object to the ACTIVE region + function getValue_arrayElement( buffer, offset ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ]; + buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + }, - indicesByUUID[ uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = object; + function getValue_toArray( buffer, offset ) { - // accounting is done, now do the same for all bindings + this.resolvedProperty.toArray( buffer, offset ); - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - binding = bindingsForPath[ index ]; + ], - bindingsForPath[ index ] = lastCached; + SetterByBindingTypeAndVersioning: [ - if ( binding === undefined ) { + [ + // Direct - // since we do not bother to create new bindings - // for objects that are cached, the binding may - // or may not exist + function setValue_direct( buffer, offset ) { - binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); + this.targetObject[ this.propertyName ] = buffer[ offset ]; - } + }, - bindingsForPath[ firstActiveIndex ] = binding; + function setValue_direct_setNeedsUpdate( buffer, offset ) { - } + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - } else if ( objects[ index ] !== knownObject ) { + }, - console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + - 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); + function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - } // else the object is already where we want it to be + this.targetObject[ this.propertyName ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - } // for arguments + } - this.nCachedObjects_ = nCachedObjects; + ], [ - }, + // EntireArray - remove: function () { + function setValue_array( buffer, offset ) { - var objects = this._objects, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + var dest = this.resolvedProperty; - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + dest[ i ] = buffer[ offset ++ ]; - if ( index !== undefined && index >= nCachedObjects ) { + } - // move existing object into the CACHED region + }, - var lastCachedIndex = nCachedObjects ++, - firstActiveObject = objects[ lastCachedIndex ]; + function setValue_array_setNeedsUpdate( buffer, offset ) { - indicesByUUID[ firstActiveObject.uuid ] = index; - objects[ index ] = firstActiveObject; + var dest = this.resolvedProperty; - indicesByUUID[ uuid ] = lastCachedIndex; - objects[ lastCachedIndex ] = object; + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - // accounting is done, now do the same for all bindings + dest[ i ] = buffer[ offset ++ ]; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } - var bindingsForPath = bindings[ j ], - firstActive = bindingsForPath[ lastCachedIndex ], - binding = bindingsForPath[ index ]; + this.targetObject.needsUpdate = true; - bindingsForPath[ index ] = firstActive; - bindingsForPath[ lastCachedIndex ] = binding; + }, - } + function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { - } + var dest = this.resolvedProperty; - } // for arguments + for ( var i = 0, n = dest.length; i !== n; ++ i ) { - this.nCachedObjects_ = nCachedObjects; + dest[ i ] = buffer[ offset ++ ]; - }, + } - // remove & forget - uncache: function () { + this.targetObject.matrixWorldNeedsUpdate = true; - var objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - indicesByUUID = this._indicesByUUID, - bindings = this._bindings, - nBindings = bindings.length; + } - for ( var i = 0, n = arguments.length; i !== n; ++ i ) { + ], [ - var object = arguments[ i ], - uuid = object.uuid, - index = indicesByUUID[ uuid ]; + // ArrayElement - if ( index !== undefined ) { + function setValue_arrayElement( buffer, offset ) { - delete indicesByUUID[ uuid ]; + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; - if ( index < nCachedObjects ) { + }, - // object is cached, shrink the CACHED region + function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { - var firstActiveIndex = -- nCachedObjects, - lastCachedObject = objects[ firstActiveIndex ], - lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.needsUpdate = true; - // last cached object takes this object's place - indicesByUUID[ lastCachedObject.uuid ] = index; - objects[ index ] = lastCachedObject; + }, - // last object goes to the activated slot and pop - indicesByUUID[ lastObject.uuid ] = firstActiveIndex; - objects[ firstActiveIndex ] = lastObject; - objects.pop(); + function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { - // accounting is done, now do the same for all bindings + this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; + this.targetObject.matrixWorldNeedsUpdate = true; - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + } - var bindingsForPath = bindings[ j ], - lastCached = bindingsForPath[ firstActiveIndex ], - last = bindingsForPath[ lastIndex ]; + ], [ - bindingsForPath[ index ] = lastCached; - bindingsForPath[ firstActiveIndex ] = last; - bindingsForPath.pop(); + // HasToFromArray - } + function setValue_fromArray( buffer, offset ) { - } else { + this.resolvedProperty.fromArray( buffer, offset ); - // object is active, just swap with the last and pop + }, - var lastIndex = -- nObjects, - lastObject = objects[ lastIndex ]; + function setValue_fromArray_setNeedsUpdate( buffer, offset ) { - indicesByUUID[ lastObject.uuid ] = index; - objects[ index ] = lastObject; - objects.pop(); + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.needsUpdate = true; - // accounting is done, now do the same for all bindings + }, - for ( var j = 0, m = nBindings; j !== m; ++ j ) { + function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { - var bindingsForPath = bindings[ j ]; + this.resolvedProperty.fromArray( buffer, offset ); + this.targetObject.matrixWorldNeedsUpdate = true; - bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; - bindingsForPath.pop(); + } - } + ] - } // cached or active + ], - } // if object is known + getValue: function getValue_unbound( targetArray, offset ) { - } // for arguments + this.bind(); + this.getValue( targetArray, offset ); - this.nCachedObjects_ = nCachedObjects; + // Note: This class uses a State pattern on a per-method basis: + // 'bind' sets 'this.getValue' / 'setValue' and shadows the + // prototype version of these methods with one that represents + // the bound state. When the property is not found, the methods + // become no-ops. - }, + }, - // Internal interface used by befriended PropertyBinding.Composite: + setValue: function getValue_unbound( sourceArray, offset ) { - subscribe_: function ( path, parsedPath ) { + this.bind(); + this.setValue( sourceArray, offset ); - // returns an array of bindings for the given path that is changed - // according to the contained objects in the group + }, - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ], - bindings = this._bindings; + // create getter / setter pair for a property in the scene graph + bind: function () { - if ( index !== undefined ) { return bindings[ index ]; } + var targetObject = this.node, + parsedPath = this.parsedPath, - var paths = this._paths, - parsedPaths = this._parsedPaths, - objects = this._objects, - nObjects = objects.length, - nCachedObjects = this.nCachedObjects_, - bindingsForPath = new Array( nObjects ); + objectName = parsedPath.objectName, + propertyName = parsedPath.propertyName, + propertyIndex = parsedPath.propertyIndex; - index = bindings.length; + if ( ! targetObject ) { - indicesByPath[ path ] = index; + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; - paths.push( path ); - parsedPaths.push( parsedPath ); - bindings.push( bindingsForPath ); + this.node = targetObject; - for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) { + } - var object = objects[ i ]; - bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); + // set fail state so we can just 'return' on error + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; - } + // ensure there is a value node + if ( ! targetObject ) { - return bindingsForPath; + console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); + return; - }, + } - unsubscribe_: function ( path ) { + if ( objectName ) { - // tells the group to forget about a property path and no longer - // update the array previously obtained with 'subscribe_' + var objectIndex = parsedPath.objectIndex; - var indicesByPath = this._bindingsIndicesByPath, - index = indicesByPath[ path ]; + // special cases were we need to reach deeper into the hierarchy to get the face materials.... + switch ( objectName ) { - if ( index !== undefined ) { + case 'materials': - var paths = this._paths, - parsedPaths = this._parsedPaths, - bindings = this._bindings, - lastBindingsIndex = bindings.length - 1, - lastBindings = bindings[ lastBindingsIndex ], - lastBindingsPath = path[ lastBindingsIndex ]; + if ( ! targetObject.material ) { - indicesByPath[ lastBindingsPath ] = index; + console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); + return; - bindings[ index ] = lastBindings; - bindings.pop(); + } - parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; - parsedPaths.pop(); + if ( ! targetObject.material.materials ) { - paths[ index ] = paths[ lastBindingsIndex ]; - paths.pop(); + console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); + return; - } + } - } + targetObject = targetObject.material.materials; - } ); + break; - /** - * - * Action provided by AnimationMixer for scheduling clip playback on specific - * objects. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - * - */ + case 'bones': - function AnimationAction( mixer, clip, localRoot ) { + if ( ! targetObject.skeleton ) { - this._mixer = mixer; - this._clip = clip; - this._localRoot = localRoot || null; + console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); + return; - var tracks = clip.tracks, - nTracks = tracks.length, - interpolants = new Array( nTracks ); + } - var interpolantSettings = { - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding - }; + // potential future optimization: skip this if propertyIndex is already an integer + // and convert the integer string to a true integer. - for ( var i = 0; i !== nTracks; ++ i ) { + targetObject = targetObject.skeleton.bones; - var interpolant = tracks[ i ].createInterpolant( null ); - interpolants[ i ] = interpolant; - interpolant.settings = interpolantSettings; + // support resolving morphTarget names into indices. + for ( var i = 0; i < targetObject.length; i ++ ) { - } + if ( targetObject[ i ].name === objectIndex ) { - this._interpolantSettings = interpolantSettings; + objectIndex = i; + break; - this._interpolants = interpolants; // bound by the mixer + } - // inside: PropertyMixer (managed by the mixer) - this._propertyBindings = new Array( nTracks ); + } - this._cacheIndex = null; // for the memory manager - this._byClipCacheIndex = null; // for the memory manager + break; - this._timeScaleInterpolant = null; - this._weightInterpolant = null; + default: - this.loop = LoopRepeat; - this._loopCount = - 1; + if ( targetObject[ objectName ] === undefined ) { - // global mixer time when the action is to be started - // it's set back to 'null' upon start of the action - this._startTime = null; + console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); + return; - // scaled local time of the action - // gets clamped or wrapped to 0..clip.duration according to loop - this.time = 0; + } - this.timeScale = 1; - this._effectiveTimeScale = 1; + targetObject = targetObject[ objectName ]; - this.weight = 1; - this._effectiveWeight = 1; + } - this.repetitions = Infinity; // no. of repetitions when looping - this.paused = false; // true -> zero effective time scale - this.enabled = true; // false -> zero effective weight + if ( objectIndex !== undefined ) { - this.clampWhenFinished = false;// keep feeding the last frame? + if ( targetObject[ objectIndex ] === undefined ) { - this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate - this.zeroSlopeAtEnd = true;// clips for start, loop and end + console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); + return; - } + } - Object.assign( AnimationAction.prototype, { + targetObject = targetObject[ objectIndex ]; - // State & Scheduling + } - play: function () { + } - this._mixer._activateAction( this ); + // resolve property + var nodeProperty = targetObject[ propertyName ]; - return this; + if ( nodeProperty === undefined ) { - }, + var nodeName = parsedPath.nodeName; - stop: function () { + console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + + '.' + propertyName + ' but it wasn\'t found.', targetObject ); + return; - this._mixer._deactivateAction( this ); + } - return this.reset(); + // determine versioning scheme + var versioning = this.Versioning.None; - }, + this.targetObject = targetObject; - reset: function () { + if ( targetObject.needsUpdate !== undefined ) { // material - this.paused = false; - this.enabled = true; + versioning = this.Versioning.NeedsUpdate; - this.time = 0; // restart clip - this._loopCount = - 1;// forget previous loops - this._startTime = null;// forget scheduling + } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform - return this.stopFading().stopWarping(); + versioning = this.Versioning.MatrixWorldNeedsUpdate; - }, + } - isRunning: function () { + // determine how the property gets bound + var bindingType = this.BindingType.Direct; - return this.enabled && ! this.paused && this.timeScale !== 0 && - this._startTime === null && this._mixer._isActiveAction( this ); + if ( propertyIndex !== undefined ) { - }, + // access a sub element of the property array (only primitives are supported right now) - // return true when play has been called - isScheduled: function () { + if ( propertyName === "morphTargetInfluences" ) { - return this._mixer._isActiveAction( this ); + // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. - }, + // support resolving morphTarget names into indices. + if ( ! targetObject.geometry ) { - startAt: function ( time ) { + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); + return; - this._startTime = time; + } - return this; + if ( targetObject.geometry.isBufferGeometry ) { - }, + if ( ! targetObject.geometry.morphAttributes ) { - setLoop: function ( mode, repetitions ) { + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); + return; - this.loop = mode; - this.repetitions = repetitions; + } - return this; + if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) { - }, + propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ]; - // Weight + } - // set the weight stopping any scheduled fading - // although .enabled = false yields an effective weight of zero, this - // method does *not* change .enabled, because it would be confusing - setEffectiveWeight: function ( weight ) { - this.weight = weight; + } else { - // note: same logic as when updated at runtime - this._effectiveWeight = this.enabled ? weight : 0; + console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this ); + return; - return this.stopFading(); + } - }, + } - // return the weight considering fading and .enabled - getEffectiveWeight: function () { + bindingType = this.BindingType.ArrayElement; - return this._effectiveWeight; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; - }, + } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { - fadeIn: function ( duration ) { + // must use copy for Object3D.Euler/Quaternion - return this._scheduleFading( duration, 0, 1 ); + bindingType = this.BindingType.HasFromToArray; - }, + this.resolvedProperty = nodeProperty; - fadeOut: function ( duration ) { + } else if ( Array.isArray( nodeProperty ) ) { - return this._scheduleFading( duration, 1, 0 ); + bindingType = this.BindingType.EntireArray; - }, + this.resolvedProperty = nodeProperty; - crossFadeFrom: function ( fadeOutAction, duration, warp ) { + } else { - fadeOutAction.fadeOut( duration ); - this.fadeIn( duration ); + this.propertyName = propertyName; - if ( warp ) { + } - var fadeInDuration = this._clip.duration, - fadeOutDuration = fadeOutAction._clip.duration, + // select getter / setter + this.getValue = this.GetterByBindingType[ bindingType ]; + this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; - startEndRatio = fadeOutDuration / fadeInDuration, - endStartRatio = fadeInDuration / fadeOutDuration; + }, - fadeOutAction.warp( 1.0, startEndRatio, duration ); - this.warp( endStartRatio, 1.0, duration ); + unbind: function () { - } + this.node = null; - return this; + // back to the prototype version of getValue / setValue + // note: avoiding to mutate the shape of 'this' via 'delete' + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; - }, + } - crossFadeTo: function ( fadeInAction, duration, warp ) { +} ); - return fadeInAction.crossFadeFrom( this, duration, warp ); +// DECLARE ALIAS AFTER assign prototype +Object.assign( PropertyBinding.prototype, { - }, + // initial state of these methods that calls 'bind' + _getValue_unbound: PropertyBinding.prototype.getValue, + _setValue_unbound: PropertyBinding.prototype.setValue, - stopFading: function () { +} ); - var weightInterpolant = this._weightInterpolant; +/** + * + * A group of objects that receives a shared animation state. + * + * Usage: + * + * - Add objects you would otherwise pass as 'root' to the + * constructor or the .clipAction method of AnimationMixer. + * + * - Instead pass this object as 'root'. + * + * - You can also add and remove objects later when the mixer + * is running. + * + * Note: + * + * Objects of this class appear as one object to the mixer, + * so cache control of the individual objects must be done + * on the group. + * + * Limitation: + * + * - The animated properties must be compatible among the + * all objects in the group. + * + * - A single property can either be controlled through a + * target group or directly, but not both. + * + * @author tschw + */ - if ( weightInterpolant !== null ) { +function AnimationObjectGroup() { - this._weightInterpolant = null; - this._mixer._takeBackControlInterpolant( weightInterpolant ); + this.uuid = MathUtils.generateUUID(); - } + // cached objects followed by the active ones + this._objects = Array.prototype.slice.call( arguments ); - return this; + this.nCachedObjects_ = 0; // threshold + // note: read by PropertyBinding.Composite - }, + var indices = {}; + this._indicesByUUID = indices; // for bookkeeping - // Time Scale Control + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - // set the time scale stopping any scheduled warping - // although .paused = true yields an effective time scale of zero, this - // method does *not* change .paused, because it would be confusing - setEffectiveTimeScale: function ( timeScale ) { + indices[ arguments[ i ].uuid ] = i; - this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 : timeScale; + } - return this.stopWarping(); + this._paths = []; // inside: string + this._parsedPaths = []; // inside: { we don't care, here } + this._bindings = []; // inside: Array< PropertyBinding > + this._bindingsIndicesByPath = {}; // inside: indices in these arrays - }, + var scope = this; - // return the time scale considering warping and .paused - getEffectiveTimeScale: function () { + this.stats = { - return this._effectiveTimeScale; + objects: { + get total() { - }, + return scope._objects.length; - setDuration: function ( duration ) { - - this.timeScale = this._clip.duration / duration; + }, + get inUse() { - return this.stopWarping(); + return this.total - scope.nCachedObjects_; + } }, + get bindingsPerObject() { - syncWith: function ( action ) { + return scope._bindings.length; - this.time = action.time; - this.timeScale = action.timeScale; + } - return this.stopWarping(); + }; - }, +} - halt: function ( duration ) { +Object.assign( AnimationObjectGroup.prototype, { - return this.warp( this._effectiveTimeScale, 0, duration ); + isAnimationObjectGroup: true, - }, + add: function () { - warp: function ( startTimeScale, endTimeScale, duration ) { + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + nBindings = bindings.length, + knownObject = undefined; - var mixer = this._mixer, now = mixer.time, - interpolant = this._timeScaleInterpolant, + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - timeScale = this.timeScale; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - if ( interpolant === null ) { + if ( index === undefined ) { - interpolant = mixer._lendControlInterpolant(); - this._timeScaleInterpolant = interpolant; + // unknown object -> add it to the ACTIVE region - } + index = nObjects ++; + indicesByUUID[ uuid ] = index; + objects.push( object ); - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + // accounting is done, now do the same for all bindings - times[ 0 ] = now; - times[ 1 ] = now + duration; + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - values[ 0 ] = startTimeScale / timeScale; - values[ 1 ] = endTimeScale / timeScale; + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); - return this; + } - }, + } else if ( index < nCachedObjects ) { - stopWarping: function () { + knownObject = objects[ index ]; - var timeScaleInterpolant = this._timeScaleInterpolant; + // move existing object to the ACTIVE region - if ( timeScaleInterpolant !== null ) { + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ]; - this._timeScaleInterpolant = null; - this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - } + indicesByUUID[ uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = object; - return this; + // accounting is done, now do the same for all bindings - }, + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - // Object Accessors + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + binding = bindingsForPath[ index ]; - getMixer: function () { + bindingsForPath[ index ] = lastCached; - return this._mixer; + if ( binding === undefined ) { - }, + // since we do not bother to create new bindings + // for objects that are cached, the binding may + // or may not exist - getClip: function () { + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); - return this._clip; + } - }, + bindingsForPath[ firstActiveIndex ] = binding; - getRoot: function () { + } - return this._localRoot || this._mixer._root; + } else if ( objects[ index ] !== knownObject ) { - }, + console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); - // Interna + } // else the object is already where we want it to be - _update: function ( time, deltaTime, timeDirection, accuIndex ) { + } // for arguments - // called by the mixer + this.nCachedObjects_ = nCachedObjects; - if ( ! this.enabled ) { + }, - // call ._updateWeight() to update ._effectiveWeight + remove: function () { - this._updateWeight( time ); - return; + var objects = this._objects, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - } + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - var startTime = this._startTime; + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - if ( startTime !== null ) { + if ( index !== undefined && index >= nCachedObjects ) { - // check for scheduled start of action + // move existing object into the CACHED region - var timeRunning = ( time - startTime ) * timeDirection; - if ( timeRunning < 0 || timeDirection === 0 ) { + var lastCachedIndex = nCachedObjects ++, + firstActiveObject = objects[ lastCachedIndex ]; - return; // yet to come / don't decide when delta = 0 + indicesByUUID[ firstActiveObject.uuid ] = index; + objects[ index ] = firstActiveObject; - } + indicesByUUID[ uuid ] = lastCachedIndex; + objects[ lastCachedIndex ] = object; - // start + // accounting is done, now do the same for all bindings - this._startTime = null; // unschedule - deltaTime = timeDirection * timeRunning; + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - } + var bindingsForPath = bindings[ j ], + firstActive = bindingsForPath[ lastCachedIndex ], + binding = bindingsForPath[ index ]; - // apply time scale and advance time + bindingsForPath[ index ] = firstActive; + bindingsForPath[ lastCachedIndex ] = binding; - deltaTime *= this._updateTimeScale( time ); - var clipTime = this._updateTime( deltaTime ); + } - // note: _updateTime may disable the action resulting in - // an effective weight of 0 + } - var weight = this._updateWeight( time ); + } // for arguments - if ( weight > 0 ) { + this.nCachedObjects_ = nCachedObjects; - var interpolants = this._interpolants; - var propertyMixers = this._propertyBindings; + }, - for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { + // remove & forget + uncache: function () { - interpolants[ j ].evaluate( clipTime ); - propertyMixers[ j ].accumulate( accuIndex, weight ); + var objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + indicesByUUID = this._indicesByUUID, + bindings = this._bindings, + nBindings = bindings.length; - } + for ( var i = 0, n = arguments.length; i !== n; ++ i ) { - } + var object = arguments[ i ], + uuid = object.uuid, + index = indicesByUUID[ uuid ]; - }, + if ( index !== undefined ) { - _updateWeight: function ( time ) { + delete indicesByUUID[ uuid ]; - var weight = 0; + if ( index < nCachedObjects ) { - if ( this.enabled ) { + // object is cached, shrink the CACHED region - weight = this.weight; - var interpolant = this._weightInterpolant; + var firstActiveIndex = -- nCachedObjects, + lastCachedObject = objects[ firstActiveIndex ], + lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - if ( interpolant !== null ) { + // last cached object takes this object's place + indicesByUUID[ lastCachedObject.uuid ] = index; + objects[ index ] = lastCachedObject; - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + // last object goes to the activated slot and pop + indicesByUUID[ lastObject.uuid ] = firstActiveIndex; + objects[ firstActiveIndex ] = lastObject; + objects.pop(); - weight *= interpolantValue; + // accounting is done, now do the same for all bindings - if ( time > interpolant.parameterPositions[ 1 ] ) { + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - this.stopFading(); + var bindingsForPath = bindings[ j ], + lastCached = bindingsForPath[ firstActiveIndex ], + last = bindingsForPath[ lastIndex ]; - if ( interpolantValue === 0 ) { + bindingsForPath[ index ] = lastCached; + bindingsForPath[ firstActiveIndex ] = last; + bindingsForPath.pop(); - // faded out, disable - this.enabled = false; + } - } + } else { - } + // object is active, just swap with the last and pop - } + var lastIndex = -- nObjects, + lastObject = objects[ lastIndex ]; - } + indicesByUUID[ lastObject.uuid ] = index; + objects[ index ] = lastObject; + objects.pop(); - this._effectiveWeight = weight; - return weight; + // accounting is done, now do the same for all bindings - }, + for ( var j = 0, m = nBindings; j !== m; ++ j ) { - _updateTimeScale: function ( time ) { + var bindingsForPath = bindings[ j ]; - var timeScale = 0; + bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; + bindingsForPath.pop(); - if ( ! this.paused ) { + } - timeScale = this.timeScale; + } // cached or active - var interpolant = this._timeScaleInterpolant; + } // if object is known - if ( interpolant !== null ) { + } // for arguments - var interpolantValue = interpolant.evaluate( time )[ 0 ]; + this.nCachedObjects_ = nCachedObjects; - timeScale *= interpolantValue; + }, - if ( time > interpolant.parameterPositions[ 1 ] ) { + // Internal interface used by befriended PropertyBinding.Composite: - this.stopWarping(); + subscribe_: function ( path, parsedPath ) { - if ( timeScale === 0 ) { + // returns an array of bindings for the given path that is changed + // according to the contained objects in the group - // motion has halted, pause - this.paused = true; + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ], + bindings = this._bindings; - } else { + if ( index !== undefined ) return bindings[ index ]; - // warp done - apply final time scale - this.timeScale = timeScale; + var paths = this._paths, + parsedPaths = this._parsedPaths, + objects = this._objects, + nObjects = objects.length, + nCachedObjects = this.nCachedObjects_, + bindingsForPath = new Array( nObjects ); - } + index = bindings.length; - } + indicesByPath[ path ] = index; - } + paths.push( path ); + parsedPaths.push( parsedPath ); + bindings.push( bindingsForPath ); - } + for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) { - this._effectiveTimeScale = timeScale; - return timeScale; + var object = objects[ i ]; + bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); - }, + } - _updateTime: function ( deltaTime ) { + return bindingsForPath; - var time = this.time + deltaTime; - var duration = this._clip.duration; - var loop = this.loop; - var loopCount = this._loopCount; + }, - var pingPong = ( loop === LoopPingPong ); + unsubscribe_: function ( path ) { - if ( deltaTime === 0 ) { + // tells the group to forget about a property path and no longer + // update the array previously obtained with 'subscribe_' - if ( loopCount === - 1 ) { return time; } + var indicesByPath = this._bindingsIndicesByPath, + index = indicesByPath[ path ]; - return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; + if ( index !== undefined ) { - } + var paths = this._paths, + parsedPaths = this._parsedPaths, + bindings = this._bindings, + lastBindingsIndex = bindings.length - 1, + lastBindings = bindings[ lastBindingsIndex ], + lastBindingsPath = path[ lastBindingsIndex ]; - if ( loop === LoopOnce ) { + indicesByPath[ lastBindingsPath ] = index; - if ( loopCount === - 1 ) { + bindings[ index ] = lastBindings; + bindings.pop(); - // just started + parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; + parsedPaths.pop(); - this._loopCount = 0; - this._setEndings( true, true, false ); + paths[ index ] = paths[ lastBindingsIndex ]; + paths.pop(); - } + } - handle_stop: { + } - if ( time >= duration ) { +} ); - time = duration; +/** + * + * Action provided by AnimationMixer for scheduling clip playback on specific + * objects. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + * + */ - } else if ( time < 0 ) { +function AnimationAction( mixer, clip, localRoot, blendMode ) { - time = 0; + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot || null; + this.blendMode = blendMode || clip.blendMode; - } else { + var tracks = clip.tracks, + nTracks = tracks.length, + interpolants = new Array( nTracks ); - this.time = time; + var interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; - break handle_stop; + for ( var i = 0; i !== nTracks; ++ i ) { - } + var interpolant = tracks[ i ].createInterpolant( null ); + interpolants[ i ] = interpolant; + interpolant.settings = interpolantSettings; - if ( this.clampWhenFinished ) { this.paused = true; } - else { this.enabled = false; } + } - this.time = time; + this._interpolantSettings = interpolantSettings; - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime < 0 ? - 1 : 1 - } ); + this._interpolants = interpolants; // bound by the mixer - } + // inside: PropertyMixer (managed by the mixer) + this._propertyBindings = new Array( nTracks ); - } else { // repetitive Repeat or PingPong + this._cacheIndex = null; // for the memory manager + this._byClipCacheIndex = null; // for the memory manager - if ( loopCount === - 1 ) { + this._timeScaleInterpolant = null; + this._weightInterpolant = null; - // just started + this.loop = LoopRepeat; + this._loopCount = - 1; - if ( deltaTime >= 0 ) { + // global mixer time when the action is to be started + // it's set back to 'null' upon start of the action + this._startTime = null; - loopCount = 0; + // scaled local time of the action + // gets clamped or wrapped to 0..clip.duration according to loop + this.time = 0; - this._setEndings( true, this.repetitions === 0, pingPong ); + this.timeScale = 1; + this._effectiveTimeScale = 1; - } else { + this.weight = 1; + this._effectiveWeight = 1; - // when looping in reverse direction, the initial - // transition through zero counts as a repetition, - // so leave loopCount at -1 + this.repetitions = Infinity; // no. of repetitions when looping - this._setEndings( this.repetitions === 0, true, pingPong ); + this.paused = false; // true -> zero effective time scale + this.enabled = true; // false -> zero effective weight - } + this.clampWhenFinished = false;// keep feeding the last frame? - } + this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate + this.zeroSlopeAtEnd = true;// clips for start, loop and end - if ( time >= duration || time < 0 ) { +} - // wrap around +Object.assign( AnimationAction.prototype, { - var loopDelta = Math.floor( time / duration ); // signed - time -= duration * loopDelta; + // State & Scheduling - loopCount += Math.abs( loopDelta ); + play: function () { - var pending = this.repetitions - loopCount; + this._mixer._activateAction( this ); - if ( pending <= 0 ) { + return this; - // have to stop (switch state, clamp time, fire event) + }, - if ( this.clampWhenFinished ) { this.paused = true; } - else { this.enabled = false; } + stop: function () { - time = deltaTime > 0 ? duration : 0; + this._mixer._deactivateAction( this ); - this.time = time; + return this.reset(); - this._mixer.dispatchEvent( { - type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : - 1 - } ); + }, - } else { + reset: function () { - // keep running + this.paused = false; + this.enabled = true; - if ( pending === 1 ) { + this.time = 0; // restart clip + this._loopCount = - 1;// forget previous loops + this._startTime = null;// forget scheduling - // entering the last round + return this.stopFading().stopWarping(); - var atStart = deltaTime < 0; - this._setEndings( atStart, ! atStart, pingPong ); + }, - } else { + isRunning: function () { - this._setEndings( false, false, pingPong ); + return this.enabled && ! this.paused && this.timeScale !== 0 && + this._startTime === null && this._mixer._isActiveAction( this ); - } + }, - this._loopCount = loopCount; + // return true when play has been called + isScheduled: function () { - this.time = time; + return this._mixer._isActiveAction( this ); - this._mixer.dispatchEvent( { - type: 'loop', action: this, loopDelta: loopDelta - } ); + }, - } + startAt: function ( time ) { - } else { + this._startTime = time; - this.time = time; + return this; - } + }, - if ( pingPong && ( loopCount & 1 ) === 1 ) { + setLoop: function ( mode, repetitions ) { - // invert time for the "pong round" + this.loop = mode; + this.repetitions = repetitions; - return duration - time; + return this; - } + }, - } + // Weight - return time; + // set the weight stopping any scheduled fading + // although .enabled = false yields an effective weight of zero, this + // method does *not* change .enabled, because it would be confusing + setEffectiveWeight: function ( weight ) { - }, + this.weight = weight; - _setEndings: function ( atStart, atEnd, pingPong ) { + // note: same logic as when updated at runtime + this._effectiveWeight = this.enabled ? weight : 0; - var settings = this._interpolantSettings; + return this.stopFading(); - if ( pingPong ) { + }, - settings.endingStart = ZeroSlopeEnding; - settings.endingEnd = ZeroSlopeEnding; + // return the weight considering fading and .enabled + getEffectiveWeight: function () { - } else { + return this._effectiveWeight; - // assuming for LoopOnce atStart == atEnd == true + }, - if ( atStart ) { + fadeIn: function ( duration ) { - settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + return this._scheduleFading( duration, 0, 1 ); - } else { + }, - settings.endingStart = WrapAroundEnding; + fadeOut: function ( duration ) { - } + return this._scheduleFading( duration, 1, 0 ); - if ( atEnd ) { + }, - settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + crossFadeFrom: function ( fadeOutAction, duration, warp ) { - } else { + fadeOutAction.fadeOut( duration ); + this.fadeIn( duration ); - settings.endingEnd = WrapAroundEnding; + if ( warp ) { - } + var fadeInDuration = this._clip.duration, + fadeOutDuration = fadeOutAction._clip.duration, - } + startEndRatio = fadeOutDuration / fadeInDuration, + endStartRatio = fadeInDuration / fadeOutDuration; - }, + fadeOutAction.warp( 1.0, startEndRatio, duration ); + this.warp( endStartRatio, 1.0, duration ); - _scheduleFading: function ( duration, weightNow, weightThen ) { + } - var mixer = this._mixer, now = mixer.time, - interpolant = this._weightInterpolant; + return this; - if ( interpolant === null ) { + }, - interpolant = mixer._lendControlInterpolant(); - this._weightInterpolant = interpolant; + crossFadeTo: function ( fadeInAction, duration, warp ) { - } + return fadeInAction.crossFadeFrom( this, duration, warp ); - var times = interpolant.parameterPositions, - values = interpolant.sampleValues; + }, - times[ 0 ] = now; - values[ 0 ] = weightNow; - times[ 1 ] = now + duration; - values[ 1 ] = weightThen; + stopFading: function () { - return this; + var weightInterpolant = this._weightInterpolant; - } + if ( weightInterpolant !== null ) { - } ); + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant( weightInterpolant ); - /** - * - * Player for AnimationClips. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + } - function AnimationMixer( root ) { + return this; - this._root = root; - this._initMemoryManager(); - this._accuIndex = 0; + }, - this.time = 0; + // Time Scale Control - this.timeScale = 1.0; + // set the time scale stopping any scheduled warping + // although .paused = true yields an effective time scale of zero, this + // method does *not* change .paused, because it would be confusing + setEffectiveTimeScale: function ( timeScale ) { - } + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; - AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + return this.stopWarping(); - constructor: AnimationMixer, + }, - _bindAction: function ( action, prototypeAction ) { + // return the time scale considering warping and .paused + getEffectiveTimeScale: function () { - var root = action._localRoot || this._root, - tracks = action._clip.tracks, - nTracks = tracks.length, - bindings = action._propertyBindings, - interpolants = action._interpolants, - rootUuid = root.uuid, - bindingsByRoot = this._bindingsByRootAndName, - bindingsByName = bindingsByRoot[ rootUuid ]; + return this._effectiveTimeScale; - if ( bindingsByName === undefined ) { + }, - bindingsByName = {}; - bindingsByRoot[ rootUuid ] = bindingsByName; + setDuration: function ( duration ) { - } + this.timeScale = this._clip.duration / duration; - for ( var i = 0; i !== nTracks; ++ i ) { + return this.stopWarping(); - var track = tracks[ i ], - trackName = track.name, - binding = bindingsByName[ trackName ]; + }, - if ( binding !== undefined ) { + syncWith: function ( action ) { - bindings[ i ] = binding; + this.time = action.time; + this.timeScale = action.timeScale; - } else { + return this.stopWarping(); - binding = bindings[ i ]; + }, - if ( binding !== undefined ) { + halt: function ( duration ) { - // existing binding, make sure the cache knows + return this.warp( this._effectiveTimeScale, 0, duration ); - if ( binding._cacheIndex === null ) { + }, - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + warp: function ( startTimeScale, endTimeScale, duration ) { - } + var mixer = this._mixer, now = mixer.time, + interpolant = this._timeScaleInterpolant, - continue; + timeScale = this.timeScale; - } + if ( interpolant === null ) { - var path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; - binding = new PropertyMixer( - PropertyBinding.create( root, trackName, path ), - track.ValueTypeName, track.getValueSize() ); + } - ++ binding.referenceCount; - this._addInactiveBinding( binding, rootUuid, trackName ); + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - bindings[ i ] = binding; + times[ 0 ] = now; + times[ 1 ] = now + duration; - } + values[ 0 ] = startTimeScale / timeScale; + values[ 1 ] = endTimeScale / timeScale; - interpolants[ i ].resultBuffer = binding.buffer; + return this; - } + }, - }, + stopWarping: function () { - _activateAction: function ( action ) { + var timeScaleInterpolant = this._timeScaleInterpolant; - if ( ! this._isActiveAction( action ) ) { + if ( timeScaleInterpolant !== null ) { - if ( action._cacheIndex === null ) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); - // this action has been forgotten by the cache, but the user - // appears to be still using it -> rebind + } - var rootUuid = ( action._localRoot || this._root ).uuid, - clipUuid = action._clip.uuid, - actionsForClip = this._actionsByClip[ clipUuid ]; + return this; - this._bindAction( action, - actionsForClip && actionsForClip.knownActions[ 0 ] ); + }, - this._addInactiveAction( action, clipUuid, rootUuid ); + // Object Accessors - } + getMixer: function () { - var bindings = action._propertyBindings; + return this._mixer; - // increment reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + }, - var binding = bindings[ i ]; + getClip: function () { - if ( binding.useCount ++ === 0 ) { + return this._clip; - this._lendBinding( binding ); - binding.saveOriginalState(); + }, - } + getRoot: function () { - } + return this._localRoot || this._mixer._root; - this._lendAction( action ); + }, - } + // Interna - }, + _update: function ( time, deltaTime, timeDirection, accuIndex ) { - _deactivateAction: function ( action ) { + // called by the mixer - if ( this._isActiveAction( action ) ) { + if ( ! this.enabled ) { - var bindings = action._propertyBindings; + // call ._updateWeight() to update ._effectiveWeight - // decrement reference counts / sort out state - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + this._updateWeight( time ); + return; - var binding = bindings[ i ]; + } - if ( -- binding.useCount === 0 ) { + var startTime = this._startTime; - binding.restoreOriginalState(); - this._takeBackBinding( binding ); + if ( startTime !== null ) { - } + // check for scheduled start of action - } + var timeRunning = ( time - startTime ) * timeDirection; + if ( timeRunning < 0 || timeDirection === 0 ) { - this._takeBackAction( action ); + return; // yet to come / don't decide when delta = 0 } - }, + // start - // Memory manager + this._startTime = null; // unschedule + deltaTime = timeDirection * timeRunning; - _initMemoryManager: function () { + } - this._actions = []; // 'nActiveActions' followed by inactive ones - this._nActiveActions = 0; + // apply time scale and advance time - this._actionsByClip = {}; - // inside: - // { - // knownActions: Array< AnimationAction > - used as prototypes - // actionByRoot: AnimationAction - lookup - // } + deltaTime *= this._updateTimeScale( time ); + var clipTime = this._updateTime( deltaTime ); + // note: _updateTime may disable the action resulting in + // an effective weight of 0 - this._bindings = []; // 'nActiveBindings' followed by inactive ones - this._nActiveBindings = 0; + var weight = this._updateWeight( time ); - this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > + if ( weight > 0 ) { + var interpolants = this._interpolants; + var propertyMixers = this._propertyBindings; - this._controlInterpolants = []; // same game as above - this._nActiveControlInterpolants = 0; + switch ( this.blendMode ) { - var scope = this; + case AdditiveAnimationBlendMode: - this.stats = { + for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { - actions: { - get total() { + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulateAdditive( weight ); - return scope._actions.length; + } - }, - get inUse() { + break; - return scope._nActiveActions; + case NormalAnimationBlendMode: + default: - } - }, - bindings: { - get total() { + for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { - return scope._bindings.length; + interpolants[ j ].evaluate( clipTime ); + propertyMixers[ j ].accumulate( accuIndex, weight ); - }, - get inUse() { + } - return scope._nActiveBindings; + } - } - }, - controlInterpolants: { - get total() { + } - return scope._controlInterpolants.length; + }, - }, - get inUse() { + _updateWeight: function ( time ) { - return scope._nActiveControlInterpolants; + var weight = 0; - } - } + if ( this.enabled ) { - }; + weight = this.weight; + var interpolant = this._weightInterpolant; - }, + if ( interpolant !== null ) { - // Memory management for AnimationAction objects + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - _isActiveAction: function ( action ) { + weight *= interpolantValue; - var index = action._cacheIndex; - return index !== null && index < this._nActiveActions; + if ( time > interpolant.parameterPositions[ 1 ] ) { - }, + this.stopFading(); - _addInactiveAction: function ( action, clipUuid, rootUuid ) { + if ( interpolantValue === 0 ) { - var actions = this._actions, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + // faded out, disable + this.enabled = false; - if ( actionsForClip === undefined ) { + } - actionsForClip = { + } - knownActions: [ action ], - actionByRoot: {} + } - }; + } - action._byClipCacheIndex = 0; + this._effectiveWeight = weight; + return weight; - actionsByClip[ clipUuid ] = actionsForClip; + }, - } else { + _updateTimeScale: function ( time ) { - var knownActions = actionsForClip.knownActions; + var timeScale = 0; - action._byClipCacheIndex = knownActions.length; - knownActions.push( action ); + if ( ! this.paused ) { - } + timeScale = this.timeScale; - action._cacheIndex = actions.length; - actions.push( action ); + var interpolant = this._timeScaleInterpolant; - actionsForClip.actionByRoot[ rootUuid ] = action; + if ( interpolant !== null ) { - }, + var interpolantValue = interpolant.evaluate( time )[ 0 ]; - _removeInactiveAction: function ( action ) { + timeScale *= interpolantValue; - var actions = this._actions, - lastInactiveAction = actions[ actions.length - 1 ], - cacheIndex = action._cacheIndex; + if ( time > interpolant.parameterPositions[ 1 ] ) { - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + this.stopWarping(); - action._cacheIndex = null; + if ( timeScale === 0 ) { + // motion has halted, pause + this.paused = true; - var clipUuid = action._clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ], - knownActionsForClip = actionsForClip.knownActions, + } else { - lastKnownAction = - knownActionsForClip[ knownActionsForClip.length - 1 ], + // warp done - apply final time scale + this.timeScale = timeScale; - byClipCacheIndex = action._byClipCacheIndex; + } - lastKnownAction._byClipCacheIndex = byClipCacheIndex; - knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; - knownActionsForClip.pop(); + } - action._byClipCacheIndex = null; + } + } - var actionByRoot = actionsForClip.actionByRoot, - rootUuid = ( action._localRoot || this._root ).uuid; + this._effectiveTimeScale = timeScale; + return timeScale; - delete actionByRoot[ rootUuid ]; + }, - if ( knownActionsForClip.length === 0 ) { + _updateTime: function ( deltaTime ) { - delete actionsByClip[ clipUuid ]; + var time = this.time + deltaTime; + var duration = this._clip.duration; + var loop = this.loop; + var loopCount = this._loopCount; - } + var pingPong = ( loop === LoopPingPong ); - this._removeInactiveBindingsForAction( action ); + if ( deltaTime === 0 ) { - }, + if ( loopCount === - 1 ) return time; - _removeInactiveBindingsForAction: function ( action ) { + return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; - var bindings = action._propertyBindings; - for ( var i = 0, n = bindings.length; i !== n; ++ i ) { + } - var binding = bindings[ i ]; + if ( loop === LoopOnce ) { - if ( -- binding.referenceCount === 0 ) { + if ( loopCount === - 1 ) { - this._removeInactiveBinding( binding ); + // just started - } + this._loopCount = 0; + this._setEndings( true, true, false ); } - }, + handle_stop: { - _lendAction: function ( action ) { + if ( time >= duration ) { - // [ active actions | inactive actions ] - // [ active actions >| inactive actions ] - // s a - // <-swap-> - // a s + time = duration; - var actions = this._actions, - prevIndex = action._cacheIndex, + } else if ( time < 0 ) { - lastActiveIndex = this._nActiveActions ++, + time = 0; - firstInactiveAction = actions[ lastActiveIndex ]; + } else { - action._cacheIndex = lastActiveIndex; - actions[ lastActiveIndex ] = action; + this.time = time; - firstInactiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = firstInactiveAction; + break handle_stop; - }, + } - _takeBackAction: function ( action ) { + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - // [ active actions | inactive actions ] - // [ active actions |< inactive actions ] - // a s - // <-swap-> - // s a + this.time = time; - var actions = this._actions, - prevIndex = action._cacheIndex, + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime < 0 ? - 1 : 1 + } ); - firstInactiveIndex = -- this._nActiveActions, + } - lastActiveAction = actions[ firstInactiveIndex ]; + } else { // repetitive Repeat or PingPong - action._cacheIndex = firstInactiveIndex; - actions[ firstInactiveIndex ] = action; + if ( loopCount === - 1 ) { - lastActiveAction._cacheIndex = prevIndex; - actions[ prevIndex ] = lastActiveAction; + // just started - }, + if ( deltaTime >= 0 ) { - // Memory management for PropertyMixer objects + loopCount = 0; - _addInactiveBinding: function ( binding, rootUuid, trackName ) { + this._setEndings( true, this.repetitions === 0, pingPong ); - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + } else { - bindings = this._bindings; + // when looping in reverse direction, the initial + // transition through zero counts as a repetition, + // so leave loopCount at -1 - if ( bindingByName === undefined ) { + this._setEndings( this.repetitions === 0, true, pingPong ); - bindingByName = {}; - bindingsByRoot[ rootUuid ] = bindingByName; + } } - bindingByName[ trackName ] = binding; - - binding._cacheIndex = bindings.length; - bindings.push( binding ); - - }, + if ( time >= duration || time < 0 ) { - _removeInactiveBinding: function ( binding ) { + // wrap around - var bindings = this._bindings, - propBinding = binding.binding, - rootUuid = propBinding.rootNode.uuid, - trackName = propBinding.path, - bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ], + var loopDelta = Math.floor( time / duration ); // signed + time -= duration * loopDelta; - lastInactiveBinding = bindings[ bindings.length - 1 ], - cacheIndex = binding._cacheIndex; + loopCount += Math.abs( loopDelta ); - lastInactiveBinding._cacheIndex = cacheIndex; - bindings[ cacheIndex ] = lastInactiveBinding; - bindings.pop(); + var pending = this.repetitions - loopCount; - delete bindingByName[ trackName ]; + if ( pending <= 0 ) { - if ( Object.keys( bindingByName ).length === 0 ) { + // have to stop (switch state, clamp time, fire event) - delete bindingsByRoot[ rootUuid ]; + if ( this.clampWhenFinished ) this.paused = true; + else this.enabled = false; - } + time = deltaTime > 0 ? duration : 0; - }, + this.time = time; - _lendBinding: function ( binding ) { + this._mixer.dispatchEvent( { + type: 'finished', action: this, + direction: deltaTime > 0 ? 1 : - 1 + } ); - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + } else { - lastActiveIndex = this._nActiveBindings ++, + // keep running - firstInactiveBinding = bindings[ lastActiveIndex ]; + if ( pending === 1 ) { - binding._cacheIndex = lastActiveIndex; - bindings[ lastActiveIndex ] = binding; + // entering the last round - firstInactiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = firstInactiveBinding; + var atStart = deltaTime < 0; + this._setEndings( atStart, ! atStart, pingPong ); - }, + } else { - _takeBackBinding: function ( binding ) { + this._setEndings( false, false, pingPong ); - var bindings = this._bindings, - prevIndex = binding._cacheIndex, + } - firstInactiveIndex = -- this._nActiveBindings, + this._loopCount = loopCount; - lastActiveBinding = bindings[ firstInactiveIndex ]; + this.time = time; - binding._cacheIndex = firstInactiveIndex; - bindings[ firstInactiveIndex ] = binding; + this._mixer.dispatchEvent( { + type: 'loop', action: this, loopDelta: loopDelta + } ); - lastActiveBinding._cacheIndex = prevIndex; - bindings[ prevIndex ] = lastActiveBinding; + } - }, + } else { + this.time = time; - // Memory management of Interpolants for weight and time scale + } - _lendControlInterpolant: function () { + if ( pingPong && ( loopCount & 1 ) === 1 ) { - var interpolants = this._controlInterpolants, - lastActiveIndex = this._nActiveControlInterpolants ++, - interpolant = interpolants[ lastActiveIndex ]; + // invert time for the "pong round" - if ( interpolant === undefined ) { + return duration - time; - interpolant = new LinearInterpolant( - new Float32Array( 2 ), new Float32Array( 2 ), - 1, this._controlInterpolantsResultBuffer ); + } - interpolant.__cacheIndex = lastActiveIndex; - interpolants[ lastActiveIndex ] = interpolant; + } - } + return time; - return interpolant; + }, - }, + _setEndings: function ( atStart, atEnd, pingPong ) { - _takeBackControlInterpolant: function ( interpolant ) { + var settings = this._interpolantSettings; - var interpolants = this._controlInterpolants, - prevIndex = interpolant.__cacheIndex, + if ( pingPong ) { - firstInactiveIndex = -- this._nActiveControlInterpolants, + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; - lastActiveInterpolant = interpolants[ firstInactiveIndex ]; + } else { - interpolant.__cacheIndex = firstInactiveIndex; - interpolants[ firstInactiveIndex ] = interpolant; + // assuming for LoopOnce atStart == atEnd == true - lastActiveInterpolant.__cacheIndex = prevIndex; - interpolants[ prevIndex ] = lastActiveInterpolant; + if ( atStart ) { - }, + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; - _controlInterpolantsResultBuffer: new Float32Array( 1 ), + } else { - // return an action for a clip optionally using a custom root target - // object (this method allocates a lot of dynamic memory in case a - // previously unknown clip/root combination is specified) - clipAction: function ( clip, optionalRoot ) { + settings.endingStart = WrapAroundEnding; - var root = optionalRoot || this._root, - rootUuid = root.uuid, + } - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + if ( atEnd ) { - clipUuid = clipObject !== null ? clipObject.uuid : clip, + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; - actionsForClip = this._actionsByClip[ clipUuid ], - prototypeAction = null; + } else { - if ( actionsForClip !== undefined ) { + settings.endingEnd = WrapAroundEnding; - var existingAction = - actionsForClip.actionByRoot[ rootUuid ]; + } - if ( existingAction !== undefined ) { + } - return existingAction; + }, - } + _scheduleFading: function ( duration, weightNow, weightThen ) { - // we know the clip, so we don't have to parse all - // the bindings again but can just copy - prototypeAction = actionsForClip.knownActions[ 0 ]; + var mixer = this._mixer, now = mixer.time, + interpolant = this._weightInterpolant; - // also, take the clip from the prototype action - if ( clipObject === null ) - { clipObject = prototypeAction._clip; } + if ( interpolant === null ) { - } + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; - // clip must be known when specified via string - if ( clipObject === null ) { return null; } + } - // allocate all resources required to run it - var newAction = new AnimationAction( this, clipObject, optionalRoot ); + var times = interpolant.parameterPositions, + values = interpolant.sampleValues; - this._bindAction( newAction, prototypeAction ); + times[ 0 ] = now; + values[ 0 ] = weightNow; + times[ 1 ] = now + duration; + values[ 1 ] = weightThen; - // and make the action known to the memory manager - this._addInactiveAction( newAction, clipUuid, rootUuid ); + return this; - return newAction; + } - }, +} ); - // get an existing action - existingAction: function ( clip, optionalRoot ) { +/** + * + * Player for AnimationClips. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - var root = optionalRoot || this._root, - rootUuid = root.uuid, +function AnimationMixer( root ) { - clipObject = typeof clip === 'string' ? - AnimationClip.findByName( root, clip ) : clip, + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; - clipUuid = clipObject ? clipObject.uuid : clip, + this.time = 0; - actionsForClip = this._actionsByClip[ clipUuid ]; + this.timeScale = 1.0; - if ( actionsForClip !== undefined ) { +} - return actionsForClip.actionByRoot[ rootUuid ] || null; +AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - } + constructor: AnimationMixer, - return null; + _bindAction: function ( action, prototypeAction ) { - }, + var root = action._localRoot || this._root, + tracks = action._clip.tracks, + nTracks = tracks.length, + bindings = action._propertyBindings, + interpolants = action._interpolants, + rootUuid = root.uuid, + bindingsByRoot = this._bindingsByRootAndName, + bindingsByName = bindingsByRoot[ rootUuid ]; - // deactivates all previously scheduled actions - stopAllAction: function () { + if ( bindingsByName === undefined ) { - var actions = this._actions, - nActions = this._nActiveActions, - bindings = this._bindings, - nBindings = this._nActiveBindings; + bindingsByName = {}; + bindingsByRoot[ rootUuid ] = bindingsByName; - this._nActiveActions = 0; - this._nActiveBindings = 0; + } - for ( var i = 0; i !== nActions; ++ i ) { + for ( var i = 0; i !== nTracks; ++ i ) { - actions[ i ].reset(); + var track = tracks[ i ], + trackName = track.name, + binding = bindingsByName[ trackName ]; - } + if ( binding !== undefined ) { - for ( var i = 0; i !== nBindings; ++ i ) { + bindings[ i ] = binding; - bindings[ i ].useCount = 0; + } else { - } + binding = bindings[ i ]; - return this; + if ( binding !== undefined ) { - }, + // existing binding, make sure the cache knows - // advance the time and update apply the animation - update: function ( deltaTime ) { + if ( binding._cacheIndex === null ) { - deltaTime *= this.timeScale; + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - var actions = this._actions, - nActions = this._nActiveActions, + } - time = this.time += deltaTime, - timeDirection = Math.sign( deltaTime ), + continue; - accuIndex = this._accuIndex ^= 1; + } - // run active actions + var path = prototypeAction && prototypeAction. + _propertyBindings[ i ].binding.parsedPath; - for ( var i = 0; i !== nActions; ++ i ) { + binding = new PropertyMixer( + PropertyBinding.create( root, trackName, path ), + track.ValueTypeName, track.getValueSize() ); - var action = actions[ i ]; + ++ binding.referenceCount; + this._addInactiveBinding( binding, rootUuid, trackName ); - action._update( time, deltaTime, timeDirection, accuIndex ); + bindings[ i ] = binding; } - // update scene graph + interpolants[ i ].resultBuffer = binding.buffer; - var bindings = this._bindings, - nBindings = this._nActiveBindings; + } - for ( var i = 0; i !== nBindings; ++ i ) { + }, - bindings[ i ].apply( accuIndex ); + _activateAction: function ( action ) { - } + if ( ! this._isActiveAction( action ) ) { - return this; + if ( action._cacheIndex === null ) { - }, + // this action has been forgotten by the cache, but the user + // appears to be still using it -> rebind - // Allows you to seek to a specific time in an animation. - setTime: function ( timeInSeconds ) { + var rootUuid = ( action._localRoot || this._root ).uuid, + clipUuid = action._clip.uuid, + actionsForClip = this._actionsByClip[ clipUuid ]; - this.time = 0; // Zero out time attribute for AnimationMixer object; - for ( var i = 0; i < this._actions.length; i ++ ) { + this._bindAction( action, + actionsForClip && actionsForClip.knownActions[ 0 ] ); - this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. + this._addInactiveAction( action, clipUuid, rootUuid ); } - return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. + var bindings = action._propertyBindings; - }, + // increment reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - // return this mixer's root target object - getRoot: function () { + var binding = bindings[ i ]; - return this._root; + if ( binding.useCount ++ === 0 ) { - }, + this._lendBinding( binding ); + binding.saveOriginalState(); - // free all resources specific to a particular clip - uncacheClip: function ( clip ) { + } - var actions = this._actions, - clipUuid = clip.uuid, - actionsByClip = this._actionsByClip, - actionsForClip = actionsByClip[ clipUuid ]; + } - if ( actionsForClip !== undefined ) { + this._lendAction( action ); - // note: just calling _removeInactiveAction would mess up the - // iteration state and also require updating the state we can - // just throw away + } - var actionsToRemove = actionsForClip.knownActions; + }, - for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { + _deactivateAction: function ( action ) { - var action = actionsToRemove[ i ]; + if ( this._isActiveAction( action ) ) { - this._deactivateAction( action ); + var bindings = action._propertyBindings; - var cacheIndex = action._cacheIndex, - lastInactiveAction = actions[ actions.length - 1 ]; + // decrement reference counts / sort out state + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - action._cacheIndex = null; - action._byClipCacheIndex = null; + var binding = bindings[ i ]; - lastInactiveAction._cacheIndex = cacheIndex; - actions[ cacheIndex ] = lastInactiveAction; - actions.pop(); + if ( -- binding.useCount === 0 ) { - this._removeInactiveBindingsForAction( action ); + binding.restoreOriginalState(); + this._takeBackBinding( binding ); } - delete actionsByClip[ clipUuid ]; - } - }, + this._takeBackAction( action ); - // free all resources specific to a particular root target object - uncacheRoot: function ( root ) { + } - var rootUuid = root.uuid, - actionsByClip = this._actionsByClip; + }, - for ( var clipUuid in actionsByClip ) { + // Memory manager - var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, - action = actionByRoot[ rootUuid ]; + _initMemoryManager: function () { - if ( action !== undefined ) { + this._actions = []; // 'nActiveActions' followed by inactive ones + this._nActiveActions = 0; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + this._actionsByClip = {}; + // inside: + // { + // knownActions: Array< AnimationAction > - used as prototypes + // actionByRoot: AnimationAction - lookup + // } - } - } + this._bindings = []; // 'nActiveBindings' followed by inactive ones + this._nActiveBindings = 0; - var bindingsByRoot = this._bindingsByRootAndName, - bindingByName = bindingsByRoot[ rootUuid ]; + this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > - if ( bindingByName !== undefined ) { - for ( var trackName in bindingByName ) { + this._controlInterpolants = []; // same game as above + this._nActiveControlInterpolants = 0; - var binding = bindingByName[ trackName ]; - binding.restoreOriginalState(); - this._removeInactiveBinding( binding ); - - } + var scope = this; - } + this.stats = { - }, + actions: { + get total() { - // remove a targeted clip from the cache - uncacheAction: function ( clip, optionalRoot ) { + return scope._actions.length; - var action = this.existingAction( clip, optionalRoot ); + }, + get inUse() { - if ( action !== null ) { + return scope._nActiveActions; - this._deactivateAction( action ); - this._removeInactiveAction( action ); + } + }, + bindings: { + get total() { - } + return scope._bindings.length; - } + }, + get inUse() { - } ); + return scope._nActiveBindings; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } + }, + controlInterpolants: { + get total() { - function Uniform( value ) { + return scope._controlInterpolants.length; - if ( typeof value === 'string' ) { + }, + get inUse() { - console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); - value = arguments[ 1 ]; + return scope._nActiveControlInterpolants; - } + } + } - this.value = value; + }; - } + }, - Uniform.prototype.clone = function () { + // Memory management for AnimationAction objects - return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); + _isActiveAction: function ( action ) { - }; + var index = action._cacheIndex; + return index !== null && index < this._nActiveActions; - /** - * @author benaadams / https://twitter.com/ben_a_adams - */ + }, - function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { + _addInactiveAction: function ( action, clipUuid, rootUuid ) { - InterleavedBuffer.call( this, array, stride ); + var actions = this._actions, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - this.meshPerAttribute = meshPerAttribute || 1; + if ( actionsForClip === undefined ) { - } + actionsForClip = { - InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), { + knownActions: [ action ], + actionByRoot: {} - constructor: InstancedInterleavedBuffer, + }; - isInstancedInterleavedBuffer: true, + action._byClipCacheIndex = 0; - copy: function ( source ) { + actionsByClip[ clipUuid ] = actionsForClip; - InterleavedBuffer.prototype.copy.call( this, source ); + } else { - this.meshPerAttribute = source.meshPerAttribute; + var knownActions = actionsForClip.knownActions; - return this; + action._byClipCacheIndex = knownActions.length; + knownActions.push( action ); } - } ); - - /** - * @author mrdoob / http://mrdoob.com/ - * @author bhouston / http://clara.io/ - * @author stephomi / http://stephaneginier.com/ - */ - - function Raycaster( origin, direction, near, far ) { + action._cacheIndex = actions.length; + actions.push( action ); - this.ray = new Ray( origin, direction ); - // direction is assumed to be normalized (for accurate distance calculations) - - this.near = near || 0; - this.far = far || Infinity; - this.camera = null; + actionsForClip.actionByRoot[ rootUuid ] = action; - this.params = { - Mesh: {}, - Line: {}, - LOD: {}, - Points: { threshold: 1 }, - Sprite: {} - }; + }, - Object.defineProperties( this.params, { - PointCloud: { - get: function () { + _removeInactiveAction: function ( action ) { - console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); - return this.Points; + var actions = this._actions, + lastInactiveAction = actions[ actions.length - 1 ], + cacheIndex = action._cacheIndex; - } - } - } ); + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - } + action._cacheIndex = null; - function ascSort( a, b ) { - return a.distance - b.distance; + var clipUuid = action._clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ], + knownActionsForClip = actionsForClip.knownActions, - } + lastKnownAction = + knownActionsForClip[ knownActionsForClip.length - 1 ], - function intersectObject( object, raycaster, intersects, recursive ) { + byClipCacheIndex = action._byClipCacheIndex; - if ( object.visible === false ) { return; } + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; + knownActionsForClip.pop(); - object.raycast( raycaster, intersects ); + action._byClipCacheIndex = null; - if ( recursive === true ) { - var children = object.children; + var actionByRoot = actionsForClip.actionByRoot, + rootUuid = ( action._localRoot || this._root ).uuid; - for ( var i = 0, l = children.length; i < l; i ++ ) { + delete actionByRoot[ rootUuid ]; - intersectObject( children[ i ], raycaster, intersects, true ); + if ( knownActionsForClip.length === 0 ) { - } + delete actionsByClip[ clipUuid ]; } - } + this._removeInactiveBindingsForAction( action ); - Object.assign( Raycaster.prototype, { + }, - linePrecision: 1, + _removeInactiveBindingsForAction: function ( action ) { - set: function ( origin, direction ) { + var bindings = action._propertyBindings; + for ( var i = 0, n = bindings.length; i !== n; ++ i ) { - // direction is assumed to be normalized (for accurate distance calculations) + var binding = bindings[ i ]; - this.ray.set( origin, direction ); + if ( -- binding.referenceCount === 0 ) { - }, + this._removeInactiveBinding( binding ); - setFromCamera: function ( coords, camera ) { + } - if ( ( camera && camera.isPerspectiveCamera ) ) { + } - this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); - this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); - this.camera = camera; + }, - } else if ( ( camera && camera.isOrthographicCamera ) ) { + _lendAction: function ( action ) { - this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera - this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); - this.camera = camera; + // [ active actions | inactive actions ] + // [ active actions >| inactive actions ] + // s a + // <-swap-> + // a s - } else { + var actions = this._actions, + prevIndex = action._cacheIndex, - console.error( 'THREE.Raycaster: Unsupported camera type.' ); + lastActiveIndex = this._nActiveActions ++, - } + firstInactiveAction = actions[ lastActiveIndex ]; - }, + action._cacheIndex = lastActiveIndex; + actions[ lastActiveIndex ] = action; - intersectObject: function ( object, recursive, optionalTarget ) { + firstInactiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = firstInactiveAction; - var intersects = optionalTarget || []; + }, - intersectObject( object, this, intersects, recursive ); + _takeBackAction: function ( action ) { - intersects.sort( ascSort ); + // [ active actions | inactive actions ] + // [ active actions |< inactive actions ] + // a s + // <-swap-> + // s a - return intersects; + var actions = this._actions, + prevIndex = action._cacheIndex, - }, + firstInactiveIndex = -- this._nActiveActions, - intersectObjects: function ( objects, recursive, optionalTarget ) { + lastActiveAction = actions[ firstInactiveIndex ]; - var intersects = optionalTarget || []; + action._cacheIndex = firstInactiveIndex; + actions[ firstInactiveIndex ] = action; - if ( Array.isArray( objects ) === false ) { + lastActiveAction._cacheIndex = prevIndex; + actions[ prevIndex ] = lastActiveAction; - console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); - return intersects; + }, - } + // Memory management for PropertyMixer objects - for ( var i = 0, l = objects.length; i < l; i ++ ) { + _addInactiveBinding: function ( binding, rootUuid, trackName ) { - intersectObject( objects[ i ], this, intersects, recursive ); + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - } + bindings = this._bindings; - intersects.sort( ascSort ); + if ( bindingByName === undefined ) { - return intersects; + bindingByName = {}; + bindingsByRoot[ rootUuid ] = bindingByName; } - } ); + bindingByName[ trackName ] = binding; - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system - * - * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. - * The azimuthal angle (theta) is measured from the positive z-axis. - */ + binding._cacheIndex = bindings.length; + bindings.push( binding ); - function Spherical( radius, phi, theta ) { + }, - this.radius = ( radius !== undefined ) ? radius : 1.0; - this.phi = ( phi !== undefined ) ? phi : 0; // polar angle - this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle + _removeInactiveBinding: function ( binding ) { - return this; + var bindings = this._bindings, + propBinding = binding.binding, + rootUuid = propBinding.rootNode.uuid, + trackName = propBinding.path, + bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ], - } + lastInactiveBinding = bindings[ bindings.length - 1 ], + cacheIndex = binding._cacheIndex; - Object.assign( Spherical.prototype, { + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[ cacheIndex ] = lastInactiveBinding; + bindings.pop(); - set: function ( radius, phi, theta ) { + delete bindingByName[ trackName ]; - this.radius = radius; - this.phi = phi; - this.theta = theta; + if ( Object.keys( bindingByName ).length === 0 ) { - return this; + delete bindingsByRoot[ rootUuid ]; - }, + } - clone: function () { + }, - return new this.constructor().copy( this ); + _lendBinding: function ( binding ) { - }, + var bindings = this._bindings, + prevIndex = binding._cacheIndex, - copy: function ( other ) { + lastActiveIndex = this._nActiveBindings ++, - this.radius = other.radius; - this.phi = other.phi; - this.theta = other.theta; + firstInactiveBinding = bindings[ lastActiveIndex ]; - return this; + binding._cacheIndex = lastActiveIndex; + bindings[ lastActiveIndex ] = binding; - }, + firstInactiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = firstInactiveBinding; - // restrict phi to be betwee EPS and PI-EPS - makeSafe: function () { + }, - var EPS = 0.000001; - this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); + _takeBackBinding: function ( binding ) { - return this; + var bindings = this._bindings, + prevIndex = binding._cacheIndex, - }, + firstInactiveIndex = -- this._nActiveBindings, - setFromVector3: function ( v ) { + lastActiveBinding = bindings[ firstInactiveIndex ]; - return this.setFromCartesianCoords( v.x, v.y, v.z ); + binding._cacheIndex = firstInactiveIndex; + bindings[ firstInactiveIndex ] = binding; - }, + lastActiveBinding._cacheIndex = prevIndex; + bindings[ prevIndex ] = lastActiveBinding; - setFromCartesianCoords: function ( x, y, z ) { + }, - this.radius = Math.sqrt( x * x + y * y + z * z ); - if ( this.radius === 0 ) { + // Memory management of Interpolants for weight and time scale - this.theta = 0; - this.phi = 0; + _lendControlInterpolant: function () { - } else { + var interpolants = this._controlInterpolants, + lastActiveIndex = this._nActiveControlInterpolants ++, + interpolant = interpolants[ lastActiveIndex ]; - this.theta = Math.atan2( x, z ); - this.phi = Math.acos( _Math.clamp( y / this.radius, - 1, 1 ) ); + if ( interpolant === undefined ) { - } + interpolant = new LinearInterpolant( + new Float32Array( 2 ), new Float32Array( 2 ), + 1, this._controlInterpolantsResultBuffer ); - return this; + interpolant.__cacheIndex = lastActiveIndex; + interpolants[ lastActiveIndex ] = interpolant; } - } ); + return interpolant; - /** - * @author Mugen87 / https://github.com/Mugen87 - * - * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system - * - */ + }, - function Cylindrical( radius, theta, y ) { + _takeBackControlInterpolant: function ( interpolant ) { - this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane - this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis - this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane + var interpolants = this._controlInterpolants, + prevIndex = interpolant.__cacheIndex, - return this; + firstInactiveIndex = -- this._nActiveControlInterpolants, - } + lastActiveInterpolant = interpolants[ firstInactiveIndex ]; - Object.assign( Cylindrical.prototype, { + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[ firstInactiveIndex ] = interpolant; - set: function ( radius, theta, y ) { + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[ prevIndex ] = lastActiveInterpolant; - this.radius = radius; - this.theta = theta; - this.y = y; + }, - return this; + _controlInterpolantsResultBuffer: new Float32Array( 1 ), - }, + // return an action for a clip optionally using a custom root target + // object (this method allocates a lot of dynamic memory in case a + // previously unknown clip/root combination is specified) + clipAction: function ( clip, optionalRoot, blendMode ) { - clone: function () { + var root = optionalRoot || this._root, + rootUuid = root.uuid, - return new this.constructor().copy( this ); + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - }, + clipUuid = clipObject !== null ? clipObject.uuid : clip, - copy: function ( other ) { + actionsForClip = this._actionsByClip[ clipUuid ], + prototypeAction = null; - this.radius = other.radius; - this.theta = other.theta; - this.y = other.y; + if ( blendMode === undefined ) { - return this; + if ( clipObject !== null ) { - }, + blendMode = clipObject.blendMode; - setFromVector3: function ( v ) { + } else { - return this.setFromCartesianCoords( v.x, v.y, v.z ); + blendMode = NormalAnimationBlendMode; - }, + } - setFromCartesianCoords: function ( x, y, z ) { + } - this.radius = Math.sqrt( x * x + z * z ); - this.theta = Math.atan2( x, z ); - this.y = y; + if ( actionsForClip !== undefined ) { - return this; + var existingAction = + actionsForClip.actionByRoot[ rootUuid ]; - } + if ( existingAction !== undefined && existingAction.blendMode === blendMode ) { - } ); + return existingAction; - /** - * @author bhouston / http://clara.io - */ + } - var _vector$6 = new Vector2(); + // we know the clip, so we don't have to parse all + // the bindings again but can just copy + prototypeAction = actionsForClip.knownActions[ 0 ]; - function Box2( min, max ) { + // also, take the clip from the prototype action + if ( clipObject === null ) + clipObject = prototypeAction._clip; - this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); + } - } + // clip must be known when specified via string + if ( clipObject === null ) return null; - Object.assign( Box2.prototype, { + // allocate all resources required to run it + var newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode ); - set: function ( min, max ) { + this._bindAction( newAction, prototypeAction ); - this.min.copy( min ); - this.max.copy( max ); + // and make the action known to the memory manager + this._addInactiveAction( newAction, clipUuid, rootUuid ); - return this; + return newAction; - }, + }, - setFromPoints: function ( points ) { + // get an existing action + existingAction: function ( clip, optionalRoot ) { - this.makeEmpty(); + var root = optionalRoot || this._root, + rootUuid = root.uuid, - for ( var i = 0, il = points.length; i < il; i ++ ) { + clipObject = typeof clip === 'string' ? + AnimationClip.findByName( root, clip ) : clip, - this.expandByPoint( points[ i ] ); + clipUuid = clipObject ? clipObject.uuid : clip, - } + actionsForClip = this._actionsByClip[ clipUuid ]; - return this; + if ( actionsForClip !== undefined ) { - }, + return actionsForClip.actionByRoot[ rootUuid ] || null; - setFromCenterAndSize: function ( center, size ) { + } - var halfSize = _vector$6.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + return null; - return this; + }, - }, + // deactivates all previously scheduled actions + stopAllAction: function () { - clone: function () { + var actions = this._actions, + nActions = this._nActiveActions; - return new this.constructor().copy( this ); + for ( var i = nActions - 1; i >= 0; -- i ) { - }, + actions[ i ].stop(); - copy: function ( box ) { + } - this.min.copy( box.min ); - this.max.copy( box.max ); + return this; - return this; + }, - }, + // advance the time and update apply the animation + update: function ( deltaTime ) { - makeEmpty: function () { + deltaTime *= this.timeScale; - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; + var actions = this._actions, + nActions = this._nActiveActions, - return this; + time = this.time += deltaTime, + timeDirection = Math.sign( deltaTime ), - }, + accuIndex = this._accuIndex ^= 1; - isEmpty: function () { + // run active actions - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + for ( var i = 0; i !== nActions; ++ i ) { - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + var action = actions[ i ]; - }, + action._update( time, deltaTime, timeDirection, accuIndex ); - getCenter: function ( target ) { + } - if ( target === undefined ) { + // update scene graph - console.warn( 'THREE.Box2: .getCenter() target is now required' ); - target = new Vector2(); + var bindings = this._bindings, + nBindings = this._nActiveBindings; - } + for ( var i = 0; i !== nBindings; ++ i ) { - return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + bindings[ i ].apply( accuIndex ); - }, + } - getSize: function ( target ) { + return this; - if ( target === undefined ) { + }, - console.warn( 'THREE.Box2: .getSize() target is now required' ); - target = new Vector2(); + // Allows you to seek to a specific time in an animation. + setTime: function ( timeInSeconds ) { - } + this.time = 0; // Zero out time attribute for AnimationMixer object; + for ( var i = 0; i < this._actions.length; i ++ ) { - return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. - }, + } - expandByPoint: function ( point ) { + return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. - this.min.min( point ); - this.max.max( point ); + }, - return this; + // return this mixer's root target object + getRoot: function () { - }, + return this._root; - expandByVector: function ( vector ) { + }, - this.min.sub( vector ); - this.max.add( vector ); + // free all resources specific to a particular clip + uncacheClip: function ( clip ) { - return this; + var actions = this._actions, + clipUuid = clip.uuid, + actionsByClip = this._actionsByClip, + actionsForClip = actionsByClip[ clipUuid ]; - }, + if ( actionsForClip !== undefined ) { - expandByScalar: function ( scalar ) { + // note: just calling _removeInactiveAction would mess up the + // iteration state and also require updating the state we can + // just throw away - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + var actionsToRemove = actionsForClip.knownActions; - return this; + for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { - }, + var action = actionsToRemove[ i ]; - containsPoint: function ( point ) { + this._deactivateAction( action ); - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; + var cacheIndex = action._cacheIndex, + lastInactiveAction = actions[ actions.length - 1 ]; - }, + action._cacheIndex = null; + action._byClipCacheIndex = null; - containsBox: function ( box ) { + lastInactiveAction._cacheIndex = cacheIndex; + actions[ cacheIndex ] = lastInactiveAction; + actions.pop(); - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y; + this._removeInactiveBindingsForAction( action ); - }, + } - getParameter: function ( point, target ) { + delete actionsByClip[ clipUuid ]; - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + } - if ( target === undefined ) { + }, - console.warn( 'THREE.Box2: .getParameter() target is now required' ); - target = new Vector2(); + // free all resources specific to a particular root target object + uncacheRoot: function ( root ) { - } + var rootUuid = root.uuid, + actionsByClip = this._actionsByClip; - return target.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); + for ( var clipUuid in actionsByClip ) { - }, + var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, + action = actionByRoot[ rootUuid ]; - intersectsBox: function ( box ) { + if ( action !== undefined ) { + + this._deactivateAction( action ); + this._removeInactiveAction( action ); - // using 4 splitting planes to rule out intersections + } - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + } - }, + var bindingsByRoot = this._bindingsByRootAndName, + bindingByName = bindingsByRoot[ rootUuid ]; - clampPoint: function ( point, target ) { + if ( bindingByName !== undefined ) { - if ( target === undefined ) { + for ( var trackName in bindingByName ) { - console.warn( 'THREE.Box2: .clampPoint() target is now required' ); - target = new Vector2(); + var binding = bindingByName[ trackName ]; + binding.restoreOriginalState(); + this._removeInactiveBinding( binding ); } - return target.copy( point ).clamp( this.min, this.max ); - - }, + } - distanceToPoint: function ( point ) { + }, - var clampedPoint = _vector$6.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + // remove a targeted clip from the cache + uncacheAction: function ( clip, optionalRoot ) { - }, + var action = this.existingAction( clip, optionalRoot ); - intersect: function ( box ) { + if ( action !== null ) { - this.min.max( box.min ); - this.max.min( box.max ); + this._deactivateAction( action ); + this._removeInactiveAction( action ); - return this; + } - }, + } - union: function ( box ) { +} ); - this.min.min( box.min ); - this.max.max( box.max ); +/** + * @author mrdoob / http://mrdoob.com/ + */ - return this; +function Uniform( value ) { - }, + if ( typeof value === 'string' ) { - translate: function ( offset ) { + console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); + value = arguments[ 1 ]; - this.min.add( offset ); - this.max.add( offset ); + } - return this; + this.value = value; - }, +} - equals: function ( box ) { +Uniform.prototype.clone = function () { - return box.min.equals( this.min ) && box.max.equals( this.max ); + return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); - } +}; - } ); +/** + * @author benaadams / https://twitter.com/ben_a_adams + */ - /** - * @author bhouston / http://clara.io - */ +function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { - var _startP = new Vector3(); - var _startEnd = new Vector3(); + InterleavedBuffer.call( this, array, stride ); - function Line3( start, end ) { + this.meshPerAttribute = meshPerAttribute || 1; - this.start = ( start !== undefined ) ? start : new Vector3(); - this.end = ( end !== undefined ) ? end : new Vector3(); +} - } +InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), { - Object.assign( Line3.prototype, { + constructor: InstancedInterleavedBuffer, - set: function ( start, end ) { + isInstancedInterleavedBuffer: true, - this.start.copy( start ); - this.end.copy( end ); + copy: function ( source ) { - return this; + InterleavedBuffer.prototype.copy.call( this, source ); - }, + this.meshPerAttribute = source.meshPerAttribute; - clone: function () { + return this; - return new this.constructor().copy( this ); + } - }, +} ); - copy: function ( line ) { +/** + * @author mrdoob / http://mrdoob.com/ + * @author bhouston / http://clara.io/ + * @author stephomi / http://stephaneginier.com/ + */ - this.start.copy( line.start ); - this.end.copy( line.end ); +function Raycaster( origin, direction, near, far ) { - return this; + this.ray = new Ray( origin, direction ); + // direction is assumed to be normalized (for accurate distance calculations) - }, + this.near = near || 0; + this.far = far || Infinity; + this.camera = null; + this.layers = new Layers(); - getCenter: function ( target ) { + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; - if ( target === undefined ) { + Object.defineProperties( this.params, { + PointCloud: { + get: function () { - console.warn( 'THREE.Line3: .getCenter() target is now required' ); - target = new Vector3(); + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); + return this.Points; } + } + } ); - return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); +} - }, +function ascSort( a, b ) { - delta: function ( target ) { + return a.distance - b.distance; - if ( target === undefined ) { +} - console.warn( 'THREE.Line3: .delta() target is now required' ); - target = new Vector3(); +function intersectObject( object, raycaster, intersects, recursive ) { - } + if ( object.layers.test( raycaster.layers ) ) { - return target.subVectors( this.end, this.start ); + object.raycast( raycaster, intersects ); - }, + } - distanceSq: function () { + if ( recursive === true ) { - return this.start.distanceToSquared( this.end ); + var children = object.children; - }, + for ( var i = 0, l = children.length; i < l; i ++ ) { - distance: function () { + intersectObject( children[ i ], raycaster, intersects, true ); - return this.start.distanceTo( this.end ); + } - }, + } - at: function ( t, target ) { +} - if ( target === undefined ) { +Object.assign( Raycaster.prototype, { - console.warn( 'THREE.Line3: .at() target is now required' ); - target = new Vector3(); + set: function ( origin, direction ) { - } + // direction is assumed to be normalized (for accurate distance calculations) - return this.delta( target ).multiplyScalar( t ).add( this.start ); + this.ray.set( origin, direction ); - }, + }, - closestPointToPointParameter: function ( point, clampToLine ) { + setFromCamera: function ( coords, camera ) { - _startP.subVectors( point, this.start ); - _startEnd.subVectors( this.end, this.start ); + if ( ( camera && camera.isPerspectiveCamera ) ) { - var startEnd2 = _startEnd.dot( _startEnd ); - var startEnd_startP = _startEnd.dot( _startP ); + this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); + this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); + this.camera = camera; - var t = startEnd_startP / startEnd2; + } else if ( ( camera && camera.isOrthographicCamera ) ) { - if ( clampToLine ) { + this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera + this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); + this.camera = camera; - t = _Math.clamp( t, 0, 1 ); + } else { - } + console.error( 'THREE.Raycaster: Unsupported camera type.' ); - return t; + } - }, + }, - closestPointToPoint: function ( point, clampToLine, target ) { + intersectObject: function ( object, recursive, optionalTarget ) { - var t = this.closestPointToPointParameter( point, clampToLine ); + var intersects = optionalTarget || []; - if ( target === undefined ) { + intersectObject( object, this, intersects, recursive ); - console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); - target = new Vector3(); + intersects.sort( ascSort ); - } + return intersects; - return this.delta( target ).multiplyScalar( t ).add( this.start ); + }, - }, + intersectObjects: function ( objects, recursive, optionalTarget ) { - applyMatrix4: function ( matrix ) { + var intersects = optionalTarget || []; - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + if ( Array.isArray( objects ) === false ) { - return this; + console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); + return intersects; - }, + } - equals: function ( line ) { + for ( var i = 0, l = objects.length; i < l; i ++ ) { - return line.start.equals( this.start ) && line.end.equals( this.end ); + intersectObject( objects[ i ], this, intersects, recursive ); } - } ); + intersects.sort( ascSort ); - /** - * @author alteredq / http://alteredqualia.com/ - */ + return intersects; - function ImmediateRenderObject( material ) { + } - Object3D.call( this ); +} ); - this.material = material; - this.render = function ( /* renderCallback */ ) {}; +/** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system + * + * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. + * The azimuthal angle (theta) is measured from the positive z-axis. + */ - } +function Spherical( radius, phi, theta ) { - ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); - ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; + this.radius = ( radius !== undefined ) ? radius : 1.0; + this.phi = ( phi !== undefined ) ? phi : 0; // polar angle + this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle - ImmediateRenderObject.prototype.isImmediateRenderObject = true; + return this; - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ +} - var _v1$5 = new Vector3(); - var _v2$3 = new Vector3(); - var _normalMatrix$1 = new Matrix3(); - var _keys = [ 'a', 'b', 'c' ]; +Object.assign( Spherical.prototype, { - function VertexNormalsHelper( object, size, hex, linewidth ) { + set: function ( radius, phi, theta ) { - this.object = object; + this.radius = radius; + this.phi = phi; + this.theta = theta; - this.size = ( size !== undefined ) ? size : 1; + return this; - var color = ( hex !== undefined ) ? hex : 0xff0000; + }, - var width = ( linewidth !== undefined ) ? linewidth : 1; + clone: function () { - // + return new this.constructor().copy( this ); - var nNormals = 0; + }, - var objGeometry = this.object.geometry; + copy: function ( other ) { - if ( objGeometry && objGeometry.isGeometry ) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; - nNormals = objGeometry.faces.length * 3; + return this; - } else if ( objGeometry && objGeometry.isBufferGeometry ) { + }, - nNormals = objGeometry.attributes.normal.count; + // restrict phi to be betwee EPS and PI-EPS + makeSafe: function () { - } + var EPS = 0.000001; + this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); - // + return this; - var geometry = new BufferGeometry(); + }, - var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 ); + setFromVector3: function ( v ) { - geometry.setAttribute( 'position', positions ); + return this.setFromCartesianCoords( v.x, v.y, v.z ); - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + }, - // + setFromCartesianCoords: function ( x, y, z ) { - this.matrixAutoUpdate = false; + this.radius = Math.sqrt( x * x + y * y + z * z ); - this.update(); + if ( this.radius === 0 ) { - } + this.theta = 0; + this.phi = 0; - VertexNormalsHelper.prototype = Object.create( LineSegments.prototype ); - VertexNormalsHelper.prototype.constructor = VertexNormalsHelper; + } else { - VertexNormalsHelper.prototype.update = function () { + this.theta = Math.atan2( x, z ); + this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); - this.object.updateMatrixWorld( true ); + } - _normalMatrix$1.getNormalMatrix( this.object.matrixWorld ); + return this; - var matrixWorld = this.object.matrixWorld; + } - var position = this.geometry.attributes.position; +} ); - // +/** + * @author Mugen87 / https://github.com/Mugen87 + * + * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system + * + */ - var objGeometry = this.object.geometry; +function Cylindrical( radius, theta, y ) { - if ( objGeometry && objGeometry.isGeometry ) { + this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane + this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis + this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane - var vertices = objGeometry.vertices; + return this; - var faces = objGeometry.faces; +} - var idx = 0; +Object.assign( Cylindrical.prototype, { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + set: function ( radius, theta, y ) { - var face = faces[ i ]; + this.radius = radius; + this.theta = theta; + this.y = y; - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + return this; - var vertex = vertices[ face[ _keys[ j ] ] ]; + }, - var normal = face.vertexNormals[ j ]; + clone: function () { - _v1$5.copy( vertex ).applyMatrix4( matrixWorld ); + return new this.constructor().copy( this ); - _v2$3.copy( normal ).applyMatrix3( _normalMatrix$1 ).normalize().multiplyScalar( this.size ).add( _v1$5 ); + }, - position.setXYZ( idx, _v1$5.x, _v1$5.y, _v1$5.z ); + copy: function ( other ) { - idx = idx + 1; + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; - position.setXYZ( idx, _v2$3.x, _v2$3.y, _v2$3.z ); + return this; - idx = idx + 1; + }, - } + setFromVector3: function ( v ) { - } + return this.setFromCartesianCoords( v.x, v.y, v.z ); - } else if ( objGeometry && objGeometry.isBufferGeometry ) { + }, - var objPos = objGeometry.attributes.position; + setFromCartesianCoords: function ( x, y, z ) { - var objNorm = objGeometry.attributes.normal; + this.radius = Math.sqrt( x * x + z * z ); + this.theta = Math.atan2( x, z ); + this.y = y; - var idx = 0; + return this; - // for simplicity, ignore index and drawcalls, and render every normal + } - for ( var j = 0, jl = objPos.count; j < jl; j ++ ) { +} ); - _v1$5.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld ); +/** + * @author bhouston / http://clara.io + */ - _v2$3.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) ); +var _vector$7 = new Vector2(); - _v2$3.applyMatrix3( _normalMatrix$1 ).normalize().multiplyScalar( this.size ).add( _v1$5 ); +function Box2( min, max ) { - position.setXYZ( idx, _v1$5.x, _v1$5.y, _v1$5.z ); + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - idx = idx + 1; +} - position.setXYZ( idx, _v2$3.x, _v2$3.y, _v2$3.z ); +Object.assign( Box2.prototype, { - idx = idx + 1; + set: function ( min, max ) { - } + this.min.copy( min ); + this.max.copy( max ); - } + return this; - position.needsUpdate = true; + }, - }; + setFromPoints: function ( points ) { - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + this.makeEmpty(); - var _vector$7 = new Vector3(); + for ( var i = 0, il = points.length; i < il; i ++ ) { - function SpotLightHelper( light, color ) { + this.expandByPoint( points[ i ] ); - Object3D.call( this ); + } - this.light = light; - this.light.updateMatrixWorld(); + return this; - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + }, - this.color = color; + setFromCenterAndSize: function ( center, size ) { - var geometry = new BufferGeometry(); + var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); - var positions = [ - 0, 0, 0, 0, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, - 1, 0, 1, - 0, 0, 0, 0, 1, 1, - 0, 0, 0, 0, - 1, 1 - ]; + return this; - for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { + }, - var p1 = ( i / l ) * Math.PI * 2; - var p2 = ( j / l ) * Math.PI * 2; + clone: function () { - positions.push( - Math.cos( p1 ), Math.sin( p1 ), 1, - Math.cos( p2 ), Math.sin( p2 ), 1 - ); + return new this.constructor().copy( this ); - } + }, - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + copy: function ( box ) { - var material = new LineBasicMaterial( { fog: false } ); + this.min.copy( box.min ); + this.max.copy( box.max ); - this.cone = new LineSegments( geometry, material ); - this.add( this.cone ); + return this; - this.update(); + }, - } + makeEmpty: function () { - SpotLightHelper.prototype = Object.create( Object3D.prototype ); - SpotLightHelper.prototype.constructor = SpotLightHelper; + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; - SpotLightHelper.prototype.dispose = function () { + return this; - this.cone.geometry.dispose(); - this.cone.material.dispose(); + }, - }; + isEmpty: function () { - SpotLightHelper.prototype.update = function () { + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - this.light.updateMatrixWorld(); + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - var coneLength = this.light.distance ? this.light.distance : 1000; - var coneWidth = coneLength * Math.tan( this.light.angle ); + }, - this.cone.scale.set( coneWidth, coneWidth, coneLength ); + getCenter: function ( target ) { - _vector$7.setFromMatrixPosition( this.light.target.matrixWorld ); + if ( target === undefined ) { - this.cone.lookAt( _vector$7 ); + console.warn( 'THREE.Box2: .getCenter() target is now required' ); + target = new Vector2(); - if ( this.color !== undefined ) { + } - this.cone.material.color.set( this.color ); + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - } else { + }, + + getSize: function ( target ) { - this.cone.material.color.copy( this.light.color ); + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .getSize() target is now required' ); + target = new Vector2(); } - }; + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); - /** - * @author Sean Griffin / http://twitter.com/sgrif - * @author Michael Guerrero / http://realitymeltdown.com - * @author mrdoob / http://mrdoob.com/ - * @author ikerr / http://verold.com - * @author Mugen87 / https://github.com/Mugen87 - */ + }, - var _vector$8 = new Vector3(); - var _boneMatrix = new Matrix4(); - var _matrixWorldInv = new Matrix4(); + expandByPoint: function ( point ) { - function getBoneList( object ) { + this.min.min( point ); + this.max.max( point ); - var boneList = []; + return this; - if ( object && object.isBone ) { + }, - boneList.push( object ); + expandByVector: function ( vector ) { - } + this.min.sub( vector ); + this.max.add( vector ); - for ( var i = 0; i < object.children.length; i ++ ) { + return this; - boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); + }, - } + expandByScalar: function ( scalar ) { - return boneList; + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - } + return this; - function SkeletonHelper( object ) { + }, - var bones = getBoneList( object ); + containsPoint: function ( point ) { - var geometry = new BufferGeometry(); + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; - var vertices = []; - var colors = []; + }, - var color1 = new Color( 0, 0, 1 ); - var color2 = new Color( 0, 1, 0 ); + containsBox: function ( box ) { - for ( var i = 0; i < bones.length; i ++ ) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; - var bone = bones[ i ]; + }, - if ( bone.parent && bone.parent.isBone ) { + getParameter: function ( point, target ) { - vertices.push( 0, 0, 0 ); - vertices.push( 0, 0, 0 ); - colors.push( color1.r, color1.g, color1.b ); - colors.push( color2.r, color2.g, color2.b ); + // This can potentially have a divide by zero if the box + // has a size dimension of 0. - } + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .getParameter() target is now required' ); + target = new Vector2(); } - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); - var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); + }, - LineSegments.call( this, geometry, material ); + intersectsBox: function ( box ) { - this.root = object; - this.bones = bones; + // using 4 splitting planes to rule out intersections - this.matrix = object.matrixWorld; - this.matrixAutoUpdate = false; + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; - } + }, - SkeletonHelper.prototype = Object.create( LineSegments.prototype ); - SkeletonHelper.prototype.constructor = SkeletonHelper; + clampPoint: function ( point, target ) { - SkeletonHelper.prototype.updateMatrixWorld = function ( force ) { + if ( target === undefined ) { - var bones = this.bones; + console.warn( 'THREE.Box2: .clampPoint() target is now required' ); + target = new Vector2(); - var geometry = this.geometry; - var position = geometry.getAttribute( 'position' ); + } - _matrixWorldInv.getInverse( this.root.matrixWorld ); + return target.copy( point ).clamp( this.min, this.max ); - for ( var i = 0, j = 0; i < bones.length; i ++ ) { + }, - var bone = bones[ i ]; + distanceToPoint: function ( point ) { - if ( bone.parent && bone.parent.isBone ) { + var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); - _vector$8.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j, _vector$8.x, _vector$8.y, _vector$8.z ); + }, - _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); - _vector$8.setFromMatrixPosition( _boneMatrix ); - position.setXYZ( j + 1, _vector$8.x, _vector$8.y, _vector$8.z ); + intersect: function ( box ) { - j += 2; + this.min.max( box.min ); + this.max.min( box.max ); - } + return this; - } + }, - geometry.getAttribute( 'position' ).needsUpdate = true; + union: function ( box ) { - Object3D.prototype.updateMatrixWorld.call( this, force ); + this.min.min( box.min ); + this.max.max( box.max ); - }; + return this; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + }, - function PointLightHelper( light, sphereSize, color ) { + translate: function ( offset ) { - this.light = light; - this.light.updateMatrixWorld(); + this.min.add( offset ); + this.max.add( offset ); + + return this; - this.color = color; + }, - var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); - var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); + equals: function ( box ) { - Mesh.call( this, geometry, material ); + return box.min.equals( this.min ) && box.max.equals( this.max ); - this.matrix = this.light.matrixWorld; - this.matrixAutoUpdate = false; + } - this.update(); +} ); +/** + * @author bhouston / http://clara.io + */ - /* - var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 ); - var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); +var _startP = new Vector3(); +var _startEnd = new Vector3(); - this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); - this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); +function Line3( start, end ) { - var d = light.distance; + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - if ( d === 0.0 ) { +} - this.lightDistance.visible = false; +Object.assign( Line3.prototype, { - } else { + set: function ( start, end ) { - this.lightDistance.scale.set( d, d, d ); + this.start.copy( start ); + this.end.copy( end ); - } + return this; - this.add( this.lightDistance ); - */ + }, - } + clone: function () { - PointLightHelper.prototype = Object.create( Mesh.prototype ); - PointLightHelper.prototype.constructor = PointLightHelper; + return new this.constructor().copy( this ); - PointLightHelper.prototype.dispose = function () { + }, - this.geometry.dispose(); - this.material.dispose(); + copy: function ( line ) { - }; + this.start.copy( line.start ); + this.end.copy( line.end ); - PointLightHelper.prototype.update = function () { + return this; - if ( this.color !== undefined ) { + }, - this.material.color.set( this.color ); + getCenter: function ( target ) { - } else { + if ( target === undefined ) { - this.material.color.copy( this.light.color ); + console.warn( 'THREE.Line3: .getCenter() target is now required' ); + target = new Vector3(); } - /* - var d = this.light.distance; + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - if ( d === 0.0 ) { + }, - this.lightDistance.visible = false; + delta: function ( target ) { - } else { + if ( target === undefined ) { - this.lightDistance.visible = true; - this.lightDistance.scale.set( d, d, d ); + console.warn( 'THREE.Line3: .delta() target is now required' ); + target = new Vector3(); } - */ - }; + return target.subVectors( this.end, this.start ); - /** - * @author abelnation / http://github.com/abelnation - * @author Mugen87 / http://github.com/Mugen87 - * @author WestLangley / http://github.com/WestLangley - * - * This helper must be added as a child of the light - */ + }, - function RectAreaLightHelper( light, color ) { + distanceSq: function () { - this.type = 'RectAreaLightHelper'; + return this.start.distanceToSquared( this.end ); - this.light = light; + }, - this.color = color; // optional hardwired color for the helper + distance: function () { - var positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ]; + return this.start.distanceTo( this.end ); - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - geometry.computeBoundingSphere(); + }, - var material = new LineBasicMaterial( { fog: false } ); + at: function ( t, target ) { - Line.call( this, geometry, material ); + if ( target === undefined ) { - // + console.warn( 'THREE.Line3: .at() target is now required' ); + target = new Vector3(); - var positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ]; + } - var geometry2 = new BufferGeometry(); - geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); - geometry2.computeBoundingSphere(); + return this.delta( target ).multiplyScalar( t ).add( this.start ); - this.add( new Mesh( geometry2, new MeshBasicMaterial( { side: BackSide, fog: false } ) ) ); + }, - this.update(); + closestPointToPointParameter: function ( point, clampToLine ) { - } + _startP.subVectors( point, this.start ); + _startEnd.subVectors( this.end, this.start ); - RectAreaLightHelper.prototype = Object.create( Line.prototype ); - RectAreaLightHelper.prototype.constructor = RectAreaLightHelper; + var startEnd2 = _startEnd.dot( _startEnd ); + var startEnd_startP = _startEnd.dot( _startP ); - RectAreaLightHelper.prototype.update = function () { + var t = startEnd_startP / startEnd2; - this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 ); + if ( clampToLine ) { - if ( this.color !== undefined ) { + t = MathUtils.clamp( t, 0, 1 ); - this.material.color.set( this.color ); - this.children[ 0 ].material.color.set( this.color ); + } - } else { + return t; - this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity ); + }, - // prevent hue shift - var c = this.material.color; - var max = Math.max( c.r, c.g, c.b ); - if ( max > 1 ) { c.multiplyScalar( 1 / max ); } + closestPointToPoint: function ( point, clampToLine, target ) { - this.children[ 0 ].material.color.copy( this.material.color ); + var t = this.closestPointToPointParameter( point, clampToLine ); - } + if ( target === undefined ) { - }; + console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); + target = new Vector3(); - RectAreaLightHelper.prototype.dispose = function () { + } - this.geometry.dispose(); - this.material.dispose(); - this.children[ 0 ].geometry.dispose(); - this.children[ 0 ].material.dispose(); + return this.delta( target ).multiplyScalar( t ).add( this.start ); - }; + }, - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + applyMatrix4: function ( matrix ) { - var _vector$9 = new Vector3(); - var _color1 = new Color(); - var _color2 = new Color(); + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - function HemisphereLightHelper( light, size, color ) { + return this; - Object3D.call( this ); + }, - this.light = light; - this.light.updateMatrixWorld(); + equals: function ( line ) { - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; + return line.start.equals( this.start ) && line.end.equals( this.end ); - this.color = color; + } - var geometry = new OctahedronBufferGeometry( size ); - geometry.rotateY( Math.PI * 0.5 ); +} ); - this.material = new MeshBasicMaterial( { wireframe: true, fog: false } ); - if ( this.color === undefined ) { this.material.vertexColors = VertexColors; } +/** + * @author alteredq / http://alteredqualia.com/ + */ - var position = geometry.getAttribute( 'position' ); - var colors = new Float32Array( position.count * 3 ); +function ImmediateRenderObject( material ) { - geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); + Object3D.call( this ); - this.add( new Mesh( geometry, this.material ) ); + this.material = material; + this.render = function ( /* renderCallback */ ) {}; - this.update(); + this.hasPositions = false; + this.hasNormals = false; + this.hasColors = false; + this.hasUvs = false; - } + this.positionArray = null; + this.normalArray = null; + this.colorArray = null; + this.uvArray = null; - HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); - HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; + this.count = 0; - HemisphereLightHelper.prototype.dispose = function () { +} - this.children[ 0 ].geometry.dispose(); - this.children[ 0 ].material.dispose(); +ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); +ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; - }; +ImmediateRenderObject.prototype.isImmediateRenderObject = true; - HemisphereLightHelper.prototype.update = function () { +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - var mesh = this.children[ 0 ]; +var _vector$8 = new Vector3(); - if ( this.color !== undefined ) { +function SpotLightHelper( light, color ) { - this.material.color.set( this.color ); + Object3D.call( this ); - } else { + this.light = light; + this.light.updateMatrixWorld(); - var colors = mesh.geometry.getAttribute( 'color' ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - _color1.copy( this.light.color ); - _color2.copy( this.light.groundColor ); + this.color = color; - for ( var i = 0, l = colors.count; i < l; i ++ ) { + var geometry = new BufferGeometry(); - var color = ( i < ( l / 2 ) ) ? _color1 : _color2; + var positions = [ + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, - 1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, - 1, 1 + ]; - colors.setXYZ( i, color.r, color.g, color.b ); + for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { - } + var p1 = ( i / l ) * Math.PI * 2; + var p2 = ( j / l ) * Math.PI * 2; - colors.needsUpdate = true; + positions.push( + Math.cos( p1 ), Math.sin( p1 ), 1, + Math.cos( p2 ), Math.sin( p2 ), 1 + ); - } + } - mesh.lookAt( _vector$9.setFromMatrixPosition( this.light.matrixWorld ).negate() ); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - }; + var material = new LineBasicMaterial( { fog: false, toneMapped: false } ); - /** - * @author WestLangley / http://github.com/WestLangley - */ + this.cone = new LineSegments( geometry, material ); + this.add( this.cone ); - function LightProbeHelper( lightProbe, size ) { + this.update(); - this.lightProbe = lightProbe; +} - this.size = size; +SpotLightHelper.prototype = Object.create( Object3D.prototype ); +SpotLightHelper.prototype.constructor = SpotLightHelper; - var defines = {}; - defines[ 'GAMMA_OUTPUT' ] = ""; +SpotLightHelper.prototype.dispose = function () { - // material - var material = new ShaderMaterial( { + this.cone.geometry.dispose(); + this.cone.material.dispose(); - defines: defines, +}; - uniforms: { +SpotLightHelper.prototype.update = function () { - sh: { value: this.lightProbe.sh.coefficients }, // by reference + this.light.updateMatrixWorld(); - intensity: { value: this.lightProbe.intensity } + var coneLength = this.light.distance ? this.light.distance : 1000; + var coneWidth = coneLength * Math.tan( this.light.angle ); - }, + this.cone.scale.set( coneWidth, coneWidth, coneLength ); - vertexShader: [ + _vector$8.setFromMatrixPosition( this.light.target.matrixWorld ); - 'varying vec3 vNormal;', + this.cone.lookAt( _vector$8 ); - 'void main() {', + if ( this.color !== undefined ) { - ' vNormal = normalize( normalMatrix * normal );', + this.cone.material.color.set( this.color ); - ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', + } else { - '}' ].join( '\n' ), + this.cone.material.color.copy( this.light.color ); - fragmentShader: [ + } - '#define RECIPROCAL_PI 0.318309886', +}; - 'vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {', +/** + * @author Sean Griffin / http://twitter.com/sgrif + * @author Michael Guerrero / http://realitymeltdown.com + * @author mrdoob / http://mrdoob.com/ + * @author ikerr / http://verold.com + * @author Mugen87 / https://github.com/Mugen87 + */ - ' // matrix is assumed to be orthogonal', +var _vector$9 = new Vector3(); +var _boneMatrix = new Matrix4(); +var _matrixWorldInv = new Matrix4(); - ' return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );', +function getBoneList( object ) { - '}', + var boneList = []; - 'vec3 linearToOutput( in vec3 a ) {', + if ( object && object.isBone ) { - ' #ifdef GAMMA_OUTPUT', + boneList.push( object ); - ' return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );', + } - ' #else', + for ( var i = 0; i < object.children.length; i ++ ) { - ' return a;', + boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); - ' #endif', + } - '}', + return boneList; - '// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf', - 'vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {', +} - ' // normal is assumed to have unit length', +function SkeletonHelper( object ) { - ' float x = normal.x, y = normal.y, z = normal.z;', + var bones = getBoneList( object ); - ' // band 0', - ' vec3 result = shCoefficients[ 0 ] * 0.886227;', + var geometry = new BufferGeometry(); - ' // band 1', - ' result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;', - ' result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;', - ' result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;', + var vertices = []; + var colors = []; - ' // band 2', - ' result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;', - ' result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;', - ' result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );', - ' result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;', - ' result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );', + var color1 = new Color( 0, 0, 1 ); + var color2 = new Color( 0, 1, 0 ); - ' return result;', + for ( var i = 0; i < bones.length; i ++ ) { - '}', + var bone = bones[ i ]; - 'uniform vec3 sh[ 9 ]; // sh coefficients', + if ( bone.parent && bone.parent.isBone ) { - 'uniform float intensity; // light probe intensity', + vertices.push( 0, 0, 0 ); + vertices.push( 0, 0, 0 ); + colors.push( color1.r, color1.g, color1.b ); + colors.push( color2.r, color2.g, color2.b ); - 'varying vec3 vNormal;', + } - 'void main() {', + } - ' vec3 normal = normalize( vNormal );', + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - ' vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );', + var material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } ); - ' vec3 irradiance = shGetIrradianceAt( worldNormal, sh );', + LineSegments.call( this, geometry, material ); - ' vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;', + this.type = 'SkeletonHelper'; - ' outgoingLight = linearToOutput( outgoingLight );', + this.root = object; + this.bones = bones; - ' gl_FragColor = vec4( outgoingLight, 1.0 );', + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; - '}' +} - ].join( '\n' ) +SkeletonHelper.prototype = Object.create( LineSegments.prototype ); +SkeletonHelper.prototype.constructor = SkeletonHelper; - } ); +SkeletonHelper.prototype.isSkeletonHelper = true; - var geometry = new SphereBufferGeometry( 1, 32, 16 ); +SkeletonHelper.prototype.updateMatrixWorld = function ( force ) { - Mesh.call( this, geometry, material ); + var bones = this.bones; - this.onBeforeRender(); + var geometry = this.geometry; + var position = geometry.getAttribute( 'position' ); - } + _matrixWorldInv.getInverse( this.root.matrixWorld ); - LightProbeHelper.prototype = Object.create( Mesh.prototype ); - LightProbeHelper.prototype.constructor = LightProbeHelper; + for ( var i = 0, j = 0; i < bones.length; i ++ ) { - LightProbeHelper.prototype.dispose = function () { + var bone = bones[ i ]; - this.geometry.dispose(); - this.material.dispose(); + if ( bone.parent && bone.parent.isBone ) { - }; + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); + _vector$9.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z ); - LightProbeHelper.prototype.onBeforeRender = function () { + _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); + _vector$9.setFromMatrixPosition( _boneMatrix ); + position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z ); - this.position.copy( this.lightProbe.position ); + j += 2; - this.scale.set( 1, 1, 1 ).multiplyScalar( this.size ); + } - this.material.uniforms.intensity.value = this.lightProbe.intensity; + } - }; + geometry.getAttribute( 'position' ).needsUpdate = true; - /** - * @author mrdoob / http://mrdoob.com/ - */ + Object3D.prototype.updateMatrixWorld.call( this, force ); - function GridHelper( size, divisions, color1, color2 ) { +}; - size = size || 10; - divisions = divisions || 10; - color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - var center = divisions / 2; - var step = size / divisions; - var halfSize = size / 2; +function PointLightHelper( light, sphereSize, color ) { - var vertices = [], colors = []; + this.light = light; + this.light.updateMatrixWorld(); - for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { + this.color = color; - vertices.push( - halfSize, 0, k, halfSize, 0, k ); - vertices.push( k, 0, - halfSize, k, 0, halfSize ); + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); + var material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); - var color = i === center ? color1 : color2; + Mesh.call( this, geometry, material ); - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; - color.toArray( colors, j ); j += 3; + this.type = 'PointLightHelper'; - } + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + this.update(); - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); - LineSegments.call( this, geometry, material ); + /* + var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 ); + var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); - } + this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); + this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); - GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), { + var d = light.distance; - constructor: GridHelper, + if ( d === 0.0 ) { - copy: function ( source ) { + this.lightDistance.visible = false; - LineSegments.prototype.copy.call( this, source ); + } else { - this.geometry.copy( source.geometry ); - this.material.copy( source.material ); + this.lightDistance.scale.set( d, d, d ); - return this; + } - }, + this.add( this.lightDistance ); + */ - clone: function () { +} - return new this.constructor().copy( this ); +PointLightHelper.prototype = Object.create( Mesh.prototype ); +PointLightHelper.prototype.constructor = PointLightHelper; - } +PointLightHelper.prototype.dispose = function () { - } ); + this.geometry.dispose(); + this.material.dispose(); - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / http://github.com/Mugen87 - * @author Hectate / http://www.github.com/Hectate - */ +}; - function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) { +PointLightHelper.prototype.update = function () { - radius = radius || 10; - radials = radials || 16; - circles = circles || 8; - divisions = divisions || 64; - color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); - color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); + if ( this.color !== undefined ) { - var vertices = []; - var colors = []; + this.material.color.set( this.color ); - var x, z; - var v, i, j, r, color; + } else { - // create the radials + this.material.color.copy( this.light.color ); - for ( i = 0; i <= radials; i ++ ) { + } - v = ( i / radials ) * ( Math.PI * 2 ); + /* + var d = this.light.distance; - x = Math.sin( v ) * radius; - z = Math.cos( v ) * radius; + if ( d === 0.0 ) { - vertices.push( 0, 0, 0 ); - vertices.push( x, 0, z ); + this.lightDistance.visible = false; - color = ( i & 1 ) ? color1 : color2; + } else { - colors.push( color.r, color.g, color.b ); - colors.push( color.r, color.g, color.b ); + this.lightDistance.visible = true; + this.lightDistance.scale.set( d, d, d ); - } + } + */ - // create the circles +}; - for ( i = 0; i <= circles; i ++ ) { +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - color = ( i & 1 ) ? color1 : color2; +var _vector$a = new Vector3(); +var _color1 = new Color(); +var _color2 = new Color(); - r = radius - ( radius / circles * i ); +function HemisphereLightHelper( light, size, color ) { - for ( j = 0; j < divisions; j ++ ) { + Object3D.call( this ); - // first vertex + this.light = light; + this.light.updateMatrixWorld(); - v = ( j / divisions ) * ( Math.PI * 2 ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - x = Math.sin( v ) * r; - z = Math.cos( v ) * r; + this.color = color; - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + var geometry = new OctahedronBufferGeometry( size ); + geometry.rotateY( Math.PI * 0.5 ); - // second vertex + this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } ); + if ( this.color === undefined ) this.material.vertexColors = true; - v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); + var position = geometry.getAttribute( 'position' ); + var colors = new Float32Array( position.count * 3 ); - x = Math.sin( v ) * r; - z = Math.cos( v ) * r; + geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); - vertices.push( x, 0, z ); - colors.push( color.r, color.g, color.b ); + this.add( new Mesh( geometry, this.material ) ); - } + this.update(); - } +} - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); +HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); +HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); +HemisphereLightHelper.prototype.dispose = function () { - LineSegments.call( this, geometry, material ); + this.children[ 0 ].geometry.dispose(); + this.children[ 0 ].material.dispose(); - } +}; - PolarGridHelper.prototype = Object.create( LineSegments.prototype ); - PolarGridHelper.prototype.constructor = PolarGridHelper; +HemisphereLightHelper.prototype.update = function () { - /** - * @author Mugen87 / http://github.com/Mugen87 - */ + var mesh = this.children[ 0 ]; - function PositionalAudioHelper( audio, range, divisionsInnerAngle, divisionsOuterAngle ) { + if ( this.color !== undefined ) { - this.audio = audio; - this.range = range || 1; - this.divisionsInnerAngle = divisionsInnerAngle || 16; - this.divisionsOuterAngle = divisionsOuterAngle || 2; + this.material.color.set( this.color ); - var geometry = new BufferGeometry(); - var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2; - var positions = new Float32Array( ( divisions * 3 + 3 ) * 3 ); - geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + } else { - var materialInnerAngle = new LineBasicMaterial( { color: 0x00ff00 } ); - var materialOuterAngle = new LineBasicMaterial( { color: 0xffff00 } ); + var colors = mesh.geometry.getAttribute( 'color' ); - Line.call( this, geometry, [ materialOuterAngle, materialInnerAngle ] ); + _color1.copy( this.light.color ); + _color2.copy( this.light.groundColor ); - this.update(); + for ( var i = 0, l = colors.count; i < l; i ++ ) { - } + var color = ( i < ( l / 2 ) ) ? _color1 : _color2; - PositionalAudioHelper.prototype = Object.create( Line.prototype ); - PositionalAudioHelper.prototype.constructor = PositionalAudioHelper; + colors.setXYZ( i, color.r, color.g, color.b ); - PositionalAudioHelper.prototype.update = function () { + } - var audio = this.audio; - var range = this.range; - var divisionsInnerAngle = this.divisionsInnerAngle; - var divisionsOuterAngle = this.divisionsOuterAngle; + colors.needsUpdate = true; - var coneInnerAngle = _Math.degToRad( audio.panner.coneInnerAngle ); - var coneOuterAngle = _Math.degToRad( audio.panner.coneOuterAngle ); + } - var halfConeInnerAngle = coneInnerAngle / 2; - var halfConeOuterAngle = coneOuterAngle / 2; + mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - var start = 0; - var count = 0; - var i, stride; +}; - var geometry = this.geometry; - var positionAttribute = geometry.attributes.position; +/** + * @author mrdoob / http://mrdoob.com/ + */ - geometry.clearGroups(); +function GridHelper( size, divisions, color1, color2 ) { - // + size = size || 10; + divisions = divisions || 10; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); - function generateSegment( from, to, divisions, materialIndex ) { + var center = divisions / 2; + var step = size / divisions; + var halfSize = size / 2; - var step = ( to - from ) / divisions; + var vertices = [], colors = []; - positionAttribute.setXYZ( start, 0, 0, 0 ); - count ++; + for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { - for ( i = from; i < to; i += step ) { + vertices.push( - halfSize, 0, k, halfSize, 0, k ); + vertices.push( k, 0, - halfSize, k, 0, halfSize ); - stride = start + count; + var color = i === center ? color1 : color2; - positionAttribute.setXYZ( stride, Math.sin( i ) * range, 0, Math.cos( i ) * range ); - positionAttribute.setXYZ( stride + 1, Math.sin( Math.min( i + step, to ) ) * range, 0, Math.cos( Math.min( i + step, to ) ) * range ); - positionAttribute.setXYZ( stride + 2, 0, 0, 0 ); + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; + color.toArray( colors, j ); j += 3; - count += 3; + } - } + var geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - geometry.addGroup( start, count, materialIndex ); + var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); - start += count; - count = 0; + LineSegments.call( this, geometry, material ); - } + this.type = 'GridHelper'; - // +} - generateSegment( - halfConeOuterAngle, - halfConeInnerAngle, divisionsOuterAngle, 0 ); - generateSegment( - halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1 ); - generateSegment( halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0 ); +GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), { - // + constructor: GridHelper, - positionAttribute.needsUpdate = true; + copy: function ( source ) { - if ( coneInnerAngle === coneOuterAngle ) { this.material[ 0 ].visible = false; } + LineSegments.prototype.copy.call( this, source ); - }; + this.geometry.copy( source.geometry ); + this.material.copy( source.material ); - PositionalAudioHelper.prototype.dispose = function () { + return this; - this.geometry.dispose(); - this.material[ 0 ].dispose(); - this.material[ 1 ].dispose(); + }, - }; + clone: function () { - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + return new this.constructor().copy( this ); - var _v1$6 = new Vector3(); - var _v2$4 = new Vector3(); - var _normalMatrix$2 = new Matrix3(); + } - function FaceNormalsHelper( object, size, hex, linewidth ) { +} ); - // FaceNormalsHelper only supports THREE.Geometry +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / http://github.com/Mugen87 + * @author Hectate / http://www.github.com/Hectate + */ - this.object = object; +function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) { - this.size = ( size !== undefined ) ? size : 1; + radius = radius || 10; + radials = radials || 16; + circles = circles || 8; + divisions = divisions || 64; + color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); + color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); - var color = ( hex !== undefined ) ? hex : 0xffff00; + var vertices = []; + var colors = []; - var width = ( linewidth !== undefined ) ? linewidth : 1; + var x, z; + var v, i, j, r, color; - // + // create the radials - var nNormals = 0; + for ( i = 0; i <= radials; i ++ ) { - var objGeometry = this.object.geometry; + v = ( i / radials ) * ( Math.PI * 2 ); - if ( objGeometry && objGeometry.isGeometry ) { + x = Math.sin( v ) * radius; + z = Math.cos( v ) * radius; - nNormals = objGeometry.faces.length; + vertices.push( 0, 0, 0 ); + vertices.push( x, 0, z ); - } else { + color = ( i & 1 ) ? color1 : color2; - console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); + colors.push( color.r, color.g, color.b ); + colors.push( color.r, color.g, color.b ); - } + } - // + // create the circles - var geometry = new BufferGeometry(); + for ( i = 0; i <= circles; i ++ ) { - var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 ); + color = ( i & 1 ) ? color1 : color2; - geometry.setAttribute( 'position', positions ); + r = radius - ( radius / circles * i ); - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); + for ( j = 0; j < divisions; j ++ ) { - // + // first vertex - this.matrixAutoUpdate = false; - this.update(); + v = ( j / divisions ) * ( Math.PI * 2 ); - } + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; - FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); - FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); - FaceNormalsHelper.prototype.update = function () { + // second vertex - this.object.updateMatrixWorld( true ); + v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); - _normalMatrix$2.getNormalMatrix( this.object.matrixWorld ); + x = Math.sin( v ) * r; + z = Math.cos( v ) * r; - var matrixWorld = this.object.matrixWorld; + vertices.push( x, 0, z ); + colors.push( color.r, color.g, color.b ); - var position = this.geometry.attributes.position; + } - // + } - var objGeometry = this.object.geometry; + var geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - var vertices = objGeometry.vertices; + var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); - var faces = objGeometry.faces; + LineSegments.call( this, geometry, material ); - var idx = 0; + this.type = 'PolarGridHelper'; - for ( var i = 0, l = faces.length; i < l; i ++ ) { +} - var face = faces[ i ]; +PolarGridHelper.prototype = Object.create( LineSegments.prototype ); +PolarGridHelper.prototype.constructor = PolarGridHelper; - var normal = face.normal; +/** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + */ - _v1$6.copy( vertices[ face.a ] ) - .add( vertices[ face.b ] ) - .add( vertices[ face.c ] ) - .divideScalar( 3 ) - .applyMatrix4( matrixWorld ); +var _v1$5 = new Vector3(); +var _v2$3 = new Vector3(); +var _v3$1 = new Vector3(); - _v2$4.copy( normal ).applyMatrix3( _normalMatrix$2 ).normalize().multiplyScalar( this.size ).add( _v1$6 ); +function DirectionalLightHelper( light, size, color ) { - position.setXYZ( idx, _v1$6.x, _v1$6.y, _v1$6.z ); + Object3D.call( this ); - idx = idx + 1; + this.light = light; + this.light.updateMatrixWorld(); - position.setXYZ( idx, _v2$4.x, _v2$4.y, _v2$4.z ); + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; - idx = idx + 1; + this.color = color; - } + if ( size === undefined ) size = 1; - position.needsUpdate = true; + var geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ + - size, size, 0, + size, size, 0, + size, - size, 0, + - size, - size, 0, + - size, size, 0 + ], 3 ) ); - }; + var material = new LineBasicMaterial( { fog: false, toneMapped: false } ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - */ + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); - var _v1$7 = new Vector3(); - var _v2$5 = new Vector3(); - var _v3$1 = new Vector3(); + geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - function DirectionalLightHelper( light, size, color ) { + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); - Object3D.call( this ); + this.update(); - this.light = light; - this.light.updateMatrixWorld(); +} - this.matrix = light.matrixWorld; - this.matrixAutoUpdate = false; +DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); +DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; - this.color = color; +DirectionalLightHelper.prototype.dispose = function () { - if ( size === undefined ) { size = 1; } + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, - - size, - size, 0, - - size, size, 0 - ], 3 ) ); +}; - var material = new LineBasicMaterial( { fog: false } ); +DirectionalLightHelper.prototype.update = function () { - this.lightPlane = new Line( geometry, material ); - this.add( this.lightPlane ); + _v1$5.setFromMatrixPosition( this.light.matrixWorld ); + _v2$3.setFromMatrixPosition( this.light.target.matrixWorld ); + _v3$1.subVectors( _v2$3, _v1$5 ); - geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); + this.lightPlane.lookAt( _v2$3 ); - this.targetLine = new Line( geometry, material ); - this.add( this.targetLine ); + if ( this.color !== undefined ) { - this.update(); + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); - } + } else { - DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); - DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); - DirectionalLightHelper.prototype.dispose = function () { + } - this.lightPlane.geometry.dispose(); - this.lightPlane.material.dispose(); - this.targetLine.geometry.dispose(); - this.targetLine.material.dispose(); + this.targetLine.lookAt( _v2$3 ); + this.targetLine.scale.z = _v3$1.length(); - }; +}; - DirectionalLightHelper.prototype.update = function () { +/** + * @author alteredq / http://alteredqualia.com/ + * @author Mugen87 / https://github.com/Mugen87 + * + * - shows frustum, line of sight and up of the camera + * - suitable for fast updates + * - based on frustum visualization in lightgl.js shadowmap example + * http://evanw.github.com/lightgl.js/tests/shadowmap.html + */ - _v1$7.setFromMatrixPosition( this.light.matrixWorld ); - _v2$5.setFromMatrixPosition( this.light.target.matrixWorld ); - _v3$1.subVectors( _v2$5, _v1$7 ); +var _vector$b = new Vector3(); +var _camera = new Camera(); - this.lightPlane.lookAt( _v2$5 ); +function CameraHelper( camera ) { - if ( this.color !== undefined ) { + var geometry = new BufferGeometry(); + var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } ); - this.lightPlane.material.color.set( this.color ); - this.targetLine.material.color.set( this.color ); + var vertices = []; + var colors = []; - } else { + var pointMap = {}; - this.lightPlane.material.color.copy( this.light.color ); - this.targetLine.material.color.copy( this.light.color ); + // colors - } + var colorFrustum = new Color( 0xffaa00 ); + var colorCone = new Color( 0xff0000 ); + var colorUp = new Color( 0x00aaff ); + var colorTarget = new Color( 0xffffff ); + var colorCross = new Color( 0x333333 ); - this.targetLine.lookAt( _v2$5 ); - this.targetLine.scale.z = _v3$1.length(); + // near - }; + addLine( 'n1', 'n2', colorFrustum ); + addLine( 'n2', 'n4', colorFrustum ); + addLine( 'n4', 'n3', colorFrustum ); + addLine( 'n3', 'n1', colorFrustum ); - /** - * @author alteredq / http://alteredqualia.com/ - * @author Mugen87 / https://github.com/Mugen87 - * - * - shows frustum, line of sight and up of the camera - * - suitable for fast updates - * - based on frustum visualization in lightgl.js shadowmap example - * http://evanw.github.com/lightgl.js/tests/shadowmap.html - */ + // far - var _vector$a = new Vector3(); - var _camera = new Camera(); + addLine( 'f1', 'f2', colorFrustum ); + addLine( 'f2', 'f4', colorFrustum ); + addLine( 'f4', 'f3', colorFrustum ); + addLine( 'f3', 'f1', colorFrustum ); - function CameraHelper( camera ) { + // sides - var geometry = new BufferGeometry(); - var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); + addLine( 'n1', 'f1', colorFrustum ); + addLine( 'n2', 'f2', colorFrustum ); + addLine( 'n3', 'f3', colorFrustum ); + addLine( 'n4', 'f4', colorFrustum ); - var vertices = []; - var colors = []; + // cone - var pointMap = {}; + addLine( 'p', 'n1', colorCone ); + addLine( 'p', 'n2', colorCone ); + addLine( 'p', 'n3', colorCone ); + addLine( 'p', 'n4', colorCone ); - // colors + // up - var colorFrustum = new Color( 0xffaa00 ); - var colorCone = new Color( 0xff0000 ); - var colorUp = new Color( 0x00aaff ); - var colorTarget = new Color( 0xffffff ); - var colorCross = new Color( 0x333333 ); + addLine( 'u1', 'u2', colorUp ); + addLine( 'u2', 'u3', colorUp ); + addLine( 'u3', 'u1', colorUp ); - // near + // target - addLine( 'n1', 'n2', colorFrustum ); - addLine( 'n2', 'n4', colorFrustum ); - addLine( 'n4', 'n3', colorFrustum ); - addLine( 'n3', 'n1', colorFrustum ); + addLine( 'c', 't', colorTarget ); + addLine( 'p', 'c', colorCross ); - // far + // cross - addLine( 'f1', 'f2', colorFrustum ); - addLine( 'f2', 'f4', colorFrustum ); - addLine( 'f4', 'f3', colorFrustum ); - addLine( 'f3', 'f1', colorFrustum ); + addLine( 'cn1', 'cn2', colorCross ); + addLine( 'cn3', 'cn4', colorCross ); - // sides + addLine( 'cf1', 'cf2', colorCross ); + addLine( 'cf3', 'cf4', colorCross ); - addLine( 'n1', 'f1', colorFrustum ); - addLine( 'n2', 'f2', colorFrustum ); - addLine( 'n3', 'f3', colorFrustum ); - addLine( 'n4', 'f4', colorFrustum ); + function addLine( a, b, color ) { - // cone + addPoint( a, color ); + addPoint( b, color ); - addLine( 'p', 'n1', colorCone ); - addLine( 'p', 'n2', colorCone ); - addLine( 'p', 'n3', colorCone ); - addLine( 'p', 'n4', colorCone ); + } - // up + function addPoint( id, color ) { - addLine( 'u1', 'u2', colorUp ); - addLine( 'u2', 'u3', colorUp ); - addLine( 'u3', 'u1', colorUp ); + vertices.push( 0, 0, 0 ); + colors.push( color.r, color.g, color.b ); - // target + if ( pointMap[ id ] === undefined ) { - addLine( 'c', 't', colorTarget ); - addLine( 'p', 'c', colorCross ); + pointMap[ id ] = []; - // cross + } - addLine( 'cn1', 'cn2', colorCross ); - addLine( 'cn3', 'cn4', colorCross ); + pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); - addLine( 'cf1', 'cf2', colorCross ); - addLine( 'cf3', 'cf4', colorCross ); + } - function addLine( a, b, color ) { + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - addPoint( a, color ); - addPoint( b, color ); + LineSegments.call( this, geometry, material ); - } + this.type = 'CameraHelper'; - function addPoint( id, color ) { + this.camera = camera; + if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix(); - vertices.push( 0, 0, 0 ); - colors.push( color.r, color.g, color.b ); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; - if ( pointMap[ id ] === undefined ) { + this.pointMap = pointMap; - pointMap[ id ] = []; + this.update(); - } +} - pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); +CameraHelper.prototype = Object.create( LineSegments.prototype ); +CameraHelper.prototype.constructor = CameraHelper; - } +CameraHelper.prototype.update = function () { - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + var geometry = this.geometry; + var pointMap = this.pointMap; - LineSegments.call( this, geometry, material ); + var w = 1, h = 1; - this.camera = camera; - if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); } + // we need just camera projection matrix inverse + // world matrix must be identity - this.matrix = camera.matrixWorld; - this.matrixAutoUpdate = false; + _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); - this.pointMap = pointMap; + // center / target - this.update(); + setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); + setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); - } + // near - CameraHelper.prototype = Object.create( LineSegments.prototype ); - CameraHelper.prototype.constructor = CameraHelper; + setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); + setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); + setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); + setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); - CameraHelper.prototype.update = function () { + // far - var geometry = this.geometry; - var pointMap = this.pointMap; + setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); + setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); + setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); + setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); - var w = 1, h = 1; + // up - // we need just camera projection matrix inverse - // world matrix must be identity + setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); - _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); + // cross - // center / target + setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); + setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); + setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); + setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); - setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); - setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); + setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); + setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); + setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); + setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); - // near + geometry.getAttribute( 'position' ).needsUpdate = true; - setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); - setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); - setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); - setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); +}; - // far +function setPoint( point, pointMap, geometry, camera, x, y, z ) { - setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); - setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); - setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); - setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); + _vector$b.set( x, y, z ).unproject( camera ); - // up + var points = pointMap[ point ]; - setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); - setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); - setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); + if ( points !== undefined ) { - // cross + var position = geometry.getAttribute( 'position' ); - setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); - setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); - setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); - setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); + for ( var i = 0, l = points.length; i < l; i ++ ) { - setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); - setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); - setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); - setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); + position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z ); - geometry.getAttribute( 'position' ).needsUpdate = true; + } - }; + } - function setPoint( point, pointMap, geometry, camera, x, y, z ) { +} - _vector$a.set( x, y, z ).unproject( camera ); +/** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / http://github.com/Mugen87 + */ - var points = pointMap[ point ]; +var _box$3 = new Box3(); - if ( points !== undefined ) { +function BoxHelper( object, color ) { - var position = geometry.getAttribute( 'position' ); + this.object = object; - for ( var i = 0, l = points.length; i < l; i ++ ) { + if ( color === undefined ) color = 0xffff00; - position.setXYZ( points[ i ], _vector$a.x, _vector$a.y, _vector$a.z ); + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + var positions = new Float32Array( 8 * 3 ); - } + var geometry = new BufferGeometry(); + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); - } + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - } + this.type = 'BoxHelper'; - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / http://github.com/Mugen87 - */ + this.matrixAutoUpdate = false; - var _box$3 = new Box3(); + this.update(); - function BoxHelper( object, color ) { +} - this.object = object; +BoxHelper.prototype = Object.create( LineSegments.prototype ); +BoxHelper.prototype.constructor = BoxHelper; - if ( color === undefined ) { color = 0xffff00; } +BoxHelper.prototype.update = function ( object ) { - var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); - var positions = new Float32Array( 8 * 3 ); + if ( object !== undefined ) { - var geometry = new BufferGeometry(); - geometry.setIndex( new BufferAttribute( indices, 1 ) ); - geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); + console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + } - this.matrixAutoUpdate = false; + if ( this.object !== undefined ) { - this.update(); + _box$3.setFromObject( this.object ); } - BoxHelper.prototype = Object.create( LineSegments.prototype ); - BoxHelper.prototype.constructor = BoxHelper; + if ( _box$3.isEmpty() ) return; - BoxHelper.prototype.update = function ( object ) { + var min = _box$3.min; + var max = _box$3.max; - if ( object !== undefined ) { + /* + 5____4 + 1/___0/| + | 6__|_7 + 2/___3/ + + 0: max.x, max.y, max.z + 1: min.x, max.y, max.z + 2: min.x, min.y, max.z + 3: max.x, min.y, max.z + 4: max.x, max.y, min.z + 5: min.x, max.y, min.z + 6: min.x, min.y, min.z + 7: max.x, min.y, min.z + */ - console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); + var position = this.geometry.attributes.position; + var array = position.array; - } + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; + array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; + array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; + array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; - if ( this.object !== undefined ) { + position.needsUpdate = true; - _box$3.setFromObject( this.object ); + this.geometry.computeBoundingSphere(); - } - if ( _box$3.isEmpty() ) { return; } +}; - var min = _box$3.min; - var max = _box$3.max; +BoxHelper.prototype.setFromObject = function ( object ) { - /* - 5____4 - 1/___0/| - | 6__|_7 - 2/___3/ - - 0: max.x, max.y, max.z - 1: min.x, max.y, max.z - 2: min.x, min.y, max.z - 3: max.x, min.y, max.z - 4: max.x, max.y, min.z - 5: min.x, max.y, min.z - 6: min.x, min.y, min.z - 7: max.x, min.y, min.z - */ - - var position = this.geometry.attributes.position; - var array = position.array; - - array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; - array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; - array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; - array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; - array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; - array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; - array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; - array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; - - position.needsUpdate = true; - - this.geometry.computeBoundingSphere(); + this.object = object; + this.update(); + return this; - }; +}; - BoxHelper.prototype.setFromObject = function ( object ) { +BoxHelper.prototype.copy = function ( source ) { - this.object = object; - this.update(); + LineSegments.prototype.copy.call( this, source ); - return this; + this.object = source.object; - }; + return this; - BoxHelper.prototype.copy = function ( source ) { +}; - LineSegments.prototype.copy.call( this, source ); +BoxHelper.prototype.clone = function () { - this.object = source.object; + return new this.constructor().copy( this ); - return this; +}; - }; +/** + * @author WestLangley / http://github.com/WestLangley + */ - BoxHelper.prototype.clone = function () { +function Box3Helper( box, color ) { - return new this.constructor().copy( this ); + this.type = 'Box3Helper'; - }; + this.box = box; - /** - * @author WestLangley / http://github.com/WestLangley - */ + color = color || 0xffff00; - function Box3Helper( box, color ) { + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); - this.type = 'Box3Helper'; + var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; - this.box = box; + var geometry = new BufferGeometry(); - color = color || 0xffff00; + geometry.setIndex( new BufferAttribute( indices, 1 ) ); - var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - var geometry = new BufferGeometry(); + this.type = 'Box3Helper'; - geometry.setIndex( new BufferAttribute( indices, 1 ) ); + this.geometry.computeBoundingSphere(); - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); +} - LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); +Box3Helper.prototype = Object.create( LineSegments.prototype ); +Box3Helper.prototype.constructor = Box3Helper; - this.geometry.computeBoundingSphere(); +Box3Helper.prototype.updateMatrixWorld = function ( force ) { - } + var box = this.box; - Box3Helper.prototype = Object.create( LineSegments.prototype ); - Box3Helper.prototype.constructor = Box3Helper; + if ( box.isEmpty() ) return; - Box3Helper.prototype.updateMatrixWorld = function ( force ) { + box.getCenter( this.position ); - var box = this.box; + box.getSize( this.scale ); - if ( box.isEmpty() ) { return; } + this.scale.multiplyScalar( 0.5 ); - box.getCenter( this.position ); + Object3D.prototype.updateMatrixWorld.call( this, force ); - box.getSize( this.scale ); +}; - this.scale.multiplyScalar( 0.5 ); +/** + * @author WestLangley / http://github.com/WestLangley + */ - Object3D.prototype.updateMatrixWorld.call( this, force ); +function PlaneHelper( plane, size, hex ) { - }; + this.plane = plane; - /** - * @author WestLangley / http://github.com/WestLangley - */ + this.size = ( size === undefined ) ? 1 : size; - function PlaneHelper( plane, size, hex ) { + var color = ( hex !== undefined ) ? hex : 0xffff00; - this.type = 'PlaneHelper'; + var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ]; - this.plane = plane; + var geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); - this.size = ( size === undefined ) ? 1 : size; + Line.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); - var color = ( hex !== undefined ) ? hex : 0xffff00; + this.type = 'PlaneHelper'; - var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ]; + // - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); - geometry.computeBoundingSphere(); + var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; - Line.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + var geometry2 = new BufferGeometry(); + geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); - // + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) ); - var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; +} - var geometry2 = new BufferGeometry(); - geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); - geometry2.computeBoundingSphere(); +PlaneHelper.prototype = Object.create( Line.prototype ); +PlaneHelper.prototype.constructor = PlaneHelper; - this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) ); +PlaneHelper.prototype.updateMatrixWorld = function ( force ) { - } + var scale = - this.plane.constant; - PlaneHelper.prototype = Object.create( Line.prototype ); - PlaneHelper.prototype.constructor = PlaneHelper; + if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter - PlaneHelper.prototype.updateMatrixWorld = function ( force ) { + this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); - var scale = - this.plane.constant; + this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here - if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter + this.lookAt( this.plane.normal ); - this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); + Object3D.prototype.updateMatrixWorld.call( this, force ); - this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here +}; - this.lookAt( this.plane.normal ); +/** + * @author WestLangley / http://github.com/WestLangley + * @author zz85 / http://github.com/zz85 + * @author bhouston / http://clara.io + * + * Creates an arrow for visualizing directions + * + * Parameters: + * dir - Vector3 + * origin - Vector3 + * length - Number + * color - color in hex value + * headLength - Number + * headWidth - Number + */ - Object3D.prototype.updateMatrixWorld.call( this, force ); +var _axis = new Vector3(); +var _lineGeometry, _coneGeometry; - }; +function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { - /** - * @author WestLangley / http://github.com/WestLangley - * @author zz85 / http://github.com/zz85 - * @author bhouston / http://clara.io - * - * Creates an arrow for visualizing directions - * - * Parameters: - * dir - Vector3 - * origin - Vector3 - * length - Number - * color - color in hex value - * headLength - Number - * headWidth - Number - */ + // dir is assumed to be normalized - var _axis = new Vector3(); - var _lineGeometry, _coneGeometry; + Object3D.call( this ); - function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { + this.type = 'ArrowHelper'; - // dir is assumed to be normalized + if ( dir === undefined ) dir = new Vector3( 0, 0, 1 ); + if ( origin === undefined ) origin = new Vector3( 0, 0, 0 ); + if ( length === undefined ) length = 1; + if ( color === undefined ) color = 0xffff00; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - Object3D.call( this ); + if ( _lineGeometry === undefined ) { - if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); } - if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); } - if ( length === undefined ) { length = 1; } - if ( color === undefined ) { color = 0xffff00; } - if ( headLength === undefined ) { headLength = 0.2 * length; } - if ( headWidth === undefined ) { headWidth = 0.2 * headLength; } + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); - if ( _lineGeometry === undefined ) { + _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); + _coneGeometry.translate( 0, - 0.5, 0 ); - _lineGeometry = new BufferGeometry(); - _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); + } - _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); - _coneGeometry.translate( 0, - 0.5, 0 ); + this.position.copy( origin ); - } + this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) ); + this.line.matrixAutoUpdate = false; + this.add( this.line ); - this.position.copy( origin ); + this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) ); + this.cone.matrixAutoUpdate = false; + this.add( this.cone ); - this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color } ) ); - this.line.matrixAutoUpdate = false; - this.add( this.line ); + this.setDirection( dir ); + this.setLength( length, headLength, headWidth ); - this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color } ) ); - this.cone.matrixAutoUpdate = false; - this.add( this.cone ); +} - this.setDirection( dir ); - this.setLength( length, headLength, headWidth ); +ArrowHelper.prototype = Object.create( Object3D.prototype ); +ArrowHelper.prototype.constructor = ArrowHelper; - } +ArrowHelper.prototype.setDirection = function ( dir ) { - ArrowHelper.prototype = Object.create( Object3D.prototype ); - ArrowHelper.prototype.constructor = ArrowHelper; + // dir is assumed to be normalized - ArrowHelper.prototype.setDirection = function ( dir ) { + if ( dir.y > 0.99999 ) { - // dir is assumed to be normalized + this.quaternion.set( 0, 0, 0, 1 ); - if ( dir.y > 0.99999 ) { + } else if ( dir.y < - 0.99999 ) { - this.quaternion.set( 0, 0, 0, 1 ); + this.quaternion.set( 1, 0, 0, 0 ); - } else if ( dir.y < - 0.99999 ) { + } else { - this.quaternion.set( 1, 0, 0, 0 ); + _axis.set( dir.z, 0, - dir.x ).normalize(); - } else { + var radians = Math.acos( dir.y ); - _axis.set( dir.z, 0, - dir.x ).normalize(); + this.quaternion.setFromAxisAngle( _axis, radians ); - var radians = Math.acos( dir.y ); + } - this.quaternion.setFromAxisAngle( _axis, radians ); +}; - } +ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { - }; + if ( headLength === undefined ) headLength = 0.2 * length; + if ( headWidth === undefined ) headWidth = 0.2 * headLength; - ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { + this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 + this.line.updateMatrix(); - if ( headLength === undefined ) { headLength = 0.2 * length; } - if ( headWidth === undefined ) { headWidth = 0.2 * headLength; } + this.cone.scale.set( headWidth, headLength, headWidth ); + this.cone.position.y = length; + this.cone.updateMatrix(); - this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 - this.line.updateMatrix(); +}; - this.cone.scale.set( headWidth, headLength, headWidth ); - this.cone.position.y = length; - this.cone.updateMatrix(); +ArrowHelper.prototype.setColor = function ( color ) { - }; + this.line.material.color.set( color ); + this.cone.material.color.set( color ); - ArrowHelper.prototype.setColor = function ( color ) { +}; - this.line.material.color.set( color ); - this.cone.material.color.set( color ); +ArrowHelper.prototype.copy = function ( source ) { - }; + Object3D.prototype.copy.call( this, source, false ); - ArrowHelper.prototype.copy = function ( source ) { + this.line.copy( source.line ); + this.cone.copy( source.cone ); - Object3D.prototype.copy.call( this, source, false ); + return this; - this.line.copy( source.line ); - this.cone.copy( source.cone ); +}; - return this; +ArrowHelper.prototype.clone = function () { - }; + return new this.constructor().copy( this ); - ArrowHelper.prototype.clone = function () { +}; - return new this.constructor().copy( this ); +/** + * @author sroucheray / http://sroucheray.org/ + * @author mrdoob / http://mrdoob.com/ + */ - }; +function AxesHelper( size ) { - /** - * @author sroucheray / http://sroucheray.org/ - * @author mrdoob / http://mrdoob.com/ - */ + size = size || 1; - function AxesHelper( size ) { + var vertices = [ + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size + ]; - size = size || 1; + var colors = [ + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 + ]; - var vertices = [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size - ]; + var geometry = new BufferGeometry(); + geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); - var colors = [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 - ]; + var material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } ); - var geometry = new BufferGeometry(); - geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); + LineSegments.call( this, geometry, material ); - var material = new LineBasicMaterial( { vertexColors: VertexColors } ); + this.type = 'AxesHelper'; - LineSegments.call( this, geometry, material ); +} - } +AxesHelper.prototype = Object.create( LineSegments.prototype ); +AxesHelper.prototype.constructor = AxesHelper; - AxesHelper.prototype = Object.create( LineSegments.prototype ); - AxesHelper.prototype.constructor = AxesHelper; +/** + * @author Emmett Lalish / elalish + * + * This class generates a Prefiltered, Mipmapped Radiance Environment Map + * (PMREM) from a cubeMap environment texture. This allows different levels of + * blur to be quickly accessed based on material roughness. It is packed into a + * special CubeUV format that allows us to perform custom interpolation so that + * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap + * chain, it only goes down to the LOD_MIN level (above), and then creates extra + * even more filtered 'mips' at the same LOD_MIN resolution, associated with + * higher roughness levels. In this way we maintain resolution to smoothly + * interpolate diffuse lighting while limiting sampling computation. + */ - /** - * @author mrdoob / http://mrdoob.com/ - */ +var LOD_MIN = 4; +var LOD_MAX = 8; +var SIZE_MAX = Math.pow( 2, LOD_MAX ); - function Face4( a, b, c, d, normal, color, materialIndex ) { +// The standard deviations (radians) associated with the extra mips. These are +// chosen to approximate a Trowbridge-Reitz distribution function times the +// geometric shadowing function. These sigma values squared must match the +// variance #defines in cube_uv_reflection_fragment.glsl.js. +var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; - console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); - return new Face3( a, b, c, normal, color, materialIndex ); +var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; - } +// The maximum length of the blur for loop. Smaller sigmas will use fewer +// samples and exit early, but not recompile the shader. +var MAX_SAMPLES = 20; - var LineStrip = 0; +var ENCODINGS = { + [ LinearEncoding ]: 0, + [ sRGBEncoding ]: 1, + [ RGBEEncoding ]: 2, + [ RGBM7Encoding ]: 3, + [ RGBM16Encoding ]: 4, + [ RGBDEncoding ]: 5, + [ GammaEncoding ]: 6 +}; - var LinePieces = 1; +var _flatCamera = new OrthographicCamera(); +var { _lodPlanes, _sizeLods, _sigmas } = _createPlanes(); +var _oldTarget = null; - function MeshFaceMaterial( materials ) { +// Golden Ratio +var PHI = ( 1 + Math.sqrt( 5 ) ) / 2; +var INV_PHI = 1 / PHI; - console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); - return materials; +// Vertices of a dodecahedron (except the opposites, which represent the +// same axis), used as axis directions evenly spread on a sphere. +var _axisDirections = [ + new Vector3( 1, 1, 1 ), + new Vector3( - 1, 1, 1 ), + new Vector3( 1, 1, - 1 ), + new Vector3( - 1, 1, - 1 ), + new Vector3( 0, PHI, INV_PHI ), + new Vector3( 0, PHI, - INV_PHI ), + new Vector3( INV_PHI, 0, PHI ), + new Vector3( - INV_PHI, 0, PHI ), + new Vector3( PHI, INV_PHI, 0 ), + new Vector3( - PHI, INV_PHI, 0 ) ]; - } +function PMREMGenerator( renderer ) { - function MultiMaterial( materials ) { + this._renderer = renderer; + this._pingPongRenderTarget = null; - if ( materials === undefined ) { materials = []; } + this._blurMaterial = _getBlurShader( MAX_SAMPLES ); + this._equirectShader = null; + this._cubemapShader = null; - console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); - materials.isMultiMaterial = true; - materials.materials = materials; - materials.clone = function () { + this._compileMaterial( this._blurMaterial ); - return materials.slice(); +} - }; - return materials; +PMREMGenerator.prototype = { - } + constructor: PMREMGenerator, - function PointCloud( geometry, material ) { + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene: function ( scene, sigma = 0, near = 0.1, far = 100 ) { - console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); - return new Points( geometry, material ); + _oldTarget = this._renderer.getRenderTarget(); + var cubeUVRenderTarget = this._allocateTargets(); - } + this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); + if ( sigma > 0 ) { - function Particle( material ) { + this._blur( cubeUVRenderTarget, 0, 0, sigma ); - console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); - return new Sprite( material ); + } - } + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - function ParticleSystem( geometry, material ) { + return cubeUVRenderTarget; - console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); - return new Points( geometry, material ); + }, - } + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular: function ( equirectangular ) { - function PointCloudMaterial( parameters ) { + equirectangular.magFilter = NearestFilter; + equirectangular.minFilter = NearestFilter; + equirectangular.generateMipmaps = false; - console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + return this.fromCubemap( equirectangular ); - } + }, - function ParticleBasicMaterial( parameters ) { - - console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); - - } - - function ParticleSystemMaterial( parameters ) { + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap: function ( cubemap ) { - console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); - return new PointsMaterial( parameters ); + _oldTarget = this._renderer.getRenderTarget(); + var cubeUVRenderTarget = this._allocateTargets( cubemap ); + this._textureToCubeUV( cubemap, cubeUVRenderTarget ); + this._applyPMREM( cubeUVRenderTarget ); + this._cleanup( cubeUVRenderTarget ); - } + return cubeUVRenderTarget; - function Vertex( x, y, z ) { + }, - console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); - return new Vector3( x, y, z ); + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader: function () { - } + if ( this._cubemapShader === null ) { - // + this._cubemapShader = _getCubemapShader(); + this._compileMaterial( this._cubemapShader ); - function DynamicBufferAttribute( array, itemSize ) { + } - console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); - return new BufferAttribute( array, itemSize ).setDynamic( true ); + }, - } + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader: function () { - function Int8Attribute( array, itemSize ) { + if ( this._equirectShader === null ) { - console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); - return new Int8BufferAttribute( array, itemSize ); + this._equirectShader = _getEquirectShader(); + this._compileMaterial( this._equirectShader ); - } + } - function Uint8Attribute( array, itemSize ) { + }, - console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); - return new Uint8BufferAttribute( array, itemSize ); + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose: function () { - } + this._blurMaterial.dispose(); - function Uint8ClampedAttribute( array, itemSize ) { + if ( this._cubemapShader !== null ) this._cubemapShader.dispose(); + if ( this._equirectShader !== null ) this._equirectShader.dispose(); - console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); - return new Uint8ClampedBufferAttribute( array, itemSize ); + for ( var i = 0; i < _lodPlanes.length; i ++ ) { - } + _lodPlanes[ i ].dispose(); - function Int16Attribute( array, itemSize ) { + } - console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); - return new Int16BufferAttribute( array, itemSize ); + }, - } + // private interface - function Uint16Attribute( array, itemSize ) { + _cleanup: function ( outputTarget ) { - console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); - return new Uint16BufferAttribute( array, itemSize ); + this._pingPongRenderTarget.dispose(); + this._renderer.setRenderTarget( _oldTarget ); + outputTarget.scissorTest = false; + // reset viewport and scissor + outputTarget.setSize( outputTarget.width, outputTarget.height ); - } + }, - function Int32Attribute( array, itemSize ) { + _allocateTargets: function ( equirectangular ) { - console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); - return new Int32BufferAttribute( array, itemSize ); + var params = { + magFilter: NearestFilter, + minFilter: NearestFilter, + generateMipmaps: false, + type: UnsignedByteType, + format: RGBEFormat, + encoding: _isLDR( equirectangular ) ? equirectangular.encoding : RGBEEncoding, + depthBuffer: false, + stencilBuffer: false + }; - } + var cubeUVRenderTarget = _createRenderTarget( params ); + cubeUVRenderTarget.depthBuffer = equirectangular ? false : true; + this._pingPongRenderTarget = _createRenderTarget( params ); + return cubeUVRenderTarget; - function Uint32Attribute( array, itemSize ) { + }, - console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); - return new Uint32BufferAttribute( array, itemSize ); + _compileMaterial: function ( material ) { - } + var tmpMesh = new Mesh( _lodPlanes[ 0 ], material ); + this._renderer.compile( tmpMesh, _flatCamera ); - function Float32Attribute( array, itemSize ) { + }, - console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); - return new Float32BufferAttribute( array, itemSize ); + _sceneToCubeUV: function ( scene, near, far, cubeUVRenderTarget ) { - } + var fov = 90; + var aspect = 1; + var cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); + var upSign = [ 1, - 1, 1, 1, 1, 1 ]; + var forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ]; + var renderer = this._renderer; - function Float64Attribute( array, itemSize ) { + var outputEncoding = renderer.outputEncoding; + var toneMapping = renderer.toneMapping; + var toneMappingExposure = renderer.toneMappingExposure; + var clearColor = renderer.getClearColor(); + var clearAlpha = renderer.getClearAlpha(); - console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); - return new Float64BufferAttribute( array, itemSize ); + renderer.toneMapping = LinearToneMapping; + renderer.toneMappingExposure = 1.0; + renderer.outputEncoding = LinearEncoding; - } + var background = scene.background; + if ( background && background.isColor ) { - // + background.convertSRGBToLinear(); + // Convert linear to RGBE + var maxComponent = Math.max( background.r, background.g, background.b ); + var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); + background = background.multiplyScalar( Math.pow( 2.0, - fExp ) ); + var alpha = ( fExp + 128.0 ) / 255.0; + renderer.setClearColor( background, alpha ); + scene.background = null; - Curve.create = function ( construct, getPoint ) { + } - console.log( 'THREE.Curve.create() has been deprecated' ); + for ( var i = 0; i < 6; i ++ ) { - construct.prototype = Object.create( Curve.prototype ); - construct.prototype.constructor = construct; - construct.prototype.getPoint = getPoint; + var col = i % 3; + if ( col == 0 ) { - return construct; + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); - }; + } else if ( col == 1 ) { - // + cubeCamera.up.set( 0, 0, upSign[ i ] ); + cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); - Object.assign( CurvePath.prototype, { + } else { - createPointsGeometry: function ( divisions ) { + cubeCamera.up.set( 0, upSign[ i ], 0 ); + cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); - console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + } - // generate geometry from path points (for Line or Points objects) + _setViewport( cubeUVRenderTarget, + col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX ); + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( scene, cubeCamera ); - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); + } - }, + renderer.toneMapping = toneMapping; + renderer.toneMappingExposure = toneMappingExposure; + renderer.outputEncoding = outputEncoding; + renderer.setClearColor( clearColor, clearAlpha ); - createSpacedPointsGeometry: function ( divisions ) { + }, - console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + _textureToCubeUV: function ( texture, cubeUVRenderTarget ) { - // generate geometry from equidistant sampling along the path + var renderer = this._renderer; - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); + if ( texture.isCubeTexture ) { - }, + if ( this._cubemapShader == null ) { - createGeometry: function ( points ) { + this._cubemapShader = _getCubemapShader(); - console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + } - var geometry = new Geometry(); + } else { - for ( var i = 0, l = points.length; i < l; i ++ ) { + if ( this._equirectShader == null ) { - var point = points[ i ]; - geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + this._equirectShader = _getEquirectShader(); } - return geometry; - } - } ); + var material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader; + var mesh = new Mesh( _lodPlanes[ 0 ], material ); - // + var uniforms = material.uniforms; - Object.assign( Path.prototype, { + uniforms[ 'envMap' ].value = texture; - fromPoints: function ( points ) { + if ( ! texture.isCubeTexture ) { - console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); - return this.setFromPoints( points ); + uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height ); } - } ); + uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ]; + uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ]; - // + _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX ); - function ClosedSplineCurve3( points ) { + renderer.setRenderTarget( cubeUVRenderTarget ); + renderer.render( mesh, _flatCamera ); - console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); + }, - CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; - this.closed = true; + _applyPMREM: function ( cubeUVRenderTarget ) { - } + var renderer = this._renderer; + var autoClear = renderer.autoClear; + renderer.autoClear = false; - ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); + for ( var i = 1; i < TOTAL_LODS; i ++ ) { - // + var sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] ); - function SplineCurve3( points ) { + var poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; - console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); + this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); - CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; + } - } + renderer.autoClear = autoClear; - SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); + }, - // + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur: function ( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { - function Spline( points ) { + var pingPongRenderTarget = this._pingPongRenderTarget; - console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' ); + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + 'latitudinal', + poleAxis ); - CatmullRomCurve3.call( this, points ); - this.type = 'catmullrom'; + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + 'longitudinal', + poleAxis ); - } + }, - Spline.prototype = Object.create( CatmullRomCurve3.prototype ); + _halfBlur: function ( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { - Object.assign( Spline.prototype, { + var renderer = this._renderer; + var blurMaterial = this._blurMaterial; - initFromArray: function ( /* a */ ) { + if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { - console.error( 'THREE.Spline: .initFromArray() has been removed.' ); + console.error( + 'blur direction must be either latitudinal or longitudinal!' ); - }, - getControlPointsArray: function ( /* optionalTarget */ ) { + } - console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' ); + // Number of standard deviations at which to cut off the discrete approximation. + var STANDARD_DEVIATIONS = 3; - }, - reparametrizeByArcLength: function ( /* samplingCoef */ ) { + var blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial ); + var blurUniforms = blurMaterial.uniforms; - console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' ); + var pixels = _sizeLods[ lodIn ] - 1; + var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); + var sigmaPixels = sigmaRadians / radiansPerPixel; + var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; - } + if ( samples > MAX_SAMPLES ) { - } ); + console.warn( `sigmaRadians, ${ + sigmaRadians}, is too large and will clip, as it requested ${ + samples} samples when the maximum is set to ${MAX_SAMPLES}` ); - // + } - function AxisHelper( size ) { + var weights = []; + var sum = 0; - console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); - return new AxesHelper( size ); + for ( var i = 0; i < MAX_SAMPLES; ++ i ) { - } + var x = i / sigmaPixels; + var weight = Math.exp( - x * x / 2 ); + weights.push( weight ); - function BoundingBoxHelper( object, color ) { + if ( i == 0 ) { - console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); - return new BoxHelper( object, color ); + sum += weight; - } + } else if ( i < samples ) { - function EdgesHelper( object, hex ) { + sum += 2 * weight; - console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); - return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + } - } + } - GridHelper.prototype.setColors = function () { + for ( var i = 0; i < weights.length; i ++ ) { - console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); + weights[ i ] = weights[ i ] / sum; - }; + } - SkeletonHelper.prototype.update = function () { + blurUniforms[ 'envMap' ].value = targetIn.texture; + blurUniforms[ 'samples' ].value = samples; + blurUniforms[ 'weights' ].value = weights; + blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; - console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); + if ( poleAxis ) { - }; + blurUniforms[ 'poleAxis' ].value = poleAxis; - function WireframeHelper( object, hex ) { + } - console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); - return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); + blurUniforms[ 'dTheta' ].value = radiansPerPixel; + blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn; + blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; + blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; - } + var outputSize = _sizeLods[ lodOut ]; + var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize ); + var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 ); - // + _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); + renderer.setRenderTarget( targetOut ); + renderer.render( blurMesh, _flatCamera ); - Object.assign( Loader.prototype, { + } - extractUrlBase: function ( url ) { +}; - console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); - return LoaderUtils.extractUrlBase( url ); +function _isLDR( texture ) { - } + if ( texture === undefined || texture.type !== UnsignedByteType ) return false; - } ); + return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding; - Loader.Handlers = { +} - add: function ( /* regex, loader */ ) { +function _createPlanes() { - console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); + var _lodPlanes = []; + var _sizeLods = []; + var _sigmas = []; - }, + var lod = LOD_MAX; - get: function ( /* file */ ) { + for ( var i = 0; i < TOTAL_LODS; i ++ ) { - console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); + var sizeLod = Math.pow( 2, lod ); + _sizeLods.push( sizeLod ); + var sigma = 1.0 / sizeLod; - } + if ( i > LOD_MAX - LOD_MIN ) { - }; + sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ]; - function XHRLoader( manager ) { + } else if ( i == 0 ) { - console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); - return new FileLoader( manager ); + sigma = 0; - } + } - function BinaryTextureLoader( manager ) { + _sigmas.push( sigma ); - console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); - return new DataTextureLoader( manager ); + var texelSize = 1.0 / ( sizeLod - 1 ); + var min = - texelSize / 2; + var max = 1 + texelSize / 2; + var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; - } + var cubeFaces = 6; + var vertices = 6; + var positionSize = 3; + var uvSize = 2; + var faceIndexSize = 1; - Object.assign( ObjectLoader.prototype, { + var position = new Float32Array( positionSize * vertices * cubeFaces ); + var uv = new Float32Array( uvSize * vertices * cubeFaces ); + var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); - setTexturePath: function ( value ) { + for ( var face = 0; face < cubeFaces; face ++ ) { - console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' ); - return this.setResourcePath( value ); + var x = ( face % 3 ) * 2 / 3 - 1; + var y = face > 2 ? 0 : - 1; + var coordinates = [ + x, y, 0, + x + 2 / 3, y, 0, + x + 2 / 3, y + 1, 0, + x, y, 0, + x + 2 / 3, y + 1, 0, + x, y + 1, 0 + ]; + position.set( coordinates, positionSize * vertices * face ); + uv.set( uv1, uvSize * vertices * face ); + var fill = [ face, face, face, face, face, face ]; + faceIndex.set( fill, faceIndexSize * vertices * face ); } - } ); + var planes = new BufferGeometry(); + planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); + planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); + planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); + _lodPlanes.push( planes ); - // + if ( lod > LOD_MIN ) { - Object.assign( Box2.prototype, { + lod --; - center: function ( optionalTarget ) { + } - console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + } - }, - empty: function () { + return { _lodPlanes, _sizeLods, _sigmas }; - console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); +} - }, - isIntersectionBox: function ( box ) { +function _createRenderTarget( params ) { - console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params ); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; - }, - size: function ( optionalTarget ) { +} - console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); +function _setViewport( target, x, y, width, height ) { - } - } ); + target.viewport.set( x, y, width, height ); + target.scissor.set( x, y, width, height ); + +} - Object.assign( Box3.prototype, { +function _getBlurShader( maxSamples ) { - center: function ( optionalTarget ) { + var weights = new Float32Array( maxSamples ); + var poleAxis = new Vector3( 0, 1, 0 ); + var shaderMaterial = new RawShaderMaterial( { - console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + defines: { 'n': maxSamples }, + uniforms: { + 'envMap': { value: null }, + 'samples': { value: 1 }, + 'weights': { value: weights }, + 'latitudinal': { value: false }, + 'dTheta': { value: 0 }, + 'mipInt': { value: 0 }, + 'poleAxis': { value: poleAxis }, + 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, + 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, - empty: function () { - console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); - return this.isEmpty(); + vertexShader: _getCommonVertexShader(), - }, - isIntersectionBox: function ( box ) { + fragmentShader: ` +precision mediump float; +precision mediump int; +varying vec3 vOutputDirection; +uniform sampler2D envMap; +uniform int samples; +uniform float weights[n]; +uniform bool latitudinal; +uniform float dTheta; +uniform float mipInt; +uniform vec3 poleAxis; - console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); +${_getEncodings()} - }, - isIntersectionSphere: function ( sphere ) { +#define ENVMAP_TYPE_CUBE_UV +#include - console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); +vec3 getSample(float theta, vec3 axis) { + float cosTheta = cos(theta); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross(axis, vOutputDirection) * sin(theta) + + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta); + return bilinearCubeUV(envMap, sampleDirection, mipInt); +} - }, - size: function ( optionalTarget ) { +void main() { + vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection); + if (all(equal(axis, vec3(0.0)))) + axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x); + axis = normalize(axis); + gl_FragColor = vec4(0.0); + gl_FragColor.rgb += weights[0] * getSample(0.0, axis); + for (int i = 1; i < n; i++) { + if (i >= samples) + break; + float theta = dTheta * float(i); + gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis); + gl_FragColor.rgb += weights[i] * getSample(theta, axis); + } + gl_FragColor = linearToOutputTexel(gl_FragColor); +} + `, - console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); - return this.getSize( optionalTarget ); + blending: NoBlending, + depthTest: false, + depthWrite: false - } } ); - Line3.prototype.center = function ( optionalTarget ) { - - console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); - return this.getCenter( optionalTarget ); + shaderMaterial.type = 'SphericalGaussianBlur'; - }; + return shaderMaterial; - Object.assign( _Math, { +} - random16: function () { +function _getEquirectShader() { - console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + var texelSize = new Vector2( 1, 1 ); + var shaderMaterial = new RawShaderMaterial( { + uniforms: { + 'envMap': { value: null }, + 'texelSize': { value: texelSize }, + 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, + 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, - nearestPowerOfTwo: function ( value ) { + vertexShader: _getCommonVertexShader(), - console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); - return _Math.floorPowerOfTwo( value ); + fragmentShader: ` +precision mediump float; +precision mediump int; +varying vec3 vOutputDirection; +uniform sampler2D envMap; +uniform vec2 texelSize; - }, +${_getEncodings()} - nextPowerOfTwo: function ( value ) { +#include - console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); - return _Math.ceilPowerOfTwo( value ); +void main() { + gl_FragColor = vec4(0.0); + vec3 outputDirection = normalize(vOutputDirection); + vec2 uv = equirectUv( outputDirection ); + vec2 f = fract(uv / texelSize - 0.5); + uv -= f * texelSize; + vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb; + uv.x += texelSize.x; + vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb; + uv.y += texelSize.y; + vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb; + uv.x -= texelSize.x; + vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb; + vec3 tm = mix(tl, tr, f.x); + vec3 bm = mix(bl, br, f.x); + gl_FragColor.rgb = mix(tm, bm, f.y); + gl_FragColor = linearToOutputTexel(gl_FragColor); +} + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false } ); - Object.assign( Matrix3.prototype, { + shaderMaterial.type = 'EquirectangularToCubeUV'; - flattenToArrayOffset: function ( array, offset ) { + return shaderMaterial; - console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); - return this.toArray( array, offset ); +} - }, - multiplyVector3: function ( vector ) { +function _getCubemapShader() { - console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); - return vector.applyMatrix3( this ); + var shaderMaterial = new RawShaderMaterial( { + uniforms: { + 'envMap': { value: null }, + 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, + 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, - multiplyVector3Array: function ( /* a */ ) { - - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); - }, - applyToBuffer: function ( buffer /*, offset, length */ ) { + vertexShader: _getCommonVertexShader(), - console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); - return this.applyToBufferAttribute( buffer ); + fragmentShader: ` +precision mediump float; +precision mediump int; +varying vec3 vOutputDirection; +uniform samplerCube envMap; - }, - applyToVector3Array: function ( /* array, offset, length */ ) { +${_getEncodings()} - console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); +void main() { + gl_FragColor = vec4(0.0); + gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb; + gl_FragColor = linearToOutputTexel(gl_FragColor); +} + `, - } + blending: NoBlending, + depthTest: false, + depthWrite: false } ); - Object.assign( Matrix4.prototype, { - - extractPosition: function ( m ) { + shaderMaterial.type = 'CubemapToCubeUV'; + + return shaderMaterial; + +} + +function _getCommonVertexShader() { + + return ` +precision mediump float; +precision mediump int; +attribute vec3 position; +attribute vec2 uv; +attribute float faceIndex; +varying vec3 vOutputDirection; + +// RH coordinate system; PMREM face-indexing convention +vec3 getDirection(vec2 uv, float face) { + uv = 2.0 * uv - 1.0; + vec3 direction = vec3(uv, 1.0); + if (face == 0.0) { + direction = direction.zyx; // ( 1, v, u ) pos x + } else if (face == 1.0) { + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + } else if (face == 2.0) { + direction.x *= -1.0; // ( -u, v, 1 ) pos z + } else if (face == 3.0) { + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + } else if (face == 4.0) { + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + } else if (face == 5.0) { + direction.z *= -1.0; // ( u, v, -1 ) neg z + } + return direction; +} + +void main() { + vOutputDirection = getDirection(uv, faceIndex); + gl_Position = vec4( position, 1.0 ); +} + `; + +} + +function _getEncodings() { + + return ` +uniform int inputEncoding; +uniform int outputEncoding; + +#include + +vec4 inputTexelToLinear(vec4 value){ + if(inputEncoding == 0){ + return value; + }else if(inputEncoding == 1){ + return sRGBToLinear(value); + }else if(inputEncoding == 2){ + return RGBEToLinear(value); + }else if(inputEncoding == 3){ + return RGBMToLinear(value, 7.0); + }else if(inputEncoding == 4){ + return RGBMToLinear(value, 16.0); + }else if(inputEncoding == 5){ + return RGBDToLinear(value, 256.0); + }else{ + return GammaToLinear(value, 2.2); + } +} + +vec4 linearToOutputTexel(vec4 value){ + if(outputEncoding == 0){ + return value; + }else if(outputEncoding == 1){ + return LinearTosRGB(value); + }else if(outputEncoding == 2){ + return LinearToRGBE(value); + }else if(outputEncoding == 3){ + return LinearToRGBM(value, 7.0); + }else if(outputEncoding == 4){ + return LinearToRGBM(value, 16.0); + }else if(outputEncoding == 5){ + return LinearToRGBD(value, 256.0); + }else{ + return LinearToGamma(value, 2.2); + } +} + +vec4 envMapTexelToLinear(vec4 color) { + return inputTexelToLinear(color); +} + `; + +} + +/** + * @author mrdoob / http://mrdoob.com/ + */ + +function Face4( a, b, c, d, normal, color, materialIndex ) { + + console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); + return new Face3( a, b, c, normal, color, materialIndex ); + +} + +var LineStrip = 0; +var LinePieces = 1; +var NoColors = 0; +var FaceColors = 1; +var VertexColors = 2; + +function MeshFaceMaterial( materials ) { + + console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); + return materials; + +} + +function MultiMaterial( materials ) { + + if ( materials === undefined ) materials = []; + + console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); + materials.isMultiMaterial = true; + materials.materials = materials; + materials.clone = function () { - console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); - return this.copyPosition( m ); + return materials.slice(); - }, - flattenToArrayOffset: function ( array, offset ) { + }; - console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); - return this.toArray( array, offset ); + return materials; - }, - getPosition: function () { +} - console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); - return new Vector3().setFromMatrixColumn( this, 3 ); +function PointCloud( geometry, material ) { - }, - setRotationFromQuaternion: function ( q ) { + console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); + return new Points( geometry, material ); - console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); - return this.makeRotationFromQuaternion( q ); +} - }, - multiplyToArray: function () { +function Particle( material ) { - console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); + console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); + return new Sprite( material ); - }, - multiplyVector3: function ( vector ) { +} - console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); +function ParticleSystem( geometry, material ) { - }, - multiplyVector4: function ( vector ) { + console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); + return new Points( geometry, material ); - console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); +} - }, - multiplyVector3Array: function ( /* a */ ) { +function PointCloudMaterial( parameters ) { - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); + console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); + return new PointsMaterial( parameters ); - }, - rotateAxis: function ( v ) { +} - console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); - v.transformDirection( this ); +function ParticleBasicMaterial( parameters ) { - }, - crossVector: function ( vector ) { + console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); + return new PointsMaterial( parameters ); - console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); - return vector.applyMatrix4( this ); +} - }, - translate: function () { +function ParticleSystemMaterial( parameters ) { - console.error( 'THREE.Matrix4: .translate() has been removed.' ); + console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); + return new PointsMaterial( parameters ); - }, - rotateX: function () { +} - console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); +function Vertex( x, y, z ) { - }, - rotateY: function () { + console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); + return new Vector3( x, y, z ); - console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); +} - }, - rotateZ: function () { +// - console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); +function DynamicBufferAttribute( array, itemSize ) { - }, - rotateByAxis: function () { + console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); + return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage ); - console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); +} - }, - applyToBuffer: function ( buffer /*, offset, length */ ) { +function Int8Attribute( array, itemSize ) { - console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); - return this.applyToBufferAttribute( buffer ); + console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); + return new Int8BufferAttribute( array, itemSize ); - }, - applyToVector3Array: function ( /* array, offset, length */ ) { +} - console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); +function Uint8Attribute( array, itemSize ) { - }, - makeFrustum: function ( left, right, bottom, top, near, far ) { + console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); + return new Uint8BufferAttribute( array, itemSize ); - console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); - return this.makePerspective( left, right, top, bottom, near, far ); +} - } +function Uint8ClampedAttribute( array, itemSize ) { - } ); + console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); + return new Uint8ClampedBufferAttribute( array, itemSize ); - Plane.prototype.isIntersectionLine = function ( line ) { +} - console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); - return this.intersectsLine( line ); +function Int16Attribute( array, itemSize ) { - }; + console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); + return new Int16BufferAttribute( array, itemSize ); - Quaternion.prototype.multiplyVector3 = function ( vector ) { +} - console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); - return vector.applyQuaternion( this ); +function Uint16Attribute( array, itemSize ) { - }; + console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); + return new Uint16BufferAttribute( array, itemSize ); - Object.assign( Ray.prototype, { +} - isIntersectionBox: function ( box ) { +function Int32Attribute( array, itemSize ) { - console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); - return this.intersectsBox( box ); + console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); + return new Int32BufferAttribute( array, itemSize ); - }, - isIntersectionPlane: function ( plane ) { +} - console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); - return this.intersectsPlane( plane ); +function Uint32Attribute( array, itemSize ) { - }, - isIntersectionSphere: function ( sphere ) { + console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); + return new Uint32BufferAttribute( array, itemSize ); - console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); - return this.intersectsSphere( sphere ); +} - } +function Float32Attribute( array, itemSize ) { - } ); + console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); + return new Float32BufferAttribute( array, itemSize ); - Object.assign( Triangle.prototype, { +} - area: function () { +function Float64Attribute( array, itemSize ) { - console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); - return this.getArea(); + console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); + return new Float64BufferAttribute( array, itemSize ); - }, - barycoordFromPoint: function ( point, target ) { +} - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return this.getBarycoord( point, target ); +// - }, - midpoint: function ( target ) { +Curve.create = function ( construct, getPoint ) { - console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); - return this.getMidpoint( target ); + console.log( 'THREE.Curve.create() has been deprecated' ); - }, - normal: function ( target ) { + construct.prototype = Object.create( Curve.prototype ); + construct.prototype.constructor = construct; + construct.prototype.getPoint = getPoint; - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return this.getNormal( target ); + return construct; - }, - plane: function ( target ) { +}; - console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); - return this.getPlane( target ); +// - } +Object.assign( CurvePath.prototype, { - } ); + createPointsGeometry: function ( divisions ) { - Object.assign( Triangle, { + console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); - barycoordFromPoint: function ( point, a, b, c, target ) { + // generate geometry from path points (for Line or Points objects) - console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); - return Triangle.getBarycoord( point, a, b, c, target ); + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); - }, - normal: function ( a, b, c, target ) { + }, - console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); - return Triangle.getNormal( a, b, c, target ); + createSpacedPointsGeometry: function ( divisions ) { - } + console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); - } ); + // generate geometry from equidistant sampling along the path - Object.assign( Shape.prototype, { + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); - extractAllPoints: function ( divisions ) { + }, - console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); - return this.extractPoints( divisions ); + createGeometry: function ( points ) { - }, - extrude: function ( options ) { + console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); - console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); - return new ExtrudeGeometry( this, options ); + var geometry = new Geometry(); - }, - makeGeometry: function ( options ) { + for ( var i = 0, l = points.length; i < l; i ++ ) { - console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); - return new ShapeGeometry( this, options ); + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); } - } ); + return geometry; - Object.assign( Vector2.prototype, { + } - fromAttribute: function ( attribute, index, offset ) { +} ); - console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); +// - }, - distanceToManhattan: function ( v ) { +Object.assign( Path.prototype, { - console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); + fromPoints: function ( points ) { - }, - lengthManhattan: function () { + console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); + return this.setFromPoints( points ); - console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + } - } +} ); - } ); +// - Object.assign( Vector3.prototype, { +function ClosedSplineCurve3( points ) { - setEulerFromRotationMatrix: function () { + console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); - console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; + this.closed = true; - }, - setEulerFromQuaternion: function () { +} - console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); +ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); - }, - getPositionFromMatrix: function ( m ) { +// - console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); - return this.setFromMatrixPosition( m ); +function SplineCurve3( points ) { - }, - getScaleFromMatrix: function ( m ) { + console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); - console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); - return this.setFromMatrixScale( m ); + CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; - }, - getColumnFromMatrix: function ( index, matrix ) { +} - console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); - return this.setFromMatrixColumn( matrix, index ); +SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); - }, - applyProjection: function ( m ) { +// - console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); - return this.applyMatrix4( m ); +function Spline( points ) { - }, - fromAttribute: function ( attribute, index, offset ) { + console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' ); - console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + CatmullRomCurve3.call( this, points ); + this.type = 'catmullrom'; - }, - distanceToManhattan: function ( v ) { +} - console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); - return this.manhattanDistanceTo( v ); +Spline.prototype = Object.create( CatmullRomCurve3.prototype ); - }, - lengthManhattan: function () { +Object.assign( Spline.prototype, { - console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); + initFromArray: function ( /* a */ ) { - } + console.error( 'THREE.Spline: .initFromArray() has been removed.' ); - } ); + }, + getControlPointsArray: function ( /* optionalTarget */ ) { - Object.assign( Vector4.prototype, { + console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' ); - fromAttribute: function ( attribute, index, offset ) { + }, + reparametrizeByArcLength: function ( /* samplingCoef */ ) { - console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); - return this.fromBufferAttribute( attribute, index, offset ); + console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' ); - }, - lengthManhattan: function () { + } - console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); - return this.manhattanLength(); +} ); - } +// - } ); +function AxisHelper( size ) { - // + console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); + return new AxesHelper( size ); - Object.assign( Geometry.prototype, { +} - computeTangents: function () { +function BoundingBoxHelper( object, color ) { - console.error( 'THREE.Geometry: .computeTangents() has been removed.' ); + console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); + return new BoxHelper( object, color ); - }, - computeLineDistances: function () { +} - console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' ); +function EdgesHelper( object, hex ) { - } + console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); + return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); - } ); +} - Object.assign( Object3D.prototype, { +GridHelper.prototype.setColors = function () { - getChildByName: function ( name ) { + console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); - console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); - return this.getObjectByName( name ); +}; - }, - renderDepth: function () { +SkeletonHelper.prototype.update = function () { - console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); - }, - translate: function ( distance, axis ) { +}; - console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); - return this.translateOnAxis( axis, distance ); +function WireframeHelper( object, hex ) { - }, - getWorldRotation: function () { + console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); + return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); - console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); +} - } +// - } ); +Object.assign( Loader.prototype, { - Object.defineProperties( Object3D.prototype, { + extractUrlBase: function ( url ) { - eulerOrder: { - get: function () { + console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); + return LoaderUtils.extractUrlBase( url ); - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - return this.rotation.order; + } - }, - set: function ( value ) { +} ); - console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); - this.rotation.order = value; +Loader.Handlers = { - } - }, - useQuaternion: { - get: function () { + add: function ( /* regex, loader */ ) { - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); - }, - set: function () { + }, - console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + get: function ( /* file */ ) { - } - } + console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); - } ); + } - Object.defineProperties( LOD.prototype, { +}; - objects: { - get: function () { +function XHRLoader( manager ) { - console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); - return this.levels; + console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); + return new FileLoader( manager ); - } - } +} - } ); +function BinaryTextureLoader( manager ) { - Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { + console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); + return new DataTextureLoader( manager ); - get: function () { +} - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); +Object.assign( ObjectLoader.prototype, { - }, - set: function () { + setTexturePath: function ( value ) { - console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' ); + return this.setResourcePath( value ); - } + } - } ); +} ); - SkinnedMesh.prototype.initBones = function () { +// - console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); +Object.assign( Box2.prototype, { - }; + center: function ( optionalTarget ) { - Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { + console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); + return this.getCenter( optionalTarget ); - get: function () { + }, + empty: function () { - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - return this.arcLengthDivisions; + console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); - }, - set: function ( value ) { + }, + isIntersectionBox: function ( box ) { - console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); - this.arcLengthDivisions = value; + console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); - } + }, + size: function ( optionalTarget ) { - } ); + console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); + return this.getSize( optionalTarget ); - // + } +} ); - PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { +Object.assign( Box3.prototype, { - console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + - "Use .setFocalLength and .filmGauge for a photographic setup." ); + center: function ( optionalTarget ) { - if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; } - this.setFocalLength( focalLength ); + console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); + return this.getCenter( optionalTarget ); - }; + }, + empty: function () { - // + console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); - Object.defineProperties( Light.prototype, { - onlyShadow: { - set: function () { + }, + isIntersectionBox: function ( box ) { - console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); - } - }, - shadowCameraFov: { - set: function ( value ) { + }, + isIntersectionSphere: function ( sphere ) { - console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); - this.shadow.camera.fov = value; + console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); - } - }, - shadowCameraLeft: { - set: function ( value ) { + }, + size: function ( optionalTarget ) { - console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); - this.shadow.camera.left = value; + console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); + return this.getSize( optionalTarget ); - } - }, - shadowCameraRight: { - set: function ( value ) { + } +} ); - console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); - this.shadow.camera.right = value; +Object.assign( Sphere.prototype, { - } - }, - shadowCameraTop: { - set: function ( value ) { + empty: function () { - console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); - this.shadow.camera.top = value; + console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' ); + return this.isEmpty(); - } - }, - shadowCameraBottom: { - set: function ( value ) { + }, - console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); - this.shadow.camera.bottom = value; +} ); - } - }, - shadowCameraNear: { - set: function ( value ) { +Frustum.prototype.setFromMatrix = function ( m ) { - console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); - this.shadow.camera.near = value; + console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); + return this.setFromProjectionMatrix( m ); - } - }, - shadowCameraFar: { - set: function ( value ) { +}; - console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); - this.shadow.camera.far = value; +Line3.prototype.center = function ( optionalTarget ) { - } - }, - shadowCameraVisible: { - set: function () { + console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); + return this.getCenter( optionalTarget ); - console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); +}; - } - }, - shadowBias: { - set: function ( value ) { +Object.assign( MathUtils, { - console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); - this.shadow.bias = value; + random16: function () { - } - }, - shadowDarkness: { - set: function () { + console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); - console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + }, - } - }, - shadowMapWidth: { - set: function ( value ) { + nearestPowerOfTwo: function ( value ) { - console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); - this.shadow.mapSize.width = value; + console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); + return MathUtils.floorPowerOfTwo( value ); - } - }, - shadowMapHeight: { - set: function ( value ) { + }, - console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); - this.shadow.mapSize.height = value; + nextPowerOfTwo: function ( value ) { - } - } - } ); + console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); + return MathUtils.ceilPowerOfTwo( value ); - // + } - Object.defineProperties( BufferAttribute.prototype, { +} ); - length: { - get: function () { +Object.assign( Matrix3.prototype, { - console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); - return this.array.length; + flattenToArrayOffset: function ( array, offset ) { - } - }, - dynamic: { - get: function () { + console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); + return this.toArray( array, offset ); - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + }, + multiplyVector3: function ( vector ) { - }, - set: function ( /* value */ ) { + console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); + return vector.applyMatrix3( this ); - console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); - this.setUsage( DynamicDrawUsage ); + }, + multiplyVector3Array: function ( /* a */ ) { - } - } + console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); - } ); + }, + applyToBufferAttribute: function ( attribute ) { - Object.assign( BufferAttribute.prototype, { - setDynamic: function ( value ) { + console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); + return attribute.applyMatrix3( this ); - console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); - return this; + }, + applyToVector3Array: function ( /* array, offset, length */ ) { - }, - copyIndicesArray: function ( /* indices */ ) { + console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); - console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); + } - }, - setArray: function ( /* array */ ) { +} ); - console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); +Object.assign( Matrix4.prototype, { - } - } ); + extractPosition: function ( m ) { - Object.assign( BufferGeometry.prototype, { + console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); + return this.copyPosition( m ); - addIndex: function ( index ) { + }, + flattenToArrayOffset: function ( array, offset ) { - console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); - this.setIndex( index ); + console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); + return this.toArray( array, offset ); - }, - addAttribute: function ( name, attribute ) { + }, + getPosition: function () { - console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); + console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); + return new Vector3().setFromMatrixColumn( this, 3 ); - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { + }, + setRotationFromQuaternion: function ( q ) { - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); + return this.makeRotationFromQuaternion( q ); - return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + }, + multiplyToArray: function () { - } + console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); - if ( name === 'index' ) { + }, + multiplyVector3: function ( vector ) { - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); - return this; + }, + multiplyVector4: function ( vector ) { - } + console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); - return this.setAttribute( name, attribute ); + }, + multiplyVector3Array: function ( /* a */ ) { - }, - addDrawCall: function ( start, count, indexOffset ) { + console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); - if ( indexOffset !== undefined ) { + }, + rotateAxis: function ( v ) { - console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); + console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); + v.transformDirection( this ); - } - console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); - this.addGroup( start, count ); + }, + crossVector: function ( vector ) { - }, - clearDrawCalls: function () { + console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); + return vector.applyMatrix4( this ); + + }, + translate: function () { + + console.error( 'THREE.Matrix4: .translate() has been removed.' ); + + }, + rotateX: function () { + + console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); + + }, + rotateY: function () { + + console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); + + }, + rotateZ: function () { + + console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); + + }, + rotateByAxis: function () { + + console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); + + }, + applyToBufferAttribute: function ( attribute ) { + + console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); + return attribute.applyMatrix4( this ); + + }, + applyToVector3Array: function ( /* array, offset, length */ ) { + + console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); + + }, + makeFrustum: function ( left, right, bottom, top, near, far ) { + + console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); + return this.makePerspective( left, right, top, bottom, near, far ); + + } + +} ); + +Plane.prototype.isIntersectionLine = function ( line ) { + + console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); + return this.intersectsLine( line ); + +}; + +Quaternion.prototype.multiplyVector3 = function ( vector ) { + + console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + return vector.applyQuaternion( this ); + +}; + +Object.assign( Ray.prototype, { + + isIntersectionBox: function ( box ) { + + console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); + return this.intersectsBox( box ); + + }, + isIntersectionPlane: function ( plane ) { + + console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); + return this.intersectsPlane( plane ); + + }, + isIntersectionSphere: function ( sphere ) { + + console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); + return this.intersectsSphere( sphere ); + + } + +} ); + +Object.assign( Triangle.prototype, { + + area: function () { + + console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); + return this.getArea(); + + }, + barycoordFromPoint: function ( point, target ) { + + console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); + return this.getBarycoord( point, target ); + + }, + midpoint: function ( target ) { + + console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); + return this.getMidpoint( target ); + + }, + normal: function ( target ) { + + console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); + return this.getNormal( target ); + + }, + plane: function ( target ) { + + console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); + return this.getPlane( target ); + + } + +} ); + +Object.assign( Triangle, { + + barycoordFromPoint: function ( point, a, b, c, target ) { + + console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); + return Triangle.getBarycoord( point, a, b, c, target ); + + }, + normal: function ( a, b, c, target ) { + + console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); + return Triangle.getNormal( a, b, c, target ); + + } + +} ); + +Object.assign( Shape.prototype, { + + extractAllPoints: function ( divisions ) { + + console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); + return this.extractPoints( divisions ); + + }, + extrude: function ( options ) { + + console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); + return new ExtrudeGeometry( this, options ); + + }, + makeGeometry: function ( options ) { + + console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); + return new ShapeGeometry( this, options ); + + } + +} ); + +Object.assign( Vector2.prototype, { + + fromAttribute: function ( attribute, index, offset ) { + + console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + return this.fromBufferAttribute( attribute, index, offset ); + + }, + distanceToManhattan: function ( v ) { + + console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); + return this.manhattanDistanceTo( v ); + + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + + } + +} ); + +Object.assign( Vector3.prototype, { + + setEulerFromRotationMatrix: function () { + + console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); + + }, + setEulerFromQuaternion: function () { + + console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); + + }, + getPositionFromMatrix: function ( m ) { + + console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); + return this.setFromMatrixPosition( m ); + + }, + getScaleFromMatrix: function ( m ) { + + console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); + return this.setFromMatrixScale( m ); + + }, + getColumnFromMatrix: function ( index, matrix ) { + + console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); + return this.setFromMatrixColumn( matrix, index ); + + }, + applyProjection: function ( m ) { + + console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); + return this.applyMatrix4( m ); - console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); - this.clearGroups(); + }, + fromAttribute: function ( attribute, index, offset ) { + + console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + return this.fromBufferAttribute( attribute, index, offset ); + + }, + distanceToManhattan: function ( v ) { + + console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); + return this.manhattanDistanceTo( v ); + + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + + } + +} ); + +Object.assign( Vector4.prototype, { + + fromAttribute: function ( attribute, index, offset ) { + + console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + return this.fromBufferAttribute( attribute, index, offset ); + + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + + } + +} ); + +// + +Object.assign( Geometry.prototype, { + + computeTangents: function () { + + console.error( 'THREE.Geometry: .computeTangents() has been removed.' ); + + }, + computeLineDistances: function () { + + console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' ); + + }, + applyMatrix: function ( matrix ) { + + console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' ); + return this.applyMatrix4( matrix ); + + } + +} ); + +Object.assign( Object3D.prototype, { + + getChildByName: function ( name ) { + + console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); + return this.getObjectByName( name ); + + }, + renderDepth: function () { + + console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); + + }, + translate: function ( distance, axis ) { + + console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); + return this.translateOnAxis( axis, distance ); + + }, + getWorldRotation: function () { + + console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); + + }, + applyMatrix: function ( matrix ) { + + console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); + return this.applyMatrix4( matrix ); + + } + +} ); + +Object.defineProperties( Object3D.prototype, { + + eulerOrder: { + get: function () { + + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + return this.rotation.order; }, - computeTangents: function () { + set: function ( value ) { - console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); + console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); + this.rotation.order = value; + + } + }, + useQuaternion: { + get: function () { + + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); }, - computeOffsets: function () { + set: function () { + + console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); + + } + } + +} ); + +Object.assign( Mesh.prototype, { + + setDrawMode: function () { + + console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); - console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + }, + +} ); + +Object.defineProperties( Mesh.prototype, { + + drawMode: { + get: function () { + + console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); + return TrianglesDrawMode; }, - removeAttribute: function ( name ) { + set: function () { + + console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); + + } + } + +} ); - console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); +Object.defineProperties( LOD.prototype, { - return this.deleteAttribute( name ); + objects: { + get: function () { + + console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); + return this.levels; } - } ); + } - Object.defineProperties( BufferGeometry.prototype, { +} ); - drawcalls: { - get: function () { +Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { - console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); - return this.groups; + get: function () { + + console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + + }, + set: function () { + + console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); + + } + +} ); + +SkinnedMesh.prototype.initBones = function () { + + console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); + +}; + +Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { + + get: function () { + + console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); + return this.arcLengthDivisions; + + }, + set: function ( value ) { + + console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); + this.arcLengthDivisions = value; + + } + +} ); + +// + +PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { + + console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + + "Use .setFocalLength and .filmGauge for a photographic setup." ); + + if ( filmGauge !== undefined ) this.filmGauge = filmGauge; + this.setFocalLength( focalLength ); + +}; + +// + +Object.defineProperties( Light.prototype, { + onlyShadow: { + set: function () { + + console.warn( 'THREE.Light: .onlyShadow has been removed.' ); + + } + }, + shadowCameraFov: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); + this.shadow.camera.fov = value; + + } + }, + shadowCameraLeft: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); + this.shadow.camera.left = value; + + } + }, + shadowCameraRight: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); + this.shadow.camera.right = value; + + } + }, + shadowCameraTop: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); + this.shadow.camera.top = value; + + } + }, + shadowCameraBottom: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); + this.shadow.camera.bottom = value; + + } + }, + shadowCameraNear: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); + this.shadow.camera.near = value; + + } + }, + shadowCameraFar: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); + this.shadow.camera.far = value; + + } + }, + shadowCameraVisible: { + set: function () { + + console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); + + } + }, + shadowBias: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); + this.shadow.bias = value; + + } + }, + shadowDarkness: { + set: function () { + + console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); + + } + }, + shadowMapWidth: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); + this.shadow.mapSize.width = value; + + } + }, + shadowMapHeight: { + set: function ( value ) { + + console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); + this.shadow.mapSize.height = value; + + } + } +} ); + +// + +Object.defineProperties( BufferAttribute.prototype, { + + length: { + get: function () { + + console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); + return this.array.length; + + } + }, + dynamic: { + get: function () { + + console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); + return this.usage === DynamicDrawUsage; - } }, - offsets: { - get: function () { + set: function ( /* value */ ) { - console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); - return this.groups; + console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); + this.setUsage( DynamicDrawUsage ); - } } + } - } ); +} ); - Object.defineProperties( InterleavedBuffer.prototype, { +Object.assign( BufferAttribute.prototype, { + setDynamic: function ( value ) { - dynamic: { - get: function () { + console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); + this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); + return this; - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - return this.usage === DynamicDrawUsage; + }, + copyIndicesArray: function ( /* indices */ ) { - }, - set: function ( value ) { + console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); - console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); - this.setUsage( value ); + }, + setArray: function ( /* array */ ) { + + console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + + } +} ); + +Object.assign( BufferGeometry.prototype, { + + addIndex: function ( index ) { + + console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); + this.setIndex( index ); + + }, + addAttribute: function ( name, attribute ) { + + console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); + + if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { + + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + + return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - } } - } ); + if ( name === 'index' ) { - Object.assign( InterleavedBuffer.prototype, { - setDynamic: function ( value ) { + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); - this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); return this; - }, - setArray: function ( /* array */ ) { + } + + return this.setAttribute( name, attribute ); + + }, + addDrawCall: function ( start, count, indexOffset ) { - console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); + if ( indexOffset !== undefined ) { + + console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); } - } ); - // + console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); + this.addGroup( start, count ); + + }, + clearDrawCalls: function () { + + console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); + this.clearGroups(); + + }, + computeTangents: function () { + + console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); + + }, + computeOffsets: function () { + + console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); + + }, + removeAttribute: function ( name ) { + + console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); + + return this.deleteAttribute( name ); - Object.assign( ExtrudeBufferGeometry.prototype, { + }, + applyMatrix: function ( matrix ) { - getArrays: function () { + console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); + return this.applyMatrix4( matrix ); - console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' ); + } + +} ); + +Object.defineProperties( BufferGeometry.prototype, { + + drawcalls: { + get: function () { + + console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); + return this.groups; + + } + }, + offsets: { + get: function () { + + console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); + return this.groups; + + } + } + +} ); + +Object.defineProperties( InstancedBufferGeometry.prototype, { + + maxInstancedCount: { + get: function () { + + console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); + return this.instanceCount; }, + set: function ( value ) { + + console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' ); + this.instanceCount = value; + + } + } - addShapeList: function () { +} ); - console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' ); +Object.defineProperties( Raycaster.prototype, { + + linePrecision: { + get: function () { + + console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); + return this.params.Line.threshold; }, + set: function ( value ) { - addShape: function () { + console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' ); + this.params.Line.threshold = value; + + } + } - console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' ); +} ); + +Object.defineProperties( InterleavedBuffer.prototype, { + + dynamic: { + get: function () { + + console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); + return this.usage === DynamicDrawUsage; + + }, + set: function ( value ) { + + console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); + this.setUsage( value ); } + } - } ); +} ); - // +Object.assign( InterleavedBuffer.prototype, { + setDynamic: function ( value ) { - Object.defineProperties( Uniform.prototype, { + console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); + this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); + return this; - dynamic: { - set: function () { + }, + setArray: function ( /* array */ ) { - console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); + console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); - } - }, - onUpdate: { - value: function () { + } +} ); - console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); - return this; +// + +Object.assign( ExtrudeBufferGeometry.prototype, { + + getArrays: function () { + + console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' ); + + }, + + addShapeList: function () { + + console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' ); + + }, + + addShape: function () { + + console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' ); + + } + +} ); + +// + +Object.defineProperties( Uniform.prototype, { + + dynamic: { + set: function () { + + console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); - } } + }, + onUpdate: { + value: function () { - } ); + console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); + return this; - // + } + } - Object.defineProperties( Material.prototype, { +} ); - wrapAround: { - get: function () { +// - console.warn( 'THREE.Material: .wrapAround has been removed.' ); +Object.defineProperties( Material.prototype, { - }, - set: function () { + wrapAround: { + get: function () { + + console.warn( 'THREE.Material: .wrapAround has been removed.' ); + + }, + set: function () { + + console.warn( 'THREE.Material: .wrapAround has been removed.' ); + + } + }, + + overdraw: { + get: function () { - console.warn( 'THREE.Material: .wrapAround has been removed.' ); + console.warn( 'THREE.Material: .overdraw has been removed.' ); - } }, + set: function () { - overdraw: { - get: function () { + console.warn( 'THREE.Material: .overdraw has been removed.' ); - console.warn( 'THREE.Material: .overdraw has been removed.' ); + } + }, - }, - set: function () { + wrapRGB: { + get: function () { - console.warn( 'THREE.Material: .overdraw has been removed.' ); + console.warn( 'THREE.Material: .wrapRGB has been removed.' ); + return new Color(); - } - }, + } + }, - wrapRGB: { - get: function () { + shading: { + get: function () { - console.warn( 'THREE.Material: .wrapRGB has been removed.' ); - return new Color(); + console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - } }, + set: function ( value ) { - shading: { - get: function () { + console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + this.flatShading = ( value === FlatShading ); - console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + } + }, - }, - set: function ( value ) { + stencilMask: { + get: function () { - console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); - this.flatShading = ( value === FlatShading ); + console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); + return this.stencilFuncMask; - } }, + set: function ( value ) { - stencilMask: { - get: function () { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - return this.stencilFuncMask; - - }, - set: function ( value ) { - - console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); - this.stencilFuncMask = value; + console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); + this.stencilFuncMask = value; - } } + } - } ); +} ); - Object.defineProperties( MeshPhongMaterial.prototype, { +Object.defineProperties( MeshPhongMaterial.prototype, { - metal: { - get: function () { + metal: { + get: function () { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); - return false; + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); + return false; - }, - set: function () { + }, + set: function () { - console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); + console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); - } } + } - } ); +} ); - Object.defineProperties( ShaderMaterial.prototype, { +Object.defineProperties( ShaderMaterial.prototype, { - derivatives: { - get: function () { + derivatives: { + get: function () { - console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - return this.extensions.derivatives; + console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + return this.extensions.derivatives; - }, - set: function ( value ) { + }, + set: function ( value ) { - console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); - this.extensions.derivatives = value; + console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); + this.extensions.derivatives = value; - } } + } - } ); - - // - - Object.assign( WebGLRenderer.prototype, { +} ); - clearTarget: function ( renderTarget, color, depth, stencil ) { +// - console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); +Object.assign( WebGLRenderer.prototype, { - }, - animate: function ( callback ) { + clearTarget: function ( renderTarget, color, depth, stencil ) { - console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); - this.setAnimationLoop( callback ); + console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - }, - getCurrentRenderTarget: function () { + }, + animate: function ( callback ) { - console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); - return this.getRenderTarget(); + console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); + this.setAnimationLoop( callback ); - }, - getMaxAnisotropy: function () { + }, + getCurrentRenderTarget: function () { - console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); - return this.capabilities.getMaxAnisotropy(); + console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); + return this.getRenderTarget(); - }, - getPrecision: function () { + }, + getMaxAnisotropy: function () { - console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); - return this.capabilities.precision; + console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); + return this.capabilities.getMaxAnisotropy(); - }, - resetGLState: function () { + }, + getPrecision: function () { - console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); - return this.state.reset(); + console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); + return this.capabilities.precision; - }, - supportsFloatTextures: function () { + }, + resetGLState: function () { - console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); - return this.extensions.get( 'OES_texture_float' ); + console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); + return this.state.reset(); - }, - supportsHalfFloatTextures: function () { + }, + supportsFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); - return this.extensions.get( 'OES_texture_half_float' ); + console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); + return this.extensions.get( 'OES_texture_float' ); - }, - supportsStandardDerivatives: function () { + }, + supportsHalfFloatTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); - return this.extensions.get( 'OES_standard_derivatives' ); + console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); + return this.extensions.get( 'OES_texture_half_float' ); - }, - supportsCompressedTextureS3TC: function () { + }, + supportsStandardDerivatives: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); + console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); + return this.extensions.get( 'OES_standard_derivatives' ); - }, - supportsCompressedTexturePVRTC: function () { + }, + supportsCompressedTextureS3TC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); - return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); - }, - supportsBlendMinMax: function () { + }, + supportsCompressedTexturePVRTC: function () { - console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); - return this.extensions.get( 'EXT_blend_minmax' ); + console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); + return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - }, - supportsVertexTextures: function () { + }, + supportsBlendMinMax: function () { - console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); - return this.capabilities.vertexTextures; + console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); + return this.extensions.get( 'EXT_blend_minmax' ); - }, - supportsInstancedArrays: function () { + }, + supportsVertexTextures: function () { - console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); - return this.extensions.get( 'ANGLE_instanced_arrays' ); + console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); + return this.capabilities.vertexTextures; - }, - enableScissorTest: function ( boolean ) { + }, + supportsInstancedArrays: function () { - console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); - this.setScissorTest( boolean ); + console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); + return this.extensions.get( 'ANGLE_instanced_arrays' ); - }, - initMaterial: function () { + }, + enableScissorTest: function ( boolean ) { - console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); + this.setScissorTest( boolean ); - }, - addPrePlugin: function () { + }, + initMaterial: function () { - console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); - }, - addPostPlugin: function () { + }, + addPrePlugin: function () { - console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); - }, - updateShadowMap: function () { + }, + addPostPlugin: function () { - console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); - }, - setFaceCulling: function () { + }, + updateShadowMap: function () { - console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); - }, - allocTextureUnit: function () { + }, + setFaceCulling: function () { - console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); - }, - setTexture: function () { + }, + allocTextureUnit: function () { - console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); - }, - setTexture2D: function () { + }, + setTexture: function () { - console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); - }, - setTextureCube: function () { + }, + setTexture2D: function () { - console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); + console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); - }, - getActiveMipMapLevel: function () { + }, + setTextureCube: function () { - console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); - return this.getActiveMipmapLevel(); + console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); - } + }, + getActiveMipMapLevel: function () { - } ); + console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); + return this.getActiveMipmapLevel(); - Object.defineProperties( WebGLRenderer.prototype, { + } - shadowMapEnabled: { - get: function () { +} ); - return this.shadowMap.enabled; +Object.defineProperties( WebGLRenderer.prototype, { - }, - set: function ( value ) { + shadowMapEnabled: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); - this.shadowMap.enabled = value; + return this.shadowMap.enabled; - } }, - shadowMapType: { - get: function () { + set: function ( value ) { - return this.shadowMap.type; + console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); + this.shadowMap.enabled = value; - }, - set: function ( value ) { + } + }, + shadowMapType: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); - this.shadowMap.type = value; + return this.shadowMap.type; - } }, - shadowMapCullFace: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); + this.shadowMap.type = value; - }, - set: function ( /* value */ ) { + } + }, + shadowMapCullFace: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); + return undefined; - } }, - context: { - get: function () { + set: function ( /* value */ ) { - console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); - return this.getContext(); + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); - } } + }, + context: { + get: function () { - } ); - - Object.defineProperties( WebGLShadowMap.prototype, { + console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); + return this.getContext(); - cullFace: { - get: function () { + } + }, + vr: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); + return this.xr; - }, - set: function ( /* cullFace */ ) { + } + }, + gammaInput: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); + console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); + return false; - } }, - renderReverseSided: { - get: function () { + set: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); - }, - set: function () { + } + }, + gammaOutput: { + get: function () { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); + return false; - } }, - renderSingleSided: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - return undefined; + console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); + this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; - }, - set: function () { + } + } - console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); +} ); - } - } +Object.defineProperties( WebGLShadowMap.prototype, { - } ); + cullFace: { + get: function () { - // + console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); + return undefined; + + }, + set: function ( /* cullFace */ ) { - Object.defineProperties( WebGLRenderTargetCube.prototype, { + console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); - activeCubeFace: { - set: function ( /* value */ ) { + } + }, + renderReverseSided: { + get: function () { - console.warn( 'THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().' ); + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + return undefined; - } }, - activeMipMapLevel: { - set: function ( /* value */ ) { + set: function () { - console.warn( 'THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().' ); + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); - } } + }, + renderSingleSided: { + get: function () { - } ); + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); + return undefined; - // + }, + set: function () { - Object.defineProperties( WebGLRenderTarget.prototype, { + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); - wrapS: { - get: function () { + } + } - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - return this.texture.wrapS; +} ); - }, - set: function ( value ) { +function WebGLRenderTargetCube( width, height, options ) { - console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); - this.texture.wrapS = value; + console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); + return new WebGLCubeRenderTarget( width, options ); - } - }, - wrapT: { - get: function () { +} - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - return this.texture.wrapT; +// - }, - set: function ( value ) { +Object.defineProperties( WebGLRenderTarget.prototype, { + + wrapS: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); - this.texture.wrapT = value; + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + return this.texture.wrapS; - } }, - magFilter: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - return this.texture.magFilter; + console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); + this.texture.wrapS = value; - }, - set: function ( value ) { + } + }, + wrapT: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); - this.texture.magFilter = value; + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + return this.texture.wrapT; - } }, - minFilter: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - return this.texture.minFilter; + console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); + this.texture.wrapT = value; - }, - set: function ( value ) { + } + }, + magFilter: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); - this.texture.minFilter = value; + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + return this.texture.magFilter; - } }, - anisotropy: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - return this.texture.anisotropy; + console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); + this.texture.magFilter = value; - }, - set: function ( value ) { + } + }, + minFilter: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); - this.texture.anisotropy = value; + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + return this.texture.minFilter; - } }, - offset: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - return this.texture.offset; + console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); + this.texture.minFilter = value; - }, - set: function ( value ) { + } + }, + anisotropy: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); - this.texture.offset = value; + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + return this.texture.anisotropy; - } }, - repeat: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - return this.texture.repeat; + console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); + this.texture.anisotropy = value; - }, - set: function ( value ) { + } + }, + offset: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); - this.texture.repeat = value; + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + return this.texture.offset; - } }, - format: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - return this.texture.format; + console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); + this.texture.offset = value; - }, - set: function ( value ) { + } + }, + repeat: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); - this.texture.format = value; + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + return this.texture.repeat; - } }, - type: { - get: function () { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - return this.texture.type; + console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); + this.texture.repeat = value; - }, - set: function ( value ) { + } + }, + format: { + get: function () { - console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); - this.texture.type = value; + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + return this.texture.format; - } }, - generateMipmaps: { - get: function () { - - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - return this.texture.generateMipmaps; - - }, - set: function ( value ) { + set: function ( value ) { - console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); - this.texture.generateMipmaps = value; + console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); + this.texture.format = value; - } } + }, + type: { + get: function () { - } ); + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + return this.texture.type; - // + }, + set: function ( value ) { - Object.defineProperties( WebVRManager.prototype, { + console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); + this.texture.type = value; - standing: { - set: function ( /* value */ ) { + } + }, + generateMipmaps: { + get: function () { - console.warn( 'THREE.WebVRManager: .standing has been removed.' ); + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + return this.texture.generateMipmaps; - } }, - userHeight: { - set: function ( /* value */ ) { + set: function ( value ) { - console.warn( 'THREE.WebVRManager: .userHeight has been removed.' ); + console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); + this.texture.generateMipmaps = value; - } } + } - } ); +} ); - // +// - Object.defineProperties( Audio.prototype, { +Object.defineProperties( Audio.prototype, { - load: { - value: function ( file ) { + load: { + value: function ( file ) { - console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); - var scope = this; - var audioLoader = new AudioLoader(); - audioLoader.load( file, function ( buffer ) { + console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); + var scope = this; + var audioLoader = new AudioLoader(); + audioLoader.load( file, function ( buffer ) { - scope.setBuffer( buffer ); + scope.setBuffer( buffer ); - } ); - return this; + } ); + return this; - } - }, - startTime: { - set: function () { + } + }, + startTime: { + set: function () { - console.warn( 'THREE.Audio: .startTime is now .play( delay ).' ); + console.warn( 'THREE.Audio: .startTime is now .play( delay ).' ); - } } + } - } ); +} ); - AudioAnalyser.prototype.getData = function () { +AudioAnalyser.prototype.getData = function () { - console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); - return this.getFrequencyData(); + console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); + return this.getFrequencyData(); - }; +}; - // +// - CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { +CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { - console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); - return this.update( renderer, scene ); + console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); + return this.update( renderer, scene ); - }; +}; - // +// - var GeometryUtils = { +var GeometryUtils = { - merge: function ( geometry1, geometry2, materialIndexOffset ) { + merge: function ( geometry1, geometry2, materialIndexOffset ) { - console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); - var matrix; + console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); + var matrix; - if ( geometry2.isMesh ) { + if ( geometry2.isMesh ) { - geometry2.matrixAutoUpdate && geometry2.updateMatrix(); + geometry2.matrixAutoUpdate && geometry2.updateMatrix(); - matrix = geometry2.matrix; - geometry2 = geometry2.geometry; + matrix = geometry2.matrix; + geometry2 = geometry2.geometry; - } + } - geometry1.merge( geometry2, matrix, materialIndexOffset ); + geometry1.merge( geometry2, matrix, materialIndexOffset ); - }, + }, - center: function ( geometry ) { + center: function ( geometry ) { - console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); - return geometry.center(); + console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); + return geometry.center(); - } + } - }; +}; - ImageUtils.crossOrigin = undefined; +ImageUtils.crossOrigin = undefined; - ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { +ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { - console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); + console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); - var loader = new TextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); + var loader = new TextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - var texture = loader.load( url, onLoad, undefined, onError ); + var texture = loader.load( url, onLoad, undefined, onError ); - if ( mapping ) { texture.mapping = mapping; } + if ( mapping ) texture.mapping = mapping; - return texture; + return texture; - }; +}; - ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { +ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { - console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); + console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); - var loader = new CubeTextureLoader(); - loader.setCrossOrigin( this.crossOrigin ); + var loader = new CubeTextureLoader(); + loader.setCrossOrigin( this.crossOrigin ); - var texture = loader.load( urls, onLoad, undefined, onError ); + var texture = loader.load( urls, onLoad, undefined, onError ); - if ( mapping ) { texture.mapping = mapping; } + if ( mapping ) texture.mapping = mapping; - return texture; + return texture; - }; +}; - ImageUtils.loadCompressedTexture = function () { +ImageUtils.loadCompressedTexture = function () { - console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); + console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); - }; +}; - ImageUtils.loadCompressedTextureCube = function () { +ImageUtils.loadCompressedTextureCube = function () { - console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); + console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); - }; +}; - // +// - function CanvasRenderer() { +function CanvasRenderer() { - console.error( 'THREE.CanvasRenderer has been removed' ); + console.error( 'THREE.CanvasRenderer has been removed' ); - } +} - // +// - function JSONLoader() { +function JSONLoader() { - console.error( 'THREE.JSONLoader has been removed.' ); + console.error( 'THREE.JSONLoader has been removed.' ); - } +} - // +// - var SceneUtils = { +var SceneUtils = { - createMultiMaterialObject: function ( /* geometry, materials */ ) { + createMultiMaterialObject: function ( /* geometry, materials */ ) { - console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - }, + }, - detach: function ( /* child, parent, scene */ ) { + detach: function ( /* child, parent, scene */ ) { - console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - }, + }, - attach: function ( /* child, scene, parent */ ) { + attach: function ( /* child, scene, parent */ ) { - console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' ); - } + } - }; +}; - // +// - function LensFlare() { +function LensFlare() { - console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' ); + console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' ); - } +} - if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { +if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { + + /* eslint-disable no-undef */ + __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { + revision: REVISION, + } } ) ); + /* eslint-enable no-undef */ + +} - /* eslint-disable no-undef */ - __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { - revision: REVISION, - } } ) ); - /* eslint-enable no-undef */ - - } - - exports.ACESFilmicToneMapping = ACESFilmicToneMapping; - exports.AddEquation = AddEquation; - exports.AddOperation = AddOperation; - exports.AdditiveBlending = AdditiveBlending; - exports.AlphaFormat = AlphaFormat; - exports.AlwaysDepth = AlwaysDepth; - exports.AlwaysStencilFunc = AlwaysStencilFunc; - exports.AmbientLight = AmbientLight; - exports.AmbientLightProbe = AmbientLightProbe; - exports.AnimationClip = AnimationClip; - exports.AnimationLoader = AnimationLoader; - exports.AnimationMixer = AnimationMixer; - exports.AnimationObjectGroup = AnimationObjectGroup; - exports.AnimationUtils = AnimationUtils; - exports.ArcCurve = ArcCurve; - exports.ArrayCamera = ArrayCamera; - exports.ArrowHelper = ArrowHelper; - exports.Audio = Audio; - exports.AudioAnalyser = AudioAnalyser; - exports.AudioContext = AudioContext; - exports.AudioListener = AudioListener; - exports.AudioLoader = AudioLoader; - exports.AxesHelper = AxesHelper; - exports.AxisHelper = AxisHelper; - exports.BackSide = BackSide; - exports.BasicDepthPacking = BasicDepthPacking; - exports.BasicShadowMap = BasicShadowMap; - exports.BinaryTextureLoader = BinaryTextureLoader; - exports.Bone = Bone; - exports.BooleanKeyframeTrack = BooleanKeyframeTrack; - exports.BoundingBoxHelper = BoundingBoxHelper; - exports.Box2 = Box2; - exports.Box3 = Box3; - exports.Box3Helper = Box3Helper; - exports.BoxBufferGeometry = BoxBufferGeometry; - exports.BoxGeometry = BoxGeometry; - exports.BoxHelper = BoxHelper; - exports.BufferAttribute = BufferAttribute; - exports.BufferGeometry = BufferGeometry; - exports.BufferGeometryLoader = BufferGeometryLoader; - exports.ByteType = ByteType; - exports.Cache = Cache; - exports.Camera = Camera; - exports.CameraHelper = CameraHelper; - exports.CanvasRenderer = CanvasRenderer; - exports.CanvasTexture = CanvasTexture; - exports.CatmullRomCurve3 = CatmullRomCurve3; - exports.CineonToneMapping = CineonToneMapping; - exports.CircleBufferGeometry = CircleBufferGeometry; - exports.CircleGeometry = CircleGeometry; - exports.ClampToEdgeWrapping = ClampToEdgeWrapping; - exports.Clock = Clock; - exports.ClosedSplineCurve3 = ClosedSplineCurve3; - exports.Color = Color; - exports.ColorKeyframeTrack = ColorKeyframeTrack; - exports.CompressedTexture = CompressedTexture; - exports.CompressedTextureLoader = CompressedTextureLoader; - exports.ConeBufferGeometry = ConeBufferGeometry; - exports.ConeGeometry = ConeGeometry; - exports.CubeCamera = CubeCamera; - exports.CubeGeometry = BoxGeometry; - exports.CubeReflectionMapping = CubeReflectionMapping; - exports.CubeRefractionMapping = CubeRefractionMapping; - exports.CubeTexture = CubeTexture; - exports.CubeTextureLoader = CubeTextureLoader; - exports.CubeUVReflectionMapping = CubeUVReflectionMapping; - exports.CubeUVRefractionMapping = CubeUVRefractionMapping; - exports.CubicBezierCurve = CubicBezierCurve; - exports.CubicBezierCurve3 = CubicBezierCurve3; - exports.CubicInterpolant = CubicInterpolant; - exports.CullFaceBack = CullFaceBack; - exports.CullFaceFront = CullFaceFront; - exports.CullFaceFrontBack = CullFaceFrontBack; - exports.CullFaceNone = CullFaceNone; - exports.Curve = Curve; - exports.CurvePath = CurvePath; - exports.CustomBlending = CustomBlending; - exports.CylinderBufferGeometry = CylinderBufferGeometry; - exports.CylinderGeometry = CylinderGeometry; - exports.Cylindrical = Cylindrical; - exports.DataTexture = DataTexture; - exports.DataTexture2DArray = DataTexture2DArray; - exports.DataTexture3D = DataTexture3D; - exports.DataTextureLoader = DataTextureLoader; - exports.DecrementStencilOp = DecrementStencilOp; - exports.DecrementWrapStencilOp = DecrementWrapStencilOp; - exports.DefaultLoadingManager = DefaultLoadingManager; - exports.DepthFormat = DepthFormat; - exports.DepthStencilFormat = DepthStencilFormat; - exports.DepthTexture = DepthTexture; - exports.DirectionalLight = DirectionalLight; - exports.DirectionalLightHelper = DirectionalLightHelper; - exports.DirectionalLightShadow = DirectionalLightShadow; - exports.DiscreteInterpolant = DiscreteInterpolant; - exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry; - exports.DodecahedronGeometry = DodecahedronGeometry; - exports.DoubleSide = DoubleSide; - exports.DstAlphaFactor = DstAlphaFactor; - exports.DstColorFactor = DstColorFactor; - exports.DynamicBufferAttribute = DynamicBufferAttribute; - exports.DynamicCopyUsage = DynamicCopyUsage; - exports.DynamicDrawUsage = DynamicDrawUsage; - exports.DynamicReadUsage = DynamicReadUsage; - exports.EdgesGeometry = EdgesGeometry; - exports.EdgesHelper = EdgesHelper; - exports.EllipseCurve = EllipseCurve; - exports.EqualDepth = EqualDepth; - exports.EqualStencilFunc = EqualStencilFunc; - exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; - exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; - exports.Euler = Euler; - exports.EventDispatcher = EventDispatcher; - exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry; - exports.ExtrudeGeometry = ExtrudeGeometry; - exports.Face3 = Face3; - exports.Face4 = Face4; - exports.FaceColors = FaceColors; - exports.FaceNormalsHelper = FaceNormalsHelper; - exports.FileLoader = FileLoader; - exports.FlatShading = FlatShading; - exports.Float32Attribute = Float32Attribute; - exports.Float32BufferAttribute = Float32BufferAttribute; - exports.Float64Attribute = Float64Attribute; - exports.Float64BufferAttribute = Float64BufferAttribute; - exports.FloatType = FloatType; - exports.Fog = Fog; - exports.FogExp2 = FogExp2; - exports.Font = Font; - exports.FontLoader = FontLoader; - exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; - exports.FrontFaceDirectionCW = FrontFaceDirectionCW; - exports.FrontSide = FrontSide; - exports.Frustum = Frustum; - exports.GammaEncoding = GammaEncoding; - exports.Geometry = Geometry; - exports.GeometryUtils = GeometryUtils; - exports.GreaterDepth = GreaterDepth; - exports.GreaterEqualDepth = GreaterEqualDepth; - exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc; - exports.GreaterStencilFunc = GreaterStencilFunc; - exports.GridHelper = GridHelper; - exports.Group = Group; - exports.HalfFloatType = HalfFloatType; - exports.HemisphereLight = HemisphereLight; - exports.HemisphereLightHelper = HemisphereLightHelper; - exports.HemisphereLightProbe = HemisphereLightProbe; - exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry; - exports.IcosahedronGeometry = IcosahedronGeometry; - exports.ImageBitmapLoader = ImageBitmapLoader; - exports.ImageLoader = ImageLoader; - exports.ImageUtils = ImageUtils; - exports.ImmediateRenderObject = ImmediateRenderObject; - exports.IncrementStencilOp = IncrementStencilOp; - exports.IncrementWrapStencilOp = IncrementWrapStencilOp; - exports.InstancedBufferAttribute = InstancedBufferAttribute; - exports.InstancedBufferGeometry = InstancedBufferGeometry; - exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; - exports.InstancedMesh = InstancedMesh; - exports.Int16Attribute = Int16Attribute; - exports.Int16BufferAttribute = Int16BufferAttribute; - exports.Int32Attribute = Int32Attribute; - exports.Int32BufferAttribute = Int32BufferAttribute; - exports.Int8Attribute = Int8Attribute; - exports.Int8BufferAttribute = Int8BufferAttribute; - exports.IntType = IntType; - exports.InterleavedBuffer = InterleavedBuffer; - exports.InterleavedBufferAttribute = InterleavedBufferAttribute; - exports.Interpolant = Interpolant; - exports.InterpolateDiscrete = InterpolateDiscrete; - exports.InterpolateLinear = InterpolateLinear; - exports.InterpolateSmooth = InterpolateSmooth; - exports.InvertStencilOp = InvertStencilOp; - exports.JSONLoader = JSONLoader; - exports.KeepStencilOp = KeepStencilOp; - exports.KeyframeTrack = KeyframeTrack; - exports.LOD = LOD; - exports.LatheBufferGeometry = LatheBufferGeometry; - exports.LatheGeometry = LatheGeometry; - exports.Layers = Layers; - exports.LensFlare = LensFlare; - exports.LessDepth = LessDepth; - exports.LessEqualDepth = LessEqualDepth; - exports.LessEqualStencilFunc = LessEqualStencilFunc; - exports.LessStencilFunc = LessStencilFunc; - exports.Light = Light; - exports.LightProbe = LightProbe; - exports.LightProbeHelper = LightProbeHelper; - exports.LightShadow = LightShadow; - exports.Line = Line; - exports.Line3 = Line3; - exports.LineBasicMaterial = LineBasicMaterial; - exports.LineCurve = LineCurve; - exports.LineCurve3 = LineCurve3; - exports.LineDashedMaterial = LineDashedMaterial; - exports.LineLoop = LineLoop; - exports.LinePieces = LinePieces; - exports.LineSegments = LineSegments; - exports.LineStrip = LineStrip; - exports.LinearEncoding = LinearEncoding; - exports.LinearFilter = LinearFilter; - exports.LinearInterpolant = LinearInterpolant; - exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; - exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; - exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter; - exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter; - exports.LinearToneMapping = LinearToneMapping; - exports.Loader = Loader; - exports.LoaderUtils = LoaderUtils; - exports.LoadingManager = LoadingManager; - exports.LogLuvEncoding = LogLuvEncoding; - exports.LoopOnce = LoopOnce; - exports.LoopPingPong = LoopPingPong; - exports.LoopRepeat = LoopRepeat; - exports.LuminanceAlphaFormat = LuminanceAlphaFormat; - exports.LuminanceFormat = LuminanceFormat; - exports.MOUSE = MOUSE; - exports.Material = Material; - exports.MaterialLoader = MaterialLoader; - exports.Math = _Math; - exports.Matrix3 = Matrix3; - exports.Matrix4 = Matrix4; - exports.MaxEquation = MaxEquation; - exports.Mesh = Mesh; - exports.MeshBasicMaterial = MeshBasicMaterial; - exports.MeshDepthMaterial = MeshDepthMaterial; - exports.MeshDistanceMaterial = MeshDistanceMaterial; - exports.MeshFaceMaterial = MeshFaceMaterial; - exports.MeshLambertMaterial = MeshLambertMaterial; - exports.MeshMatcapMaterial = MeshMatcapMaterial; - exports.MeshNormalMaterial = MeshNormalMaterial; - exports.MeshPhongMaterial = MeshPhongMaterial; - exports.MeshPhysicalMaterial = MeshPhysicalMaterial; - exports.MeshStandardMaterial = MeshStandardMaterial; - exports.MeshToonMaterial = MeshToonMaterial; - exports.MinEquation = MinEquation; - exports.MirroredRepeatWrapping = MirroredRepeatWrapping; - exports.MixOperation = MixOperation; - exports.MultiMaterial = MultiMaterial; - exports.MultiplyBlending = MultiplyBlending; - exports.MultiplyOperation = MultiplyOperation; - exports.NearestFilter = NearestFilter; - exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; - exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; - exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; - exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; - exports.NeverDepth = NeverDepth; - exports.NeverStencilFunc = NeverStencilFunc; - exports.NoBlending = NoBlending; - exports.NoColors = NoColors; - exports.NoToneMapping = NoToneMapping; - exports.NormalBlending = NormalBlending; - exports.NotEqualDepth = NotEqualDepth; - exports.NotEqualStencilFunc = NotEqualStencilFunc; - exports.NumberKeyframeTrack = NumberKeyframeTrack; - exports.Object3D = Object3D; - exports.ObjectLoader = ObjectLoader; - exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap; - exports.OctahedronBufferGeometry = OctahedronBufferGeometry; - exports.OctahedronGeometry = OctahedronGeometry; - exports.OneFactor = OneFactor; - exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; - exports.OneMinusDstColorFactor = OneMinusDstColorFactor; - exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; - exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; - exports.OrthographicCamera = OrthographicCamera; - exports.PCFShadowMap = PCFShadowMap; - exports.PCFSoftShadowMap = PCFSoftShadowMap; - exports.ParametricBufferGeometry = ParametricBufferGeometry; - exports.ParametricGeometry = ParametricGeometry; - exports.Particle = Particle; - exports.ParticleBasicMaterial = ParticleBasicMaterial; - exports.ParticleSystem = ParticleSystem; - exports.ParticleSystemMaterial = ParticleSystemMaterial; - exports.Path = Path; - exports.PerspectiveCamera = PerspectiveCamera; - exports.Plane = Plane; - exports.PlaneBufferGeometry = PlaneBufferGeometry; - exports.PlaneGeometry = PlaneGeometry; - exports.PlaneHelper = PlaneHelper; - exports.PointCloud = PointCloud; - exports.PointCloudMaterial = PointCloudMaterial; - exports.PointLight = PointLight; - exports.PointLightHelper = PointLightHelper; - exports.Points = Points; - exports.PointsMaterial = PointsMaterial; - exports.PolarGridHelper = PolarGridHelper; - exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry; - exports.PolyhedronGeometry = PolyhedronGeometry; - exports.PositionalAudio = PositionalAudio; - exports.PositionalAudioHelper = PositionalAudioHelper; - exports.PropertyBinding = PropertyBinding; - exports.PropertyMixer = PropertyMixer; - exports.QuadraticBezierCurve = QuadraticBezierCurve; - exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; - exports.Quaternion = Quaternion; - exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; - exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; - exports.REVISION = REVISION; - exports.RGBADepthPacking = RGBADepthPacking; - exports.RGBAFormat = RGBAFormat; - exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; - exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; - exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; - exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; - exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; - exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; - exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; - exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; - exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; - exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; - exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; - exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; - exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; - exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; - exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; - exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; - exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; - exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; - exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; - exports.RGBDEncoding = RGBDEncoding; - exports.RGBEEncoding = RGBEEncoding; - exports.RGBEFormat = RGBEFormat; - exports.RGBFormat = RGBFormat; - exports.RGBM16Encoding = RGBM16Encoding; - exports.RGBM7Encoding = RGBM7Encoding; - exports.RGB_ETC1_Format = RGB_ETC1_Format; - exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; - exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; - exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; - exports.RawShaderMaterial = RawShaderMaterial; - exports.Ray = Ray; - exports.Raycaster = Raycaster; - exports.RectAreaLight = RectAreaLight; - exports.RectAreaLightHelper = RectAreaLightHelper; - exports.RedFormat = RedFormat; - exports.ReinhardToneMapping = ReinhardToneMapping; - exports.RepeatWrapping = RepeatWrapping; - exports.ReplaceStencilOp = ReplaceStencilOp; - exports.ReverseSubtractEquation = ReverseSubtractEquation; - exports.RingBufferGeometry = RingBufferGeometry; - exports.RingGeometry = RingGeometry; - exports.Scene = Scene; - exports.SceneUtils = SceneUtils; - exports.ShaderChunk = ShaderChunk; - exports.ShaderLib = ShaderLib; - exports.ShaderMaterial = ShaderMaterial; - exports.ShadowMaterial = ShadowMaterial; - exports.Shape = Shape; - exports.ShapeBufferGeometry = ShapeBufferGeometry; - exports.ShapeGeometry = ShapeGeometry; - exports.ShapePath = ShapePath; - exports.ShapeUtils = ShapeUtils; - exports.ShortType = ShortType; - exports.Skeleton = Skeleton; - exports.SkeletonHelper = SkeletonHelper; - exports.SkinnedMesh = SkinnedMesh; - exports.SmoothShading = SmoothShading; - exports.Sphere = Sphere; - exports.SphereBufferGeometry = SphereBufferGeometry; - exports.SphereGeometry = SphereGeometry; - exports.Spherical = Spherical; - exports.SphericalHarmonics3 = SphericalHarmonics3; - exports.SphericalReflectionMapping = SphericalReflectionMapping; - exports.Spline = Spline; - exports.SplineCurve = SplineCurve; - exports.SplineCurve3 = SplineCurve3; - exports.SpotLight = SpotLight; - exports.SpotLightHelper = SpotLightHelper; - exports.SpotLightShadow = SpotLightShadow; - exports.Sprite = Sprite; - exports.SpriteMaterial = SpriteMaterial; - exports.SrcAlphaFactor = SrcAlphaFactor; - exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; - exports.SrcColorFactor = SrcColorFactor; - exports.StaticCopyUsage = StaticCopyUsage; - exports.StaticDrawUsage = StaticDrawUsage; - exports.StaticReadUsage = StaticReadUsage; - exports.StereoCamera = StereoCamera; - exports.StreamCopyUsage = StreamCopyUsage; - exports.StreamDrawUsage = StreamDrawUsage; - exports.StreamReadUsage = StreamReadUsage; - exports.StringKeyframeTrack = StringKeyframeTrack; - exports.SubtractEquation = SubtractEquation; - exports.SubtractiveBlending = SubtractiveBlending; - exports.TOUCH = TOUCH; - exports.TangentSpaceNormalMap = TangentSpaceNormalMap; - exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry; - exports.TetrahedronGeometry = TetrahedronGeometry; - exports.TextBufferGeometry = TextBufferGeometry; - exports.TextGeometry = TextGeometry; - exports.Texture = Texture; - exports.TextureLoader = TextureLoader; - exports.TorusBufferGeometry = TorusBufferGeometry; - exports.TorusGeometry = TorusGeometry; - exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; - exports.TorusKnotGeometry = TorusKnotGeometry; - exports.Triangle = Triangle; - exports.TriangleFanDrawMode = TriangleFanDrawMode; - exports.TriangleStripDrawMode = TriangleStripDrawMode; - exports.TrianglesDrawMode = TrianglesDrawMode; - exports.TubeBufferGeometry = TubeBufferGeometry; - exports.TubeGeometry = TubeGeometry; - exports.UVMapping = UVMapping; - exports.Uint16Attribute = Uint16Attribute; - exports.Uint16BufferAttribute = Uint16BufferAttribute; - exports.Uint32Attribute = Uint32Attribute; - exports.Uint32BufferAttribute = Uint32BufferAttribute; - exports.Uint8Attribute = Uint8Attribute; - exports.Uint8BufferAttribute = Uint8BufferAttribute; - exports.Uint8ClampedAttribute = Uint8ClampedAttribute; - exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute; - exports.Uncharted2ToneMapping = Uncharted2ToneMapping; - exports.Uniform = Uniform; - exports.UniformsLib = UniformsLib; - exports.UniformsUtils = UniformsUtils; - exports.UnsignedByteType = UnsignedByteType; - exports.UnsignedInt248Type = UnsignedInt248Type; - exports.UnsignedIntType = UnsignedIntType; - exports.UnsignedShort4444Type = UnsignedShort4444Type; - exports.UnsignedShort5551Type = UnsignedShort5551Type; - exports.UnsignedShort565Type = UnsignedShort565Type; - exports.UnsignedShortType = UnsignedShortType; - exports.VSMShadowMap = VSMShadowMap; - exports.Vector2 = Vector2; - exports.Vector3 = Vector3; - exports.Vector4 = Vector4; - exports.VectorKeyframeTrack = VectorKeyframeTrack; - exports.Vertex = Vertex; - exports.VertexColors = VertexColors; - exports.VertexNormalsHelper = VertexNormalsHelper; - exports.VideoTexture = VideoTexture; - exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget; - exports.WebGLRenderTarget = WebGLRenderTarget; - exports.WebGLRenderTargetCube = WebGLRenderTargetCube; - exports.WebGLRenderer = WebGLRenderer; - exports.WebGLUtils = WebGLUtils; - exports.WireframeGeometry = WireframeGeometry; - exports.WireframeHelper = WireframeHelper; - exports.WrapAroundEnding = WrapAroundEnding; - exports.XHRLoader = XHRLoader; - exports.ZeroCurvatureEnding = ZeroCurvatureEnding; - exports.ZeroFactor = ZeroFactor; - exports.ZeroSlopeEnding = ZeroSlopeEnding; - exports.ZeroStencilOp = ZeroStencilOp; - exports.sRGBEncoding = sRGBEncoding; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); +export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, BoxGeometry as CubeGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGLCubeRenderTarget, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding }; +const THREE = { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeGeometry: BoxGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, Math: MathUtils, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGLCubeRenderTarget, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding }; +export default THREE; \ No newline at end of file From b59c2a03fb05d6271519faeed514a8293df68aeb Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 13:06:45 -0600 Subject: [PATCH 05/11] Update OrbitControls from XRPackage Add OrbitControls.js - commit 5837f95e53bacef1721b14353a5e48ec2436c18c from XRPackage --- OrbitControls.js | 200 +++++++++++++++++++++-------------------------- 1 file changed, 91 insertions(+), 109 deletions(-) diff --git a/OrbitControls.js b/OrbitControls.js index 82a9a85..aa85d28 100644 --- a/OrbitControls.js +++ b/OrbitControls.js @@ -7,6 +7,16 @@ * @author ScieCode / http://github.com/sciecode */ +import { + EventDispatcher, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3 +} from "./three.js"; + // This set of controls performs orbiting, dollying (zooming), and panning. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). // @@ -14,7 +24,7 @@ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move -THREE.OrbitControls = function ( object, domElement ) { +var OrbitControls = function ( object, domElement, document ) { if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); @@ -26,7 +36,7 @@ THREE.OrbitControls = function ( object, domElement ) { this.enabled = true; // "target" sets the location of focus, where the object orbits around - this.target = new THREE.Vector3(); + this.target = new Vector3(); // How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0; @@ -78,10 +88,10 @@ THREE.OrbitControls = function ( object, domElement ) { this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; // Mouse buttons - this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }; + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; // Touch fingers - this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN }; + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; // for reset this.target0 = this.target.clone(); @@ -130,14 +140,14 @@ THREE.OrbitControls = function ( object, domElement ) { // this method is exposed, but perhaps it would be better if we can make it private... this.update = function () { - var offset = new THREE.Vector3(); + var offset = new Vector3(); // so camera.up is the orbit axis - var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); + var quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); var quatInverse = quat.clone().inverse(); - var lastPosition = new THREE.Vector3(); - var lastQuaternion = new THREE.Quaternion(); + var lastPosition = new Vector3(); + var lastQuaternion = new Quaternion(); return function update() { @@ -290,24 +300,24 @@ THREE.OrbitControls = function ( object, domElement ) { var EPS = 0.000001; // current position in spherical coordinates - var spherical = new THREE.Spherical(); - var sphericalDelta = new THREE.Spherical(); + var spherical = new Spherical(); + var sphericalDelta = new Spherical(); var scale = 1; - var panOffset = new THREE.Vector3(); + var panOffset = new Vector3(); var zoomChanged = false; - var rotateStart = new THREE.Vector2(); - var rotateEnd = new THREE.Vector2(); - var rotateDelta = new THREE.Vector2(); + var rotateStart = new Vector2(); + var rotateEnd = new Vector2(); + var rotateDelta = new Vector2(); - var panStart = new THREE.Vector2(); - var panEnd = new THREE.Vector2(); - var panDelta = new THREE.Vector2(); + var panStart = new Vector2(); + var panEnd = new Vector2(); + var panDelta = new Vector2(); - var dollyStart = new THREE.Vector2(); - var dollyEnd = new THREE.Vector2(); - var dollyDelta = new THREE.Vector2(); + var dollyStart = new Vector2(); + var dollyEnd = new Vector2(); + var dollyDelta = new Vector2(); function getAutoRotationAngle() { @@ -335,7 +345,7 @@ THREE.OrbitControls = function ( object, domElement ) { var panLeft = function () { - var v = new THREE.Vector3(); + var v = new Vector3(); return function panLeft( distance, objectMatrix ) { @@ -350,7 +360,7 @@ THREE.OrbitControls = function ( object, domElement ) { var panUp = function () { - var v = new THREE.Vector3(); + var v = new Vector3(); return function panUp( distance, objectMatrix ) { @@ -376,7 +386,7 @@ THREE.OrbitControls = function ( object, domElement ) { // deltaX and deltaY are in pixels; right and down are positive var pan = function () { - var offset = new THREE.Vector3(); + var offset = new Vector3(); return function pan( deltaX, deltaY ) { @@ -753,7 +763,6 @@ THREE.OrbitControls = function ( object, domElement ) { if ( scope.enabled === false ) return; // Prevent the browser from scrolling. - event.preventDefault(); // Manually set the focus since calling preventDefault above @@ -761,119 +770,90 @@ THREE.OrbitControls = function ( object, domElement ) { scope.domElement.focus ? scope.domElement.focus() : window.focus(); + var mouseAction; + switch ( event.button ) { case 0: - switch ( scope.mouseButtons.LEFT ) { - - case THREE.MOUSE.ROTATE: - - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + mouseAction = scope.mouseButtons.LEFT; + break; - if ( scope.enablePan === false ) return; + case 1: - handleMouseDownPan( event ); + mouseAction = scope.mouseButtons.MIDDLE; + break; - state = STATE.PAN; + case 2: - } else { + mouseAction = scope.mouseButtons.RIGHT; + break; - if ( scope.enableRotate === false ) return; + default: - handleMouseDownRotate( event ); + mouseAction = - 1; - state = STATE.ROTATE; + } - } + switch ( mouseAction ) { - break; + case MOUSE.DOLLY: - case THREE.MOUSE.PAN: + if ( scope.enableZoom === false ) return; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + handleMouseDownDolly( event ); - if ( scope.enableRotate === false ) return; + state = STATE.DOLLY; - handleMouseDownRotate( event ); + break; - state = STATE.ROTATE; + case MOUSE.ROTATE: - } else { + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - if ( scope.enablePan === false ) return; + if ( scope.enablePan === false ) return; - handleMouseDownPan( event ); + handleMouseDownPan( event ); - state = STATE.PAN; + state = STATE.PAN; - } + } else { - break; + if ( scope.enableRotate === false ) return; - default: + handleMouseDownRotate( event ); - state = STATE.NONE; + state = STATE.ROTATE; } break; + case MOUSE.PAN: - case 1: + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - switch ( scope.mouseButtons.MIDDLE ) { + if ( scope.enableRotate === false ) return; - case THREE.MOUSE.DOLLY: + handleMouseDownRotate( event ); - if ( scope.enableZoom === false ) return; + state = STATE.ROTATE; - handleMouseDownDolly( event ); + } else { - state = STATE.DOLLY; + if ( scope.enablePan === false ) return; - break; + handleMouseDownPan( event ); - - default: - - state = STATE.NONE; + state = STATE.PAN; } break; - case 2: - - switch ( scope.mouseButtons.RIGHT ) { - - case THREE.MOUSE.ROTATE: - - if ( scope.enableRotate === false ) return; - - handleMouseDownRotate( event ); - - state = STATE.ROTATE; - - break; - - case THREE.MOUSE.PAN: - - if ( scope.enablePan === false ) return; - - handleMouseDownPan( event ); - - state = STATE.PAN; - - break; - - default: - - state = STATE.NONE; - - } + default: - break; + state = STATE.NONE; } @@ -943,7 +923,7 @@ THREE.OrbitControls = function ( object, domElement ) { if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; - event.preventDefault(); + // event.preventDefault(); event.stopPropagation(); scope.dispatchEvent( startEvent ); @@ -966,7 +946,7 @@ THREE.OrbitControls = function ( object, domElement ) { if ( scope.enabled === false ) return; - event.preventDefault(); + event.preventDefault(); // prevent scrolling switch ( event.touches.length ) { @@ -974,7 +954,7 @@ THREE.OrbitControls = function ( object, domElement ) { switch ( scope.touches.ONE ) { - case THREE.TOUCH.ROTATE: + case TOUCH.ROTATE: if ( scope.enableRotate === false ) return; @@ -984,7 +964,7 @@ THREE.OrbitControls = function ( object, domElement ) { break; - case THREE.TOUCH.PAN: + case TOUCH.PAN: if ( scope.enablePan === false ) return; @@ -1006,7 +986,7 @@ THREE.OrbitControls = function ( object, domElement ) { switch ( scope.touches.TWO ) { - case THREE.TOUCH.DOLLY_PAN: + case TOUCH.DOLLY_PAN: if ( scope.enableZoom === false && scope.enablePan === false ) return; @@ -1016,7 +996,7 @@ THREE.OrbitControls = function ( object, domElement ) { break; - case THREE.TOUCH.DOLLY_ROTATE: + case TOUCH.DOLLY_ROTATE: if ( scope.enableZoom === false && scope.enableRotate === false ) return; @@ -1052,7 +1032,7 @@ THREE.OrbitControls = function ( object, domElement ) { if ( scope.enabled === false ) return; - event.preventDefault(); + event.preventDefault(); // prevent scrolling event.stopPropagation(); switch ( state ) { @@ -1152,8 +1132,8 @@ THREE.OrbitControls = function ( object, domElement ) { }; -THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); -THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; +OrbitControls.prototype = Object.create( EventDispatcher.prototype ); +OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning. @@ -1164,17 +1144,19 @@ THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - left mouse, or arrow keys / touch: one-finger move -THREE.MapControls = function ( object, domElement ) { +var MapControls = function ( object, domElement ) { - THREE.OrbitControls.call( this, object, domElement ); + OrbitControls.call( this, object, domElement ); - this.mouseButtons.LEFT = THREE.MOUSE.PAN; - this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE; + this.mouseButtons.LEFT = MOUSE.PAN; + this.mouseButtons.RIGHT = MOUSE.ROTATE; - this.touches.ONE = THREE.TOUCH.PAN; - this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE; + this.touches.ONE = TOUCH.PAN; + this.touches.TWO = TOUCH.DOLLY_ROTATE; }; -THREE.MapControls.prototype = Object.create( THREE.EventDispatcher.prototype ); -THREE.MapControls.prototype.constructor = THREE.MapControls; +MapControls.prototype = Object.create( EventDispatcher.prototype ); +MapControls.prototype.constructor = MapControls; + +export { OrbitControls, MapControls }; From 5c5442734f81628cc70a8370b1c7354820f97fe2 Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Tue, 16 Jun 2020 13:22:03 -0600 Subject: [PATCH 06/11] updated imports --- Reflector.js | 1 + avatars.js | 2 +- vrarmik/ArmTransforms.js | 2 ++ vrarmik/LegsManager.js | 1 + vrarmik/ShoulderPoser.js | 1 + vrarmik/ShoulderTransforms.js | 1 + vrarmik/SkeletonUtils.js | 2 ++ vrarmik/Unity.js | 2 ++ vrarmik/VRArmIK.js | 1 + vrarmik/VRTrackingReferences.js | 2 ++ vrarmik/three-vrm.js | 2 ++ 11 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Reflector.js b/Reflector.js index 6c7533a..7814e19 100644 --- a/Reflector.js +++ b/Reflector.js @@ -1,6 +1,7 @@ /** * @author Slayvin / http://slayvin.net */ +import THREE from './three.js'; THREE.Reflector = function ( geometry, options ) { diff --git a/avatars.js b/avatars.js index 8e08448..54dbc30 100644 --- a/avatars.js +++ b/avatars.js @@ -1,4 +1,4 @@ -import THREE from '../three.module.js'; +import THREE from '../three.js'; import './vrarmik/three-vrm.js'; import {fixSkeletonZForward} from './vrarmik/SkeletonUtils.js'; import PoseManager from './vrarmik/PoseManager.js'; diff --git a/vrarmik/ArmTransforms.js b/vrarmik/ArmTransforms.js index e0f9b5e..993cf24 100644 --- a/vrarmik/ArmTransforms.js +++ b/vrarmik/ArmTransforms.js @@ -1,3 +1,5 @@ +import THREE from '../three.js'; + class ArmTransforms { constructor() { diff --git a/vrarmik/LegsManager.js b/vrarmik/LegsManager.js index ce3ec53..1933c6d 100644 --- a/vrarmik/LegsManager.js +++ b/vrarmik/LegsManager.js @@ -1,3 +1,4 @@ +import THREE from '../three.js'; import {Helpers} from './Unity.js'; const stepRate = 0.2; diff --git a/vrarmik/ShoulderPoser.js b/vrarmik/ShoulderPoser.js index 27ef53c..31ea6f2 100644 --- a/vrarmik/ShoulderPoser.js +++ b/vrarmik/ShoulderPoser.js @@ -1,3 +1,4 @@ +import THREE from '../three.js'; import {Helpers} from './Unity.js'; const rightVector = new THREE.Vector3(1, 0, 0); diff --git a/vrarmik/ShoulderTransforms.js b/vrarmik/ShoulderTransforms.js index 30dcfe4..0af7ffe 100644 --- a/vrarmik/ShoulderTransforms.js +++ b/vrarmik/ShoulderTransforms.js @@ -1,3 +1,4 @@ +import THREE from '../three.js'; import ArmTransforms from './ArmTransforms.js'; import ShoulderPoser from './ShoulderPoser.js'; import VRArmIK from './VRArmIK.js'; diff --git a/vrarmik/SkeletonUtils.js b/vrarmik/SkeletonUtils.js index fd82960..541532b 100644 --- a/vrarmik/SkeletonUtils.js +++ b/vrarmik/SkeletonUtils.js @@ -1,3 +1,5 @@ +import THREE from '../three.js'; + /** * Takes in a rootBone and recursively traverses the bone heirarchy, * setting each bone's +Z axis to face it's child bones. The IK system follows this diff --git a/vrarmik/Unity.js b/vrarmik/Unity.js index 9039b53..2537f8f 100644 --- a/vrarmik/Unity.js +++ b/vrarmik/Unity.js @@ -1,3 +1,5 @@ +import THREE from '../three.js'; + const localVector = new THREE.Vector3(); const localVector2 = new THREE.Vector3(); const Helpers = { diff --git a/vrarmik/VRArmIK.js b/vrarmik/VRArmIK.js index 452fe53..8dfb59d 100644 --- a/vrarmik/VRArmIK.js +++ b/vrarmik/VRArmIK.js @@ -1,3 +1,4 @@ +import THREE from '../three.js'; import {Helpers} from './Unity.js'; const zeroVector = new THREE.Vector3(); diff --git a/vrarmik/VRTrackingReferences.js b/vrarmik/VRTrackingReferences.js index c58358e..ec05eea 100644 --- a/vrarmik/VRTrackingReferences.js +++ b/vrarmik/VRTrackingReferences.js @@ -1,3 +1,5 @@ +import THREE from '../three.js'; + class VRTrackingReferences { constructor() { /* this.leftController = new Transform(); diff --git a/vrarmik/three-vrm.js b/vrarmik/three-vrm.js index 0dea3c6..e60451a 100644 --- a/vrarmik/three-vrm.js +++ b/vrarmik/three-vrm.js @@ -1,3 +1,5 @@ +import THREE from '../three.js'; + var __three_vrm__ = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache From 9515ad82fe6a9d2a08047fda7b954e670ffe4168 Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Wed, 17 Jun 2020 11:58:27 -0600 Subject: [PATCH 07/11] some fixes for html imports --- GLTFLoader.js | 2 +- index.html | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GLTFLoader.js b/GLTFLoader.js index 0189341..1c92f11 100644 --- a/GLTFLoader.js +++ b/GLTFLoader.js @@ -67,7 +67,7 @@ import { Vector3, VectorKeyframeTrack, sRGBEncoding -} from "./three.module.js"; +} from "./three.js"; var GLTFLoader = ( function () { diff --git a/index.html b/index.html index 316db8c..a777d08 100644 --- a/index.html +++ b/index.html @@ -305,10 +305,10 @@ padding: 0 30px; } - - - - + + + +
From 65129f8f48a21643065f8d47d7d3e6af160abaaa Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Wed, 17 Jun 2020 19:11:24 -0600 Subject: [PATCH 08/11] testing three import in index.html --- index.html | 6 ++++-- index.js | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index a777d08..134d32e 100644 --- a/index.html +++ b/index.html @@ -305,10 +305,12 @@ padding: 0 30px; } - + - +
diff --git a/index.js b/index.js index 9e55d52..9c6512c 100755 --- a/index.js +++ b/index.js @@ -15,3 +15,5 @@ https.createServer({ .listen(443) console.log(`https://dev.exokit.org`); + +app.listen(3009, () => console.log(`localhost:3000`)); \ No newline at end of file From bbd77b01047097ff98a52f798697983ffdd85e4d Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Wed, 17 Jun 2020 19:11:24 -0600 Subject: [PATCH 09/11] testing three import in index.html --- index.html | 6 ++++-- index.js | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index a777d08..134d32e 100644 --- a/index.html +++ b/index.html @@ -305,10 +305,12 @@ padding: 0 30px; } - + - +
diff --git a/index.js b/index.js index 9e55d52..e0b290c 100755 --- a/index.js +++ b/index.js @@ -15,3 +15,5 @@ https.createServer({ .listen(443) console.log(`https://dev.exokit.org`); + +app.listen(3100, () => console.log(`localhost:3100`)); \ No newline at end of file From 592a79053172d4e098064998bcf480170d228174 Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Thu, 18 Jun 2020 19:10:35 -0600 Subject: [PATCH 10/11] fixed errors --- GLTFLoader.js | 2 +- OrbitControls.js | 202 +++++++++++++++++--------------- Reflector.js | 8 +- avatars.js | 4 +- bmfont.js | 3 + index.html | 27 +++-- three.js => three.module.js | 3 - vrarmik/ArmTransforms.js | 2 +- vrarmik/LegsManager.js | 2 +- vrarmik/ShoulderPoser.js | 2 +- vrarmik/ShoulderTransforms.js | 2 +- vrarmik/SkeletonUtils.js | 4 +- vrarmik/Unity.js | 2 +- vrarmik/VRArmIK.js | 2 +- vrarmik/VRTrackingReferences.js | 2 +- vrarmik/three-vrm.js | 4 +- 16 files changed, 145 insertions(+), 126 deletions(-) rename three.js => three.module.js (99%) diff --git a/GLTFLoader.js b/GLTFLoader.js index 1c92f11..0189341 100644 --- a/GLTFLoader.js +++ b/GLTFLoader.js @@ -67,7 +67,7 @@ import { Vector3, VectorKeyframeTrack, sRGBEncoding -} from "./three.js"; +} from "./three.module.js"; var GLTFLoader = ( function () { diff --git a/OrbitControls.js b/OrbitControls.js index aa85d28..79aa244 100644 --- a/OrbitControls.js +++ b/OrbitControls.js @@ -6,17 +6,7 @@ * @author erich666 / http://erichaines.com * @author ScieCode / http://github.com/sciecode */ - -import { - EventDispatcher, - MOUSE, - Quaternion, - Spherical, - TOUCH, - Vector2, - Vector3 -} from "./three.js"; - +import THREE from './three.module.js'; // This set of controls performs orbiting, dollying (zooming), and panning. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). // @@ -24,7 +14,7 @@ import { // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move -var OrbitControls = function ( object, domElement, document ) { +THREE.OrbitControls = function ( object, domElement ) { if ( domElement === undefined ) console.warn( 'THREE.OrbitControls: The second parameter "domElement" is now mandatory.' ); if ( domElement === document ) console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.' ); @@ -36,7 +26,7 @@ var OrbitControls = function ( object, domElement, document ) { this.enabled = true; // "target" sets the location of focus, where the object orbits around - this.target = new Vector3(); + this.target = new THREE.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0; @@ -88,10 +78,10 @@ var OrbitControls = function ( object, domElement, document ) { this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; // Mouse buttons - this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }; // Touch fingers - this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN }; // for reset this.target0 = this.target.clone(); @@ -140,14 +130,14 @@ var OrbitControls = function ( object, domElement, document ) { // this method is exposed, but perhaps it would be better if we can make it private... this.update = function () { - var offset = new Vector3(); + var offset = new THREE.Vector3(); // so camera.up is the orbit axis - var quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); var quatInverse = quat.clone().inverse(); - var lastPosition = new Vector3(); - var lastQuaternion = new Quaternion(); + var lastPosition = new THREE.Vector3(); + var lastQuaternion = new THREE.Quaternion(); return function update() { @@ -300,24 +290,24 @@ var OrbitControls = function ( object, domElement, document ) { var EPS = 0.000001; // current position in spherical coordinates - var spherical = new Spherical(); - var sphericalDelta = new Spherical(); + var spherical = new THREE.Spherical(); + var sphericalDelta = new THREE.Spherical(); var scale = 1; - var panOffset = new Vector3(); + var panOffset = new THREE.Vector3(); var zoomChanged = false; - var rotateStart = new Vector2(); - var rotateEnd = new Vector2(); - var rotateDelta = new Vector2(); + var rotateStart = new THREE.Vector2(); + var rotateEnd = new THREE.Vector2(); + var rotateDelta = new THREE.Vector2(); - var panStart = new Vector2(); - var panEnd = new Vector2(); - var panDelta = new Vector2(); + var panStart = new THREE.Vector2(); + var panEnd = new THREE.Vector2(); + var panDelta = new THREE.Vector2(); - var dollyStart = new Vector2(); - var dollyEnd = new Vector2(); - var dollyDelta = new Vector2(); + var dollyStart = new THREE.Vector2(); + var dollyEnd = new THREE.Vector2(); + var dollyDelta = new THREE.Vector2(); function getAutoRotationAngle() { @@ -345,7 +335,7 @@ var OrbitControls = function ( object, domElement, document ) { var panLeft = function () { - var v = new Vector3(); + var v = new THREE.Vector3(); return function panLeft( distance, objectMatrix ) { @@ -360,7 +350,7 @@ var OrbitControls = function ( object, domElement, document ) { var panUp = function () { - var v = new Vector3(); + var v = new THREE.Vector3(); return function panUp( distance, objectMatrix ) { @@ -386,7 +376,7 @@ var OrbitControls = function ( object, domElement, document ) { // deltaX and deltaY are in pixels; right and down are positive var pan = function () { - var offset = new Vector3(); + var offset = new THREE.Vector3(); return function pan( deltaX, deltaY ) { @@ -763,6 +753,7 @@ var OrbitControls = function ( object, domElement, document ) { if ( scope.enabled === false ) return; // Prevent the browser from scrolling. + event.preventDefault(); // Manually set the focus since calling preventDefault above @@ -770,90 +761,119 @@ var OrbitControls = function ( object, domElement, document ) { scope.domElement.focus ? scope.domElement.focus() : window.focus(); - var mouseAction; - switch ( event.button ) { case 0: - mouseAction = scope.mouseButtons.LEFT; - break; + switch ( scope.mouseButtons.LEFT ) { - case 1: + case THREE.MOUSE.ROTATE: - mouseAction = scope.mouseButtons.MIDDLE; - break; + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - case 2: + if ( scope.enablePan === false ) return; - mouseAction = scope.mouseButtons.RIGHT; - break; + handleMouseDownPan( event ); - default: + state = STATE.PAN; - mouseAction = - 1; + } else { - } + if ( scope.enableRotate === false ) return; - switch ( mouseAction ) { + handleMouseDownRotate( event ); - case MOUSE.DOLLY: + state = STATE.ROTATE; - if ( scope.enableZoom === false ) return; + } - handleMouseDownDolly( event ); + break; - state = STATE.DOLLY; + case THREE.MOUSE.PAN: - break; + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { - case MOUSE.ROTATE: + if ( scope.enableRotate === false ) return; - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + handleMouseDownRotate( event ); - if ( scope.enablePan === false ) return; + state = STATE.ROTATE; - handleMouseDownPan( event ); + } else { - state = STATE.PAN; + if ( scope.enablePan === false ) return; - } else { + handleMouseDownPan( event ); - if ( scope.enableRotate === false ) return; + state = STATE.PAN; - handleMouseDownRotate( event ); + } - state = STATE.ROTATE; + break; + + default: + + state = STATE.NONE; } break; - case MOUSE.PAN: - if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + case 1: - if ( scope.enableRotate === false ) return; + switch ( scope.mouseButtons.MIDDLE ) { - handleMouseDownRotate( event ); + case THREE.MOUSE.DOLLY: - state = STATE.ROTATE; + if ( scope.enableZoom === false ) return; - } else { + handleMouseDownDolly( event ); - if ( scope.enablePan === false ) return; + state = STATE.DOLLY; - handleMouseDownPan( event ); + break; - state = STATE.PAN; + + default: + + state = STATE.NONE; } break; - default: + case 2: - state = STATE.NONE; + switch ( scope.mouseButtons.RIGHT ) { + + case THREE.MOUSE.ROTATE: + + if ( scope.enableRotate === false ) return; + + handleMouseDownRotate( event ); + + state = STATE.ROTATE; + + break; + + case THREE.MOUSE.PAN: + + if ( scope.enablePan === false ) return; + + handleMouseDownPan( event ); + + state = STATE.PAN; + + break; + + default: + + state = STATE.NONE; + + } + + break; } @@ -923,7 +943,7 @@ var OrbitControls = function ( object, domElement, document ) { if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; - // event.preventDefault(); + event.preventDefault(); event.stopPropagation(); scope.dispatchEvent( startEvent ); @@ -946,7 +966,7 @@ var OrbitControls = function ( object, domElement, document ) { if ( scope.enabled === false ) return; - event.preventDefault(); // prevent scrolling + event.preventDefault(); switch ( event.touches.length ) { @@ -954,7 +974,7 @@ var OrbitControls = function ( object, domElement, document ) { switch ( scope.touches.ONE ) { - case TOUCH.ROTATE: + case THREE.TOUCH.ROTATE: if ( scope.enableRotate === false ) return; @@ -964,7 +984,7 @@ var OrbitControls = function ( object, domElement, document ) { break; - case TOUCH.PAN: + case THREE.TOUCH.PAN: if ( scope.enablePan === false ) return; @@ -986,7 +1006,7 @@ var OrbitControls = function ( object, domElement, document ) { switch ( scope.touches.TWO ) { - case TOUCH.DOLLY_PAN: + case THREE.TOUCH.DOLLY_PAN: if ( scope.enableZoom === false && scope.enablePan === false ) return; @@ -996,7 +1016,7 @@ var OrbitControls = function ( object, domElement, document ) { break; - case TOUCH.DOLLY_ROTATE: + case THREE.TOUCH.DOLLY_ROTATE: if ( scope.enableZoom === false && scope.enableRotate === false ) return; @@ -1032,7 +1052,7 @@ var OrbitControls = function ( object, domElement, document ) { if ( scope.enabled === false ) return; - event.preventDefault(); // prevent scrolling + event.preventDefault(); event.stopPropagation(); switch ( state ) { @@ -1132,8 +1152,8 @@ var OrbitControls = function ( object, domElement, document ) { }; -OrbitControls.prototype = Object.create( EventDispatcher.prototype ); -OrbitControls.prototype.constructor = OrbitControls; +THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); +THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning. @@ -1144,19 +1164,17 @@ OrbitControls.prototype.constructor = OrbitControls; // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish // Pan - left mouse, or arrow keys / touch: one-finger move -var MapControls = function ( object, domElement ) { +THREE.MapControls = function ( object, domElement ) { - OrbitControls.call( this, object, domElement ); + THREE.OrbitControls.call( this, object, domElement ); - this.mouseButtons.LEFT = MOUSE.PAN; - this.mouseButtons.RIGHT = MOUSE.ROTATE; + this.mouseButtons.LEFT = THREE.MOUSE.PAN; + this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE; - this.touches.ONE = TOUCH.PAN; - this.touches.TWO = TOUCH.DOLLY_ROTATE; + this.touches.ONE = THREE.TOUCH.PAN; + this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE; }; -MapControls.prototype = Object.create( EventDispatcher.prototype ); -MapControls.prototype.constructor = MapControls; - -export { OrbitControls, MapControls }; +THREE.MapControls.prototype = Object.create( THREE.EventDispatcher.prototype ); +THREE.MapControls.prototype.constructor = THREE.MapControls; diff --git a/Reflector.js b/Reflector.js index 7814e19..2374b27 100644 --- a/Reflector.js +++ b/Reflector.js @@ -1,7 +1,7 @@ /** * @author Slayvin / http://slayvin.net */ -import THREE from './three.js'; +import THREE from './three.module.js'; THREE.Reflector = function ( geometry, options ) { @@ -156,17 +156,17 @@ THREE.Reflector = function ( geometry, options ) { var currentRenderTarget = renderer.getRenderTarget(); - var currentVrEnabled = renderer.vr.enabled; + var currentVrEnabled = renderer.xr.enabled; var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate; - renderer.vr.enabled = false; // Avoid camera modification and recursion + renderer.xr.enabled = false; // Avoid camera modification and recursion renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows renderer.setRenderTarget( renderTarget ); renderer.clear(); renderer.render( scene, virtualCamera ); - renderer.vr.enabled = currentVrEnabled; + renderer.xr.enabled = currentVrEnabled; renderer.shadowMap.autoUpdate = currentShadowAutoUpdate; renderer.setRenderTarget( currentRenderTarget ); diff --git a/avatars.js b/avatars.js index 54dbc30..477842a 100644 --- a/avatars.js +++ b/avatars.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from './three.module.js'; import './vrarmik/three-vrm.js'; import {fixSkeletonZForward} from './vrarmik/SkeletonUtils.js'; import PoseManager from './vrarmik/PoseManager.js'; @@ -1093,4 +1093,4 @@ class Avatar { this.setMicrophoneMediaStream(null); } } -export default Avatar; \ No newline at end of file +export default Avatar; diff --git a/bmfont.js b/bmfont.js index 1819e9d..86c943b 100644 --- a/bmfont.js +++ b/bmfont.js @@ -1,3 +1,5 @@ +import THREE from './three.module.js'; + (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i - +
@@ -497,8 +498,8 @@

Multiplayer

}; const teleportGeometry = new THREE.TorusBufferGeometry(0.5, 0.15, 3, 5) - .applyMatrix(new THREE.Matrix4().makeRotationX(-(Math.PI / 2))) - .applyMatrix(new THREE.Matrix4().makeRotationY((1 / 20) * (Math.PI * 2))); + .applyMatrix4(new THREE.Matrix4().makeRotationX(-(Math.PI / 2))) + .applyMatrix4(new THREE.Matrix4().makeRotationY((1 / 20) * (Math.PI * 2))); const teleportMaterial = new THREE.MeshBasicMaterial({ color: 0x44c2ff, }); @@ -635,7 +636,7 @@

Multiplayer

const mirrorWidth = 3; const mirrorHeight = 2; const geometry = new THREE.PlaneBufferGeometry(mirrorWidth, mirrorHeight) - .applyMatrix(new THREE.Matrix4().makeTranslation(0, 1, 0)); + .applyMatrix4(new THREE.Matrix4().makeTranslation(0, 1, 0)); const mesh = new THREE.Reflector(geometry, { clipBias: 0.003, textureWidth: 1024 * window.devicePixelRatio, @@ -649,7 +650,7 @@

Multiplayer

const borderMesh = new THREE.Mesh( new THREE.BoxBufferGeometry(mirrorWidth + 0.1, mirrorHeight + 0.1, 0.1) - .applyMatrix(new THREE.Matrix4().makeTranslation(0, 1, -0.1/2 - 0.01)), + .applyMatrix4(new THREE.Matrix4().makeTranslation(0, 1, -0.1/2 - 0.01)), new THREE.MeshPhongMaterial({ color: 0x5c6bc0, }) @@ -755,8 +756,8 @@

Multiplayer

const timeDiff = now - lastTimestamp; if (rig) { - if (renderer.vr.enabled) { - const vrCameras = renderer.vr.getCamera(camera).cameras; + if (renderer.xr.enabled) { + const vrCameras = renderer.xr.getCamera(camera).cameras; const vrCamera = vrCameras[0]; const vrCamera2 = vrCameras[1]; vrCamera.matrixWorld.decompose(vrCamera.position, vrCamera.quaternion, vrCamera.scale); @@ -1259,9 +1260,9 @@

Multiplayer

}; await _loadReferenceSpace(); const loadReferenceSpaceInterval = setInterval(_loadReferenceSpace, 1000); - + await new Promise((accept, reject) => { - renderer.vr.setSession(session); + renderer.xr.setSession(session); let interations = 0; const _raf = (timestamp, frame) => { @@ -1282,9 +1283,9 @@

Multiplayer

renderer.setAnimationLoop(null); - renderer.vr.enabled = true; - renderer.vr.setSession(session); - renderer.vr.setAnimationLoop(animate); + renderer.xr.enabled = true; + renderer.xr.setSession(session); + renderer.xr.setAnimationLoop(animate); accept(); } else { diff --git a/three.js b/three.module.js similarity index 99% rename from three.js rename to three.module.js index a5c94e7..f37bad9 100644 --- a/three.js +++ b/three.module.js @@ -50945,9 +50945,6 @@ if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { } - - - export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, BoxGeometry as CubeGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils as Math, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGLCubeRenderTarget, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding }; const THREE = { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, AxisHelper, BackSide, BasicDepthPacking, BasicShadowMap, BinaryTextureLoader, Bone, BooleanKeyframeTrack, BoundingBoxHelper, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasRenderer, CanvasTexture, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, ClosedSplineCurve3, Color, ColorKeyframeTrack, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeGeometry: BoxGeometry, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubeUVRefractionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CylinderBufferGeometry, CylinderGeometry, Cylindrical, DataTexture, DataTexture2DArray, DataTexture3D, DataTextureLoader, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DirectionalLightShadow, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicBufferAttribute, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EdgesHelper, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, Face3, Face4, FaceColors, FileLoader, FlatShading, Float32Attribute, Float32BufferAttribute, Float64Attribute, Float64BufferAttribute, FloatType, Fog, FogExp2, Font, FontLoader, FrontFaceDirectionCCW, FrontFaceDirectionCW, FrontSide, Frustum, GammaEncoding, Geometry, GeometryUtils, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16Attribute, Int16BufferAttribute, Int32Attribute, Int32BufferAttribute, Int8Attribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, JSONLoader, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LensFlare, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightShadow, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LinePieces, LineSegments, LineStrip, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LogLuvEncoding, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, Math: MathUtils, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshFaceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiMaterial, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColors, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, ParametricBufferGeometry, ParametricGeometry, Particle, ParticleBasicMaterial, ParticleSystem, ParticleSystemMaterial, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointCloud, PointCloudMaterial, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDEncoding, RGBEEncoding, RGBEFormat, RGBFormat, RGBIntegerFormat, RGBM16Encoding, RGBM7Encoding, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SRGB8_ALPHA8_ASTC_10x10_Format, SRGB8_ALPHA8_ASTC_10x5_Format, SRGB8_ALPHA8_ASTC_10x6_Format, SRGB8_ALPHA8_ASTC_10x8_Format, SRGB8_ALPHA8_ASTC_12x10_Format, SRGB8_ALPHA8_ASTC_12x12_Format, SRGB8_ALPHA8_ASTC_4x4_Format, SRGB8_ALPHA8_ASTC_5x4_Format, SRGB8_ALPHA8_ASTC_5x5_Format, SRGB8_ALPHA8_ASTC_6x5_Format, SRGB8_ALPHA8_ASTC_6x6_Format, SRGB8_ALPHA8_ASTC_8x5_Format, SRGB8_ALPHA8_ASTC_8x6_Format, SRGB8_ALPHA8_ASTC_8x8_Format, Scene, SceneUtils, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SmoothShading, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SphericalReflectionMapping, Spline, SplineCurve, SplineCurve3, SpotLight, SpotLightHelper, SpotLightShadow, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, TextBufferGeometry, TextGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, UVMapping, Uint16Attribute, Uint16BufferAttribute, Uint32Attribute, Uint32BufferAttribute, Uint8Attribute, Uint8BufferAttribute, Uint8ClampedAttribute, Uint8ClampedBufferAttribute, Uncharted2ToneMapping, Uniform, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShort565Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, Vertex, VertexColors, VideoTexture, WebGLCubeRenderTarget, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderTargetCube, WebGLRenderer, WebGLUtils, WireframeGeometry, WireframeHelper, WrapAroundEnding, XHRLoader, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, sRGBEncoding }; export default THREE; \ No newline at end of file diff --git a/vrarmik/ArmTransforms.js b/vrarmik/ArmTransforms.js index 993cf24..0c374f4 100644 --- a/vrarmik/ArmTransforms.js +++ b/vrarmik/ArmTransforms.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; class ArmTransforms { diff --git a/vrarmik/LegsManager.js b/vrarmik/LegsManager.js index 1933c6d..6e6e1fa 100644 --- a/vrarmik/LegsManager.js +++ b/vrarmik/LegsManager.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; import {Helpers} from './Unity.js'; const stepRate = 0.2; diff --git a/vrarmik/ShoulderPoser.js b/vrarmik/ShoulderPoser.js index 31ea6f2..19a72ab 100644 --- a/vrarmik/ShoulderPoser.js +++ b/vrarmik/ShoulderPoser.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; import {Helpers} from './Unity.js'; const rightVector = new THREE.Vector3(1, 0, 0); diff --git a/vrarmik/ShoulderTransforms.js b/vrarmik/ShoulderTransforms.js index 0af7ffe..bc5b034 100644 --- a/vrarmik/ShoulderTransforms.js +++ b/vrarmik/ShoulderTransforms.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; import ArmTransforms from './ArmTransforms.js'; import ShoulderPoser from './ShoulderPoser.js'; import VRArmIK from './VRArmIK.js'; diff --git a/vrarmik/SkeletonUtils.js b/vrarmik/SkeletonUtils.js index 541532b..e73321a 100644 --- a/vrarmik/SkeletonUtils.js +++ b/vrarmik/SkeletonUtils.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; /** * Takes in a rootBone and recursively traverses the bone heirarchy, @@ -168,4 +168,4 @@ function _localToWorldDirection(direction, parent) { export { fixSkeletonZForward, setQuaternionFromDirection -}; \ No newline at end of file +}; diff --git a/vrarmik/Unity.js b/vrarmik/Unity.js index 2537f8f..21a4fcb 100644 --- a/vrarmik/Unity.js +++ b/vrarmik/Unity.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; const localVector = new THREE.Vector3(); const localVector2 = new THREE.Vector3(); diff --git a/vrarmik/VRArmIK.js b/vrarmik/VRArmIK.js index 8dfb59d..84450de 100644 --- a/vrarmik/VRArmIK.js +++ b/vrarmik/VRArmIK.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; import {Helpers} from './Unity.js'; const zeroVector = new THREE.Vector3(); diff --git a/vrarmik/VRTrackingReferences.js b/vrarmik/VRTrackingReferences.js index ec05eea..6d5ff39 100644 --- a/vrarmik/VRTrackingReferences.js +++ b/vrarmik/VRTrackingReferences.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; class VRTrackingReferences { constructor() { diff --git a/vrarmik/three-vrm.js b/vrarmik/three-vrm.js index e60451a..0ed0c98 100644 --- a/vrarmik/three-vrm.js +++ b/vrarmik/three-vrm.js @@ -1,4 +1,4 @@ -import THREE from '../three.js'; +import THREE from '../three.module.js'; var __three_vrm__ = /******/ (function(modules) { // webpackBootstrap @@ -4217,4 +4217,4 @@ module.exports = THREE; /***/ }) -/******/ }); \ No newline at end of file +/******/ }); From acc2cc2ede8ea1ae1707e988f1c67bd8ab8ca148 Mon Sep 17 00:00:00 2001 From: YaHeng Su Date: Thu, 18 Jun 2020 19:10:35 -0600 Subject: [PATCH 11/11] fixed errors --- avatars.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/avatars.js b/avatars.js index 477842a..1b0fc21 100644 --- a/avatars.js +++ b/avatars.js @@ -62,7 +62,7 @@ const _copySkeleton = (src, dst) => { }; const cubeGeometry = new THREE.ConeBufferGeometry(0.05, 0.2, 3) - .applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion( + .applyMatrix(new THREE.Matrix4().makeRotationFromQuaternion( new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1))) ); const cubeMaterials ={};