text
stringlengths 3
1.05M
|
|---|
import unittest
from funclib import fn
class TestDict(unittest.TestCase):
def test_index(self):
persons = [{"name": "Tom", "age": 12},
{"name": "Jerry", "age": 20},
{"name": "Mary", "age": 35}]
self.assertEqual(fn.index({"name": 'Jerry'}, persons), 1)
self.assertEqual(fn.index(lambda x: x['name'] == 'Mary', persons), 2)
def test_find(self):
persons = [{"name": "Tom", "age": 12},
{"name": "Jerry", "age": 20},
{"name": "Mary", "age": 35}]
Jerry = fn.find({"name": 'Jerry'}, persons)
Mary = fn.find(lambda x: x['name'] == 'Mary', persons)
self.assertDictEqual(
fn.find({"name": 'Jerry'}, persons),
{'name': 'Jerry', 'age': 20},
msg=None
)
self.assertDictEqual(
fn.find(lambda x: x['name'] == 'Mary', persons),
{'name': 'Mary', 'age': 35},
msg=None
)
def test_filter(self):
persons = [{"name": "Tom", "age": 20},
{"name": "Jerry", "age": 20},
{"name": "Jerry", "age": 35}]
age20 = fn.filter({"age": 20}, persons)
Jerrys = fn.filter(lambda x: x['name'] == 'Jerry', persons)
self.assertTrue(len(age20) == 2 and fn.every({'age': 20}, age20))
self.assertTrue(len(Jerrys) == 2 and fn.every({'name': 'Jerry'}, Jerrys))
def test_reject(self):
persons = [{"name": "Tom", "age": 12},
{"name": "Jerry", "age": 20},
{"name": "Mary", "age": 35}]
not_age20 = fn.reject({"age": 20}, persons)
not_Jerry = fn.reject(lambda x: x['name'] == 'Jerry', persons)
self.assertTrue(len(not_age20) == 2 and not fn.every({'age': 20}, not_age20))
self.assertTrue(len(not_Jerry) == 2 and not fn.every({'name': 'Jerry'}, not_Jerry))
def test_reduce(self):
self.assertEqual(fn.reduce(lambda a, b: a + b, [1 , 2, 3, 4]), 10)
def test_contains(self):
persons = [{"name": "Tom", "age": 12},
{"name": "Jerry", "age": 20},
{"name": "Mary", "age": 35}]
self.assertFalse(fn.contains({"name": "Jerry", "age": 12}, persons))
self.assertTrue(fn.contains(lambda x: x['name'] == 'Mary', persons))
def test_flatten(self):
self.assertListEqual(
fn.flatten([1, [2], [3, [[4]]]]),
[1, 2, 3, [[4]]],
msg=None
)
self.assertListEqual(
fn.flatten([1, [2], [3, [[4]]]], True),
[1, 2, 3, 4],
msg=None
)
def test_uniq(self):
persons = [{"name": "Tom", "age": 12, "pet": {"species": "dog", "name": "Kitty"}},
{"name": "Tom", "age": 20, "pet": {"species": "cat", "name": "wang"}},
{"name": "Mary", "age": 35, "pet": {"species": "cat", "name": "mimi"}}]
self.assertListEqual(
fn.uniq(["Tom", "Tom", "Jerry"]),
["Tom", "Jerry"],
msg=None
)
self.assertListEqual(
fn.uniq([False, [], False, True, [], {}, False, '']),
[False, [], True, {}, ''],
msg=None
)
self.assertListEqual(
fn.uniq(persons, '/name'),
[{"name": "Tom", "age": 12, "pet": {"species": "dog", "name": "Kitty"}},
{"name": "Mary", "age": 35, "pet": {"species": "cat", "name": "mimi"}}],
msg=None
)
self.assertListEqual(
fn.uniq(persons, '/pet/species'),
[{"name": "Tom", "age": 12, "pet": {"species": "dog", "name": "Kitty"}},
{"name": "Tom", "age": 20, "pet": {"species": "cat", "name": "wang"}}],
msg=None
)
def test_pluck(self):
persons = [{"name": "Tom", "hobbies": ["sing", "running"]},
{"name": "Jerry", "hobbies": []},
{"name": "Mary", "hobbies": ['hiking', 'sing']}]
self.assertListEqual(
fn.pluck(persons, 'hobbies'),
["sing", "running", 'hiking', 'sing'],
msg=None
)
self.assertListEqual(
fn.pluck(persons, 'hobbies', is_uniq=True),
["sing", "running", 'hiking'],
msg=None
)
def test_get(self):
Tom = {
"name": "Tom",
"age": 12,
"pets": [
{"species": "dog", "name": "Kitty"},
{"species": "cat", "name": "mimi"}
]
}
self.assertEqual(fn.get(Tom, '/age'), 12)
self.assertEqual(fn.get(Tom, '/pets/0/species'), 'dog')
self.assertEqual(fn.get(Tom, '/pets/1/name'), 'mimi')
self.assertTrue(fn.get(Tom, '/pets/1/name', 'str'))
self.assertFalse(fn.get(Tom, '/pets/1/name', 'int'))
def test_every(self):
persons = [{"name": "Tom", "age": 12, "sex": "m"},
{"name": "Jerry", "age": 20, "sex": "m"},
{"name": "Mary", "age": 35, "sex": "f"}]
self.assertFalse(fn.every(5, [1, 1, 2, 3, 5, 8]))
self.assertFalse(fn.every({"sex": "m"}, persons))
self.assertFalse(fn.every(lambda x: x['age'] > 18, persons))
def test_some(self):
persons = [{"name": "Tom", "age": 12, "sex": "m"},
{"name": "Jerry", "age": 20, "sex": "m"},
{"name": "Mary", "age": 35, "sex": "f"}]
self.assertTrue(fn.some(5, [1, 1, 2, 3, 5, 8]))
self.assertTrue(fn.some({"sex": "m"}, persons))
self.assertTrue(fn.some(lambda x: x['age'] > 18, persons))
def test_tolist(self):
fn.tolist() # => []
fn.tolist([]) # => []
fn.tolist({}) # => [{}]
fn.tolist(None) # => [None]
fn.tolist('str') # => ['str']
self.assertListEqual(fn.tolist(), [], msg=None)
self.assertListEqual(fn.tolist([]), [], msg=None)
self.assertListEqual(fn.tolist({}), [{}], msg=None)
self.assertListEqual(fn.tolist(None), [None], msg=None)
self.assertListEqual(fn.tolist('str'), ['str'], msg=None)
def test_drop(self):
tmp_list = [0, '', 3, None, [], {}, ['Yes'], 'Test']
self.assertListEqual(fn.drop(tmp_list), [3, ['Yes'], 'Test'], msg=None)
self.assertListEqual(fn.drop(tmp_list, True), [0, 3, ['Yes'], 'Test'], msg=None)
def test_test(self):
self.assertFalse(fn.test(r'ab', 'Hello World!'))
self.assertTrue(fn.test(r'll', 'Hello World!'))
def test_replace(self):
self.assertEqual(fn.replace(r'Tom', 'Jack', 'Hello I\'m Tom!'), 'Hello I\'m Jack!')
def test_iscan(self):
self.assertTrue(fn.iscan("int('5')"))
self.assertFalse(fn.iscan("int('a')"))
def test_typeof(self):
self.assertTrue(fn.typeof(None, 'non'))
self.assertFalse(fn.typeof(True, 'str'))
self.assertTrue(fn.typeof([], 'map', 'lst', 'tup'))
self.assertTrue(fn.typeof(lambda x: x, 'fun'))
def test_typeval(self):
self.assertEqual(fn.typeval('test', 'str'), 'test')
self.assertListEqual(fn.typeval([], 'lst'), [], msg=None)
self.assertFalse(fn.typeval({}, 'lst'))
if __name__=='__main__':
unittest.main()
|
/*
* Copyright (c) 2008 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of CACE Technologies nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <pcap.h>
#include <pcap-int.h>
#include "pcap-tc.h"
#include <malloc.h>
#include <memory.h>
#include <string.h>
#include <errno.h>
#ifdef _WIN32
#include <tchar.h>
#endif
typedef TC_STATUS (TC_CALLCONV *TcFcnQueryPortList) (PTC_PORT *ppPorts, PULONG pLength);
typedef TC_STATUS (TC_CALLCONV *TcFcnFreePortList) (TC_PORT *pPorts);
typedef PCHAR (TC_CALLCONV *TcFcnStatusGetString) (TC_STATUS status);
typedef PCHAR (TC_CALLCONV *TcFcnPortGetName) (TC_PORT port);
typedef PCHAR (TC_CALLCONV *TcFcnPortGetDescription) (TC_PORT port);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceOpenByName) (PCHAR name, PTC_INSTANCE pInstance);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceClose) (TC_INSTANCE instance);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceSetFeature) (TC_INSTANCE instance, ULONG feature, ULONG value);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceQueryFeature) (TC_INSTANCE instance, ULONG feature, PULONG pValue);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceReceivePackets) (TC_INSTANCE instance, PTC_PACKETS_BUFFER pBuffer);
typedef HANDLE (TC_CALLCONV *TcFcnInstanceGetReceiveWaitHandle) (TC_INSTANCE instance);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceTransmitPackets) (TC_INSTANCE instance, TC_PACKETS_BUFFER pBuffer);
typedef TC_STATUS (TC_CALLCONV *TcFcnInstanceQueryStatistics) (TC_INSTANCE instance, PTC_STATISTICS pStatistics);
typedef TC_STATUS (TC_CALLCONV *TcFcnPacketsBufferCreate) (ULONG size, PTC_PACKETS_BUFFER pBuffer);
typedef VOID (TC_CALLCONV *TcFcnPacketsBufferDestroy) (TC_PACKETS_BUFFER buffer);
typedef TC_STATUS (TC_CALLCONV *TcFcnPacketsBufferQueryNextPacket)(TC_PACKETS_BUFFER buffer, PTC_PACKET_HEADER pHeader, PVOID *ppData);
typedef TC_STATUS (TC_CALLCONV *TcFcnPacketsBufferCommitNextPacket)(TC_PACKETS_BUFFER buffer, PTC_PACKET_HEADER pHeader, PVOID pData);
typedef VOID (TC_CALLCONV *TcFcnStatisticsDestroy) (TC_STATISTICS statistics);
typedef TC_STATUS (TC_CALLCONV *TcFcnStatisticsUpdate) (TC_STATISTICS statistics);
typedef TC_STATUS (TC_CALLCONV *TcFcnStatisticsQueryValue) (TC_STATISTICS statistics, ULONG counterId, PULONGLONG pValue);
typedef enum LONG
{
TC_API_UNLOADED = 0,
TC_API_LOADED,
TC_API_CANNOT_LOAD,
TC_API_LOADING
}
TC_API_LOAD_STATUS;
typedef struct _TC_FUNCTIONS
{
TC_API_LOAD_STATUS LoadStatus;
#ifdef _WIN32
HMODULE hTcApiDllHandle;
#endif
TcFcnQueryPortList QueryPortList;
TcFcnFreePortList FreePortList;
TcFcnStatusGetString StatusGetString;
TcFcnPortGetName PortGetName;
TcFcnPortGetDescription PortGetDescription;
TcFcnInstanceOpenByName InstanceOpenByName;
TcFcnInstanceClose InstanceClose;
TcFcnInstanceSetFeature InstanceSetFeature;
TcFcnInstanceQueryFeature InstanceQueryFeature;
TcFcnInstanceReceivePackets InstanceReceivePackets;
#ifdef _WIN32
TcFcnInstanceGetReceiveWaitHandle InstanceGetReceiveWaitHandle;
#endif
TcFcnInstanceTransmitPackets InstanceTransmitPackets;
TcFcnInstanceQueryStatistics InstanceQueryStatistics;
TcFcnPacketsBufferCreate PacketsBufferCreate;
TcFcnPacketsBufferDestroy PacketsBufferDestroy;
TcFcnPacketsBufferQueryNextPacket PacketsBufferQueryNextPacket;
TcFcnPacketsBufferCommitNextPacket PacketsBufferCommitNextPacket;
TcFcnStatisticsDestroy StatisticsDestroy;
TcFcnStatisticsUpdate StatisticsUpdate;
TcFcnStatisticsQueryValue StatisticsQueryValue;
}
TC_FUNCTIONS;
static pcap_if_t* TcCreatePcapIfFromPort(TC_PORT port);
static int TcSetDatalink(pcap_t *p, int dlt);
static int TcGetNonBlock(pcap_t *p);
static int TcSetNonBlock(pcap_t *p, int nonblock);
static void TcCleanup(pcap_t *p);
static int TcInject(pcap_t *p, const void *buf, int size);
static int TcRead(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
static int TcStats(pcap_t *p, struct pcap_stat *ps);
static int TcSetFilter(pcap_t *p, struct bpf_program *fp);
#ifdef _WIN32
static struct pcap_stat *TcStatsEx(pcap_t *p, int *pcap_stat_size);
static int TcSetBuff(pcap_t *p, int dim);
static int TcSetMode(pcap_t *p, int mode);
static int TcSetMinToCopy(pcap_t *p, int size);
static HANDLE TcGetReceiveWaitHandle(pcap_t *p);
static int TcOidGetRequest(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp);
static int TcOidSetRequest(pcap_t *p, bpf_u_int32 oid, const void *data, size_t *lenp);
static u_int TcSendqueueTransmit(pcap_t *p, pcap_send_queue *queue, int sync);
static int TcSetUserBuffer(pcap_t *p, int size);
static int TcLiveDump(pcap_t *p, char *filename, int maxsize, int maxpacks);
static int TcLiveDumpEnded(pcap_t *p, int sync);
static PAirpcapHandle TcGetAirPcapHandle(pcap_t *p);
#endif
#ifdef _WIN32
TC_FUNCTIONS g_TcFunctions =
{
TC_API_UNLOADED, /* LoadStatus */
NULL, /* hTcApiDllHandle */
NULL, /* QueryPortList */
NULL, /* FreePortList */
NULL, /* StatusGetString */
NULL, /* PortGetName */
NULL, /* PortGetDescription */
NULL, /* InstanceOpenByName */
NULL, /* InstanceClose */
NULL, /* InstanceSetFeature */
NULL, /* InstanceQueryFeature */
NULL, /* InstanceReceivePackets */
NULL, /* InstanceGetReceiveWaitHandle */
NULL, /* InstanceTransmitPackets */
NULL, /* InstanceQueryStatistics */
NULL, /* PacketsBufferCreate */
NULL, /* PacketsBufferDestroy */
NULL, /* PacketsBufferQueryNextPacket */
NULL, /* PacketsBufferCommitNextPacket */
NULL, /* StatisticsDestroy */
NULL, /* StatisticsUpdate */
NULL /* StatisticsQueryValue */
};
#else
TC_FUNCTIONS g_TcFunctions =
{
TC_API_LOADED, /* LoadStatus */
TcQueryPortList,
TcFreePortList,
TcStatusGetString,
TcPortGetName,
TcPortGetDescription,
TcInstanceOpenByName,
TcInstanceClose,
TcInstanceSetFeature,
TcInstanceQueryFeature,
TcInstanceReceivePackets,
#ifdef _WIN32
TcInstanceGetReceiveWaitHandle,
#endif
TcInstanceTransmitPackets,
TcInstanceQueryStatistics,
TcPacketsBufferCreate,
TcPacketsBufferDestroy,
TcPacketsBufferQueryNextPacket,
TcPacketsBufferCommitNextPacket,
TcStatisticsDestroy,
TcStatisticsUpdate,
TcStatisticsQueryValue,
};
#endif
#define MAX_TC_PACKET_SIZE 9500
#pragma pack(push, 1)
#define PPH_PH_FLAG_PADDING ((UCHAR)0x01)
#define PPH_PH_VERSION ((UCHAR)0x00)
typedef struct _PPI_PACKET_HEADER
{
UCHAR PphVersion;
UCHAR PphFlags;
USHORT PphLength;
ULONG PphDlt;
}
PPI_PACKET_HEADER, *PPPI_PACKET_HEADER;
typedef struct _PPI_FIELD_HEADER
{
USHORT PfhType;
USHORT PfhLength;
}
PPI_FIELD_HEADER, *PPPI_FIELD_HEADER;
#define PPI_FIELD_TYPE_AGGREGATION_EXTENSION ((UCHAR)0x08)
typedef struct _PPI_FIELD_AGGREGATION_EXTENSION
{
ULONG InterfaceId;
}
PPI_FIELD_AGGREGATION_EXTENSION, *PPPI_FIELD_AGGREGATION_EXTENSION;
#define PPI_FIELD_TYPE_802_3_EXTENSION ((UCHAR)0x09)
#define PPI_FLD_802_3_EXT_FLAG_FCS_PRESENT ((ULONG)0x00000001)
typedef struct _PPI_FIELD_802_3_EXTENSION
{
ULONG Flags;
ULONG Errors;
}
PPI_FIELD_802_3_EXTENSION, *PPPI_FIELD_802_3_EXTENSION;
typedef struct _PPI_HEADER
{
PPI_PACKET_HEADER PacketHeader;
PPI_FIELD_HEADER AggregationFieldHeader;
PPI_FIELD_AGGREGATION_EXTENSION AggregationField;
PPI_FIELD_HEADER Dot3FieldHeader;
PPI_FIELD_802_3_EXTENSION Dot3Field;
}
PPI_HEADER, *PPPI_HEADER;
#pragma pack(pop)
#ifdef _WIN32
//
// This wrapper around loadlibrary appends the system folder (usually c:\windows\system32)
// to the relative path of the DLL, so that the DLL is always loaded from an absolute path
// (It's no longer possible to load airpcap.dll from the application folder).
// This solves the DLL Hijacking issue discovered in August 2010
// http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
//
HMODULE LoadLibrarySafe(LPCTSTR lpFileName)
{
TCHAR path[MAX_PATH];
TCHAR fullFileName[MAX_PATH];
UINT res;
HMODULE hModule = NULL;
do
{
res = GetSystemDirectory(path, MAX_PATH);
if (res == 0)
{
//
// some bad failure occurred;
//
break;
}
if (res > MAX_PATH)
{
//
// the buffer was not big enough
//
SetLastError(ERROR_INSUFFICIENT_BUFFER);
break;
}
if (res + 1 + _tcslen(lpFileName) + 1 < MAX_PATH)
{
memcpy(fullFileName, path, res * sizeof(TCHAR));
fullFileName[res] = _T('\\');
memcpy(&fullFileName[res + 1], lpFileName, (_tcslen(lpFileName) + 1) * sizeof(TCHAR));
hModule = LoadLibrary(fullFileName);
}
else
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
}
}while(FALSE);
return hModule;
}
/*
* NOTE: this function should be called by the pcap functions that can theoretically
* deal with the Tc library for the first time, namely listing the adapters and
* opening one. All the other ones (close, read, write, set parameters) work
* on an open instance of TC, so we do not care to call this function
*/
TC_API_LOAD_STATUS LoadTcFunctions(void)
{
TC_API_LOAD_STATUS currentStatus;
do
{
currentStatus = InterlockedCompareExchange((LONG*)&g_TcFunctions.LoadStatus, TC_API_LOADING, TC_API_UNLOADED);
while(currentStatus == TC_API_LOADING)
{
currentStatus = InterlockedCompareExchange((LONG*)&g_TcFunctions.LoadStatus, TC_API_LOADING, TC_API_LOADING);
Sleep(10);
}
/*
* at this point we are either in the LOADED state, unloaded state (i.e. we are the ones loading everything)
* or in cannot load
*/
if(currentStatus == TC_API_LOADED)
{
return TC_API_LOADED;
}
if (currentStatus == TC_API_CANNOT_LOAD)
{
return TC_API_CANNOT_LOAD;
}
currentStatus = TC_API_CANNOT_LOAD;
g_TcFunctions.hTcApiDllHandle = LoadLibrarySafe("TcApi.dll");
if (g_TcFunctions.hTcApiDllHandle == NULL) break;
g_TcFunctions.QueryPortList = (TcFcnQueryPortList) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcQueryPortList");
g_TcFunctions.FreePortList = (TcFcnFreePortList) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcFreePortList");
g_TcFunctions.StatusGetString = (TcFcnStatusGetString) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatusGetString");
g_TcFunctions.PortGetName = (TcFcnPortGetName) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPortGetName");
g_TcFunctions.PortGetDescription = (TcFcnPortGetDescription) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPortGetDescription");
g_TcFunctions.InstanceOpenByName = (TcFcnInstanceOpenByName) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceOpenByName");
g_TcFunctions.InstanceClose = (TcFcnInstanceClose) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceClose");
g_TcFunctions.InstanceSetFeature = (TcFcnInstanceSetFeature) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceSetFeature");
g_TcFunctions.InstanceQueryFeature = (TcFcnInstanceQueryFeature) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceQueryFeature");
g_TcFunctions.InstanceReceivePackets = (TcFcnInstanceReceivePackets) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceReceivePackets");
g_TcFunctions.InstanceGetReceiveWaitHandle = (TcFcnInstanceGetReceiveWaitHandle)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceGetReceiveWaitHandle");
g_TcFunctions.InstanceTransmitPackets = (TcFcnInstanceTransmitPackets)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceTransmitPackets");
g_TcFunctions.InstanceQueryStatistics = (TcFcnInstanceQueryStatistics)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcInstanceQueryStatistics");
g_TcFunctions.PacketsBufferCreate = (TcFcnPacketsBufferCreate) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferCreate");
g_TcFunctions.PacketsBufferDestroy = (TcFcnPacketsBufferDestroy) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferDestroy");
g_TcFunctions.PacketsBufferQueryNextPacket = (TcFcnPacketsBufferQueryNextPacket)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferQueryNextPacket");
g_TcFunctions.PacketsBufferCommitNextPacket = (TcFcnPacketsBufferCommitNextPacket)GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcPacketsBufferCommitNextPacket");
g_TcFunctions.StatisticsDestroy = (TcFcnStatisticsDestroy) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsDestroy");
g_TcFunctions.StatisticsUpdate = (TcFcnStatisticsUpdate) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsUpdate");
g_TcFunctions.StatisticsQueryValue = (TcFcnStatisticsQueryValue) GetProcAddress(g_TcFunctions.hTcApiDllHandle, "TcStatisticsQueryValue");
if ( g_TcFunctions.QueryPortList == NULL
|| g_TcFunctions.FreePortList == NULL
|| g_TcFunctions.StatusGetString == NULL
|| g_TcFunctions.PortGetName == NULL
|| g_TcFunctions.PortGetDescription == NULL
|| g_TcFunctions.InstanceOpenByName == NULL
|| g_TcFunctions.InstanceClose == NULL
|| g_TcFunctions.InstanceSetFeature == NULL
|| g_TcFunctions.InstanceQueryFeature == NULL
|| g_TcFunctions.InstanceReceivePackets == NULL
|| g_TcFunctions.InstanceGetReceiveWaitHandle == NULL
|| g_TcFunctions.InstanceTransmitPackets == NULL
|| g_TcFunctions.InstanceQueryStatistics == NULL
|| g_TcFunctions.PacketsBufferCreate == NULL
|| g_TcFunctions.PacketsBufferDestroy == NULL
|| g_TcFunctions.PacketsBufferQueryNextPacket == NULL
|| g_TcFunctions.PacketsBufferCommitNextPacket == NULL
|| g_TcFunctions.StatisticsDestroy == NULL
|| g_TcFunctions.StatisticsUpdate == NULL
|| g_TcFunctions.StatisticsQueryValue == NULL
)
{
break;
}
/*
* everything got loaded, yay!!
*/
currentStatus = TC_API_LOADED;
}while(FALSE);
if (currentStatus != TC_API_LOADED)
{
if (g_TcFunctions.hTcApiDllHandle != NULL)
{
FreeLibrary(g_TcFunctions.hTcApiDllHandle);
g_TcFunctions.hTcApiDllHandle = NULL;
}
}
InterlockedExchange((LONG*)&g_TcFunctions.LoadStatus, currentStatus);
return currentStatus;
}
#else
// static linking
TC_API_LOAD_STATUS LoadTcFunctions(void)
{
return TC_API_LOADED;
}
#endif
/*
* Private data for capturing on TurboCap devices.
*/
struct pcap_tc {
TC_INSTANCE TcInstance;
TC_PACKETS_BUFFER TcPacketsBuffer;
ULONG TcAcceptedCount;
u_char *PpiPacket;
};
int
TcFindAllDevs(pcap_if_list_t *devlist, char *errbuf)
{
TC_API_LOAD_STATUS loadStatus;
ULONG numPorts;
PTC_PORT pPorts = NULL;
TC_STATUS status;
int result = 0;
pcap_if_t *dev;
ULONG i;
do
{
loadStatus = LoadTcFunctions();
if (loadStatus != TC_API_LOADED)
{
result = 0;
break;
}
/*
* enumerate the ports, and add them to the list
*/
status = g_TcFunctions.QueryPortList(&pPorts, &numPorts);
if (status != TC_SUCCESS)
{
result = 0;
break;
}
for (i = 0; i < numPorts; i++)
{
/*
* transform the port into an entry in the list
*/
dev = TcCreatePcapIfFromPort(pPorts[i]);
if (dev != NULL)
add_dev(devlist, dev->name, dev->flags, dev->description, errbuf);
}
if (numPorts > 0)
{
/*
* ignore the result here
*/
status = g_TcFunctions.FreePortList(pPorts);
}
}while(FALSE);
return result;
}
static pcap_if_t* TcCreatePcapIfFromPort(TC_PORT port)
{
CHAR *name;
CHAR *description;
pcap_if_t *newIf = NULL;
newIf = (pcap_if_t*)malloc(sizeof(*newIf));
if (newIf == NULL)
{
return NULL;
}
memset(newIf, 0, sizeof(*newIf));
name = g_TcFunctions.PortGetName(port);
description = g_TcFunctions.PortGetDescription(port);
newIf->name = (char*)malloc(strlen(name) + 1);
if (newIf->name == NULL)
{
free(newIf);
return NULL;
}
newIf->description = (char*)malloc(strlen(description) + 1);
if (newIf->description == NULL)
{
free(newIf->name);
free(newIf);
return NULL;
}
strcpy(newIf->name, name);
strcpy(newIf->description, description);
newIf->addresses = NULL;
newIf->next = NULL;
newIf->flags = 0;
return newIf;
}
static int
TcActivate(pcap_t *p)
{
struct pcap_tc *pt = p->priv;
TC_STATUS status;
ULONG timeout;
PPPI_HEADER pPpiHeader;
if (p->opt.rfmon)
{
/*
* No monitor mode on Tc cards; they're Ethernet
* capture adapters.
*/
return PCAP_ERROR_RFMON_NOTSUP;
}
pt->PpiPacket = malloc(sizeof(PPI_HEADER) + MAX_TC_PACKET_SIZE);
if (pt->PpiPacket == NULL)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Error allocating memory");
return PCAP_ERROR;
}
/*
* Turn a negative snapshot value (invalid), a snapshot value of
* 0 (unspecified), or a value bigger than the normal maximum
* value, into the maximum allowed value.
*
* If some application really *needs* a bigger snapshot
* length, we should just increase MAXIMUM_SNAPLEN.
*/
if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
p->snapshot = MAXIMUM_SNAPLEN;
/*
* Initialize the PPI fixed fields
*/
pPpiHeader = (PPPI_HEADER)pt->PpiPacket;
pPpiHeader->PacketHeader.PphDlt = DLT_EN10MB;
pPpiHeader->PacketHeader.PphLength = sizeof(PPI_HEADER);
pPpiHeader->PacketHeader.PphFlags = 0;
pPpiHeader->PacketHeader.PphVersion = 0;
pPpiHeader->AggregationFieldHeader.PfhLength = sizeof(PPI_FIELD_AGGREGATION_EXTENSION);
pPpiHeader->AggregationFieldHeader.PfhType = PPI_FIELD_TYPE_AGGREGATION_EXTENSION;
pPpiHeader->Dot3FieldHeader.PfhLength = sizeof(PPI_FIELD_802_3_EXTENSION);
pPpiHeader->Dot3FieldHeader.PfhType = PPI_FIELD_TYPE_802_3_EXTENSION;
status = g_TcFunctions.InstanceOpenByName(p->opt.device, &pt->TcInstance);
if (status != TC_SUCCESS)
{
/* Adapter detected but we are not able to open it. Return failure. */
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Error opening TurboCap adapter: %s", g_TcFunctions.StatusGetString(status));
return PCAP_ERROR;
}
p->linktype = DLT_EN10MB;
p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
/*
* If that fails, just leave the list empty.
*/
if (p->dlt_list != NULL) {
p->dlt_list[0] = DLT_EN10MB;
p->dlt_list[1] = DLT_PPI;
p->dlt_count = 2;
}
/*
* ignore promiscuous mode
* p->opt.promisc
*/
/*
* ignore all the buffer sizes
*/
/*
* enable reception
*/
status = g_TcFunctions.InstanceSetFeature(pt->TcInstance, TC_INST_FT_RX_STATUS, 1);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,"Error enabling reception on a TurboCap instance: %s", g_TcFunctions.StatusGetString(status));
goto bad;
}
/*
* enable transmission
*/
status = g_TcFunctions.InstanceSetFeature(pt->TcInstance, TC_INST_FT_TX_STATUS, 1);
/*
* Ignore the error here.
*/
p->inject_op = TcInject;
/*
* if the timeout is -1, it means immediate return, no timeout
* if the timeout is 0, it means INFINITE
*/
if (p->opt.timeout == 0)
{
timeout = 0xFFFFFFFF;
}
else
if (p->opt.timeout < 0)
{
/*
* we insert a minimal timeout here
*/
timeout = 10;
}
else
{
timeout = p->opt.timeout;
}
status = g_TcFunctions.InstanceSetFeature(pt->TcInstance, TC_INST_FT_READ_TIMEOUT, timeout);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,"Error setting the read timeout a TurboCap instance: %s", g_TcFunctions.StatusGetString(status));
goto bad;
}
p->read_op = TcRead;
p->setfilter_op = TcSetFilter;
p->setdirection_op = NULL; /* Not implemented. */
p->set_datalink_op = TcSetDatalink;
p->getnonblock_op = TcGetNonBlock;
p->setnonblock_op = TcSetNonBlock;
p->stats_op = TcStats;
#ifdef _WIN32
p->stats_ex_op = TcStatsEx;
p->setbuff_op = TcSetBuff;
p->setmode_op = TcSetMode;
p->setmintocopy_op = TcSetMinToCopy;
p->getevent_op = TcGetReceiveWaitHandle;
p->oid_get_request_op = TcOidGetRequest;
p->oid_set_request_op = TcOidSetRequest;
p->sendqueue_transmit_op = TcSendqueueTransmit;
p->setuserbuffer_op = TcSetUserBuffer;
p->live_dump_op = TcLiveDump;
p->live_dump_ended_op = TcLiveDumpEnded;
p->get_airpcap_handle_op = TcGetAirPcapHandle;
#else
p->selectable_fd = -1;
#endif
p->cleanup_op = TcCleanup;
return 0;
bad:
TcCleanup(p);
return PCAP_ERROR;
}
pcap_t *
TcCreate(const char *device, char *ebuf, int *is_ours)
{
ULONG numPorts;
PTC_PORT pPorts = NULL;
TC_STATUS status;
int is_tc;
ULONG i;
pcap_t *p;
if (LoadTcFunctions() != TC_API_LOADED)
{
/*
* XXX - report this as an error rather than as
* "not a TurboCap device"?
*/
*is_ours = 0;
return NULL;
}
/*
* enumerate the ports, and add them to the list
*/
status = g_TcFunctions.QueryPortList(&pPorts, &numPorts);
if (status != TC_SUCCESS)
{
/*
* XXX - report this as an error rather than as
* "not a TurboCap device"?
*/
*is_ours = 0;
return NULL;
}
is_tc = FALSE;
for (i = 0; i < numPorts; i++)
{
if (strcmp(g_TcFunctions.PortGetName(pPorts[i]), device) == 0)
{
is_tc = TRUE;
break;
}
}
if (numPorts > 0)
{
/*
* ignore the result here
*/
(void)g_TcFunctions.FreePortList(pPorts);
}
if (!is_tc)
{
*is_ours = 0;
return NULL;
}
/* OK, it's probably ours. */
*is_ours = 1;
p = pcap_create_common(ebuf, sizeof (struct pcap_tc));
if (p == NULL)
return NULL;
p->activate_op = TcActivate;
/*
* Set these up front, so that, even if our client tries
* to set non-blocking mode before we're activated, or
* query the state of non-blocking mode, they get an error,
* rather than having the non-blocking mode option set
* for use later.
*/
p->getnonblock_op = TcGetNonBlock;
p->setnonblock_op = TcSetNonBlock;
return p;
}
static int TcSetDatalink(pcap_t *p, int dlt)
{
/*
* We don't have to do any work here; pcap_set_datalink() checks
* whether the value is in the list of DLT_ values we
* supplied, so we don't have to, and, if it is valid, sets
* p->linktype to the new value; we don't have to do anything
* in hardware, we just use what's in p->linktype.
*
* We do have to have a routine, however, so that pcap_set_datalink()
* doesn't think we don't support setting the link-layer header
* type at all.
*/
return 0;
}
static int TcGetNonBlock(pcap_t *p)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Non-blocking mode isn't supported for TurboCap ports");
return -1;
}
static int TcSetNonBlock(pcap_t *p, int nonblock)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Non-blocking mode isn't supported for TurboCap ports");
return -1;
}
static void TcCleanup(pcap_t *p)
{
struct pcap_tc *pt = p->priv;
if (pt->TcPacketsBuffer != NULL)
{
g_TcFunctions.PacketsBufferDestroy(pt->TcPacketsBuffer);
pt->TcPacketsBuffer = NULL;
}
if (pt->TcInstance != NULL)
{
/*
* here we do not check for the error values
*/
g_TcFunctions.InstanceClose(pt->TcInstance);
pt->TcInstance = NULL;
}
if (pt->PpiPacket != NULL)
{
free(pt->PpiPacket);
pt->PpiPacket = NULL;
}
pcap_cleanup_live_common(p);
}
/* Send a packet to the network */
static int TcInject(pcap_t *p, const void *buf, int size)
{
struct pcap_tc *pt = p->priv;
TC_STATUS status;
TC_PACKETS_BUFFER buffer;
TC_PACKET_HEADER header;
if (size >= 0xFFFF)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: the TurboCap API does not support packets larger than 64k");
return -1;
}
status = g_TcFunctions.PacketsBufferCreate(sizeof(TC_PACKET_HEADER) + TC_ALIGN_USHORT_TO_64BIT((USHORT)size), &buffer);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: TcPacketsBufferCreate failure: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
/*
* we assume that the packet is without the checksum, as common with WinPcap
*/
memset(&header, 0, sizeof(header));
header.Length = (USHORT)size;
header.CapturedLength = header.Length;
status = g_TcFunctions.PacketsBufferCommitNextPacket(buffer, &header, (PVOID)buf);
if (status == TC_SUCCESS)
{
status = g_TcFunctions.InstanceTransmitPackets(pt->TcInstance, buffer);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: TcInstanceTransmitPackets failure: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
}
}
else
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: TcPacketsBufferCommitNextPacket failure: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
}
g_TcFunctions.PacketsBufferDestroy(buffer);
if (status != TC_SUCCESS)
{
return -1;
}
else
{
return 0;
}
}
static int TcRead(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
struct pcap_tc *pt = p->priv;
TC_STATUS status;
int n = 0;
/*
* Has "pcap_breakloop()" been called?
*/
if (p->break_loop)
{
/*
* Yes - clear the flag that indicates that it
* has, and return -2 to indicate that we were
* told to break out of the loop.
*/
p->break_loop = 0;
return -2;
}
if (pt->TcPacketsBuffer == NULL)
{
status = g_TcFunctions.InstanceReceivePackets(pt->TcInstance, &pt->TcPacketsBuffer);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error, TcInstanceReceivePackets failure: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
}
while (TRUE)
{
struct pcap_pkthdr hdr;
TC_PACKET_HEADER tcHeader;
PVOID data;
ULONG filterResult;
/*
* Has "pcap_breakloop()" been called?
* If so, return immediately - if we haven't read any
* packets, clear the flag and return -2 to indicate
* that we were told to break out of the loop, otherwise
* leave the flag set, so that the *next* call will break
* out of the loop without having read any packets, and
* return the number of packets we've processed so far.
*/
if (p->break_loop)
{
if (n == 0)
{
p->break_loop = 0;
return -2;
}
else
{
return n;
}
}
if (pt->TcPacketsBuffer == NULL)
{
break;
}
status = g_TcFunctions.PacketsBufferQueryNextPacket(pt->TcPacketsBuffer, &tcHeader, &data);
if (status == TC_ERROR_END_OF_BUFFER)
{
g_TcFunctions.PacketsBufferDestroy(pt->TcPacketsBuffer);
pt->TcPacketsBuffer = NULL;
break;
}
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error, TcPacketsBufferQueryNextPacket failure: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
/* No underlaying filtering system. We need to filter on our own */
if (p->fcode.bf_insns)
{
filterResult = bpf_filter(p->fcode.bf_insns, data, tcHeader.Length, tcHeader.CapturedLength);
if (filterResult == 0)
{
continue;
}
if (filterResult > tcHeader.CapturedLength)
{
filterResult = tcHeader.CapturedLength;
}
}
else
{
filterResult = tcHeader.CapturedLength;
}
pt->TcAcceptedCount ++;
hdr.ts.tv_sec = (bpf_u_int32)(tcHeader.Timestamp / (ULONGLONG)(1000 * 1000 * 1000));
hdr.ts.tv_usec = (bpf_u_int32)((tcHeader.Timestamp % (ULONGLONG)(1000 * 1000 * 1000)) / 1000);
if (p->linktype == DLT_EN10MB)
{
hdr.caplen = filterResult;
hdr.len = tcHeader.Length;
(*callback)(user, &hdr, data);
}
else
{
PPPI_HEADER pPpiHeader = (PPPI_HEADER)pt->PpiPacket;
PVOID data2 = pPpiHeader + 1;
pPpiHeader->AggregationField.InterfaceId = TC_PH_FLAGS_RX_PORT_ID(tcHeader.Flags);
pPpiHeader->Dot3Field.Errors = tcHeader.Errors;
if (tcHeader.Flags & TC_PH_FLAGS_CHECKSUM)
{
pPpiHeader->Dot3Field.Flags = PPI_FLD_802_3_EXT_FLAG_FCS_PRESENT;
}
else
{
pPpiHeader->Dot3Field.Flags = 0;
}
if (filterResult <= MAX_TC_PACKET_SIZE)
{
memcpy(data2, data, filterResult);
hdr.caplen = sizeof(PPI_HEADER) + filterResult;
hdr.len = sizeof(PPI_HEADER) + tcHeader.Length;
}
else
{
memcpy(data2, data, MAX_TC_PACKET_SIZE);
hdr.caplen = sizeof(PPI_HEADER) + MAX_TC_PACKET_SIZE;
hdr.len = sizeof(PPI_HEADER) + tcHeader.Length;
}
(*callback)(user, &hdr, pt->PpiPacket);
}
if (++n >= cnt && cnt > 0)
{
return n;
}
}
return n;
}
static int
TcStats(pcap_t *p, struct pcap_stat *ps)
{
struct pcap_tc *pt = p->priv;
TC_STATISTICS statistics;
TC_STATUS status;
ULONGLONG counter;
struct pcap_stat s;
status = g_TcFunctions.InstanceQueryStatistics(pt->TcInstance, &statistics);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcInstanceQueryStatistics: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
memset(&s, 0, sizeof(s));
status = g_TcFunctions.StatisticsQueryValue(statistics, TC_COUNTER_INSTANCE_TOTAL_RX_PACKETS, &counter);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcStatisticsQueryValue: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
if (counter <= (ULONGLONG)0xFFFFFFFF)
{
s.ps_recv = (ULONG)counter;
}
else
{
s.ps_recv = 0xFFFFFFFF;
}
status = g_TcFunctions.StatisticsQueryValue(statistics, TC_COUNTER_INSTANCE_RX_DROPPED_PACKETS, &counter);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcStatisticsQueryValue: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return -1;
}
if (counter <= (ULONGLONG)0xFFFFFFFF)
{
s.ps_ifdrop = (ULONG)counter;
s.ps_drop = (ULONG)counter;
}
else
{
s.ps_ifdrop = 0xFFFFFFFF;
s.ps_drop = 0xFFFFFFFF;
}
#if defined(_WIN32) && defined(ENABLE_REMOTE)
s.ps_capt = pt->TcAcceptedCount;
#endif
*ps = s;
return 0;
}
/*
* We filter at user level, since the kernel driver does't process the packets
*/
static int
TcSetFilter(pcap_t *p, struct bpf_program *fp)
{
if(!fp)
{
strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
return -1;
}
/* Install a user level filter */
if (install_bpf_program(p, fp) < 0)
{
return -1;
}
return 0;
}
#ifdef _WIN32
static struct pcap_stat *
TcStatsEx(pcap_t *p, int *pcap_stat_size)
{
struct pcap_tc *pt = p->priv;
TC_STATISTICS statistics;
TC_STATUS status;
ULONGLONG counter;
*pcap_stat_size = sizeof (p->stat);
status = g_TcFunctions.InstanceQueryStatistics(pt->TcInstance, &statistics);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcInstanceQueryStatistics: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return NULL;
}
memset(&p->stat, 0, sizeof(p->stat));
status = g_TcFunctions.StatisticsQueryValue(statistics, TC_COUNTER_INSTANCE_TOTAL_RX_PACKETS, &counter);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcStatisticsQueryValue: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return NULL;
}
if (counter <= (ULONGLONG)0xFFFFFFFF)
{
p->stat.ps_recv = (ULONG)counter;
}
else
{
p->stat.ps_recv = 0xFFFFFFFF;
}
status = g_TcFunctions.StatisticsQueryValue(statistics, TC_COUNTER_INSTANCE_RX_DROPPED_PACKETS, &counter);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error in TcStatisticsQueryValue: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
return NULL;
}
if (counter <= (ULONGLONG)0xFFFFFFFF)
{
p->stat.ps_ifdrop = (ULONG)counter;
p->stat.ps_drop = (ULONG)counter;
}
else
{
p->stat.ps_ifdrop = 0xFFFFFFFF;
p->stat.ps_drop = 0xFFFFFFFF;
}
#if defined(_WIN32) && defined(ENABLE_REMOTE)
p->stat.ps_capt = pt->TcAcceptedCount;
#endif
return &p->stat;
}
/* Set the dimension of the kernel-level capture buffer */
static int
TcSetBuff(pcap_t *p, int dim)
{
/*
* XXX turbocap has an internal way of managing buffers.
* And at the moment it's not configurable, so we just
* silently ignore the request to set the buffer.
*/
return 0;
}
static int
TcSetMode(pcap_t *p, int mode)
{
if (mode != MODE_CAPT)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Mode %u not supported by TurboCap devices. TurboCap only supports capture.", mode);
return -1;
}
return 0;
}
static int
TcSetMinToCopy(pcap_t *p, int size)
{
struct pcap_tc *pt = p->priv;
TC_STATUS status;
if (size < 0)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Mintocopy cannot be less than 0.");
return -1;
}
status = g_TcFunctions.InstanceSetFeature(pt->TcInstance, TC_INST_FT_MINTOCOPY, (ULONG)size);
if (status != TC_SUCCESS)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "TurboCap error setting the mintocopy: %s (%08x)", g_TcFunctions.StatusGetString(status), status);
}
return 0;
}
static HANDLE
TcGetReceiveWaitHandle(pcap_t *p)
{
struct pcap_tc *pt = p->priv;
return g_TcFunctions.InstanceGetReceiveWaitHandle(pt->TcInstance);
}
static int
TcOidGetRequest(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_, size_t *lenp _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"An OID get request cannot be performed on a TurboCap device");
return PCAP_ERROR;
}
static int
TcOidSetRequest(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
size_t *lenp _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"An OID set request cannot be performed on a TurboCap device");
return PCAP_ERROR;
}
static u_int
TcSendqueueTransmit(pcap_t *p, pcap_send_queue *queue _U_, int sync _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Packets cannot be bulk transmitted on a TurboCap device");
return 0;
}
static int
TcSetUserBuffer(pcap_t *p, int size _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"The user buffer cannot be set on a TurboCap device");
return -1;
}
static int
TcLiveDump(pcap_t *p, char *filename _U_, int maxsize _U_, int maxpacks _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Live packet dumping cannot be performed on a TurboCap device");
return -1;
}
static int
TcLiveDumpEnded(pcap_t *p, int sync _U_)
{
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"Live packet dumping cannot be performed on a TurboCap device");
return -1;
}
static PAirpcapHandle
TcGetAirPcapHandle(pcap_t *p _U_)
{
return NULL;
}
#endif
|
import numpy as np
import cv2
import sys
def main(argv):
if (int(argv[1]))==0: # read a mask image and a ROI and erase the masked parts from the roi
roi = cv2.imread(argv[2],0)
if roi is None:raise Exception("imageUtils no ROI at "+str(argv[2]))
treeMask = cv2.imread(argv[3],0)
if treeMask is None:raise Exception("imageUtils no maskTops at "+str(argv[3]))
roi[treeMask==0]=255
cv2.imwrite(argv[2],roi)
else:
raise Exception("demUtils, wrong code")
if __name__ == '__main__':
main(sys.argv)
|
from django.db import models
# Create your models here
from user.models import CustomUser
class DoctorClinic(models.Model):
user = models.ForeignKey(CustomUser, default = 1, verbose_name="username", on_delete = models.SET_DEFAULT)
doctor_name = models.CharField(max_length=256)
specialty = models.CharField(max_length=100)
clinic_name = models.CharField(max_length=256)
clinic_street= models.CharField(max_length=1000)
clinic_city = models.CharField(max_length=256)
clinic_state=models.CharField(max_length=200)
clinic_country = models.CharField(max_length=200)
clinic_zipcode = models.IntegerField()
doctor_id = models.CharField(max_length=64)
def __str__(self):
return self.doctor_id
|
import Toast from 'react-native-root-toast';
export function showToast(message) {
Toast.show(message, {
duration: Toast.durations.SHORT,
position: Toast.positions.CENTER,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});
}
|
from __future__ import unicode_literals
import datetime
import json
import re
from jinja2 import Environment, DictLoader, TemplateNotFound
import six
from six.moves.urllib.parse import parse_qs, urlparse
from werkzeug.exceptions import HTTPException
from moto.core.utils import camelcase_to_underscores, method_names_from_class
def _decode_dict(d):
decoded = {}
for key, value in d.items():
if isinstance(key, six.binary_type):
newkey = key.decode("utf-8")
elif isinstance(key, (list, tuple)):
newkey = []
for k in key:
if isinstance(k, six.binary_type):
newkey.append(k.decode('utf-8'))
else:
newkey.append(k)
else:
newkey = key
if isinstance(value, six.binary_type):
newvalue = value.decode("utf-8")
elif isinstance(value, (list, tuple)):
newvalue = []
for v in value:
if isinstance(v, six.binary_type):
newvalue.append(v.decode('utf-8'))
else:
newvalue.append(v)
else:
newvalue = value
decoded[newkey] = newvalue
return decoded
class DynamicDictLoader(DictLoader):
"""
Note: There's a bug in jinja2 pre-2.7.3 DictLoader where caching does not work.
Including the fixed (current) method version here to ensure performance benefit
even for those using older jinja versions.
"""
def get_source(self, environment, template):
if template in self.mapping:
source = self.mapping[template]
return source, None, lambda: source == self.mapping.get(template)
raise TemplateNotFound(template)
def update(self, mapping):
self.mapping.update(mapping)
def contains(self, template):
return bool(template in self.mapping)
class _TemplateEnvironmentMixin(object):
loader = DynamicDictLoader({})
environment = Environment(loader=loader)
def contains_template(self, template_id):
return self.loader.contains(template_id)
def response_template(self, source):
template_id = id(source)
if not self.contains_template(template_id):
self.loader.update({template_id: source})
self.environment = Environment(loader=self.loader)
return self.environment.get_template(template_id)
class BaseResponse(_TemplateEnvironmentMixin):
default_region = 'us-east-1'
region_regex = r'\.(.+?)\.amazonaws\.com'
@classmethod
def dispatch(cls, *args, **kwargs):
return cls()._dispatch(*args, **kwargs)
def _dispatch(self, request, full_url, headers):
querystring = {}
if hasattr(request, 'body'):
# Boto
self.body = request.body
else:
# Flask server
# FIXME: At least in Flask==0.10.1, request.data is an empty string
# and the information we want is in request.form. Keeping self.body
# definition for back-compatibility
self.body = request.data
querystring = {}
for key, value in request.form.items():
querystring[key] = [value, ]
if not querystring:
querystring.update(parse_qs(urlparse(full_url).query, keep_blank_values=True))
if not querystring:
querystring.update(parse_qs(self.body, keep_blank_values=True))
if not querystring:
querystring.update(headers)
querystring = _decode_dict(querystring)
self.uri = full_url
self.path = urlparse(full_url).path
self.querystring = querystring
self.method = request.method
region = re.search(self.region_regex, full_url)
if region:
self.region = region.group(1)
else:
self.region = self.default_region
self.headers = dict(request.headers)
self.response_headers = headers
return self.call_action()
def call_action(self):
headers = self.response_headers
action = self.querystring.get('Action', [""])[0]
if not action: # Some services use a header for the action
# Headers are case-insensitive. Probably a better way to do this.
match = self.headers.get('x-amz-target') or self.headers.get('X-Amz-Target')
if match:
action = match.split(".")[1]
action = camelcase_to_underscores(action)
method_names = method_names_from_class(self.__class__)
if action in method_names:
method = getattr(self, action)
try:
response = method()
except HTTPException as http_error:
response = http_error.description, dict(status=http_error.code)
if isinstance(response, six.string_types):
return 200, headers, response
else:
body, new_headers = response
status = new_headers.get('status', 200)
headers.update(new_headers)
return status, headers, body
raise NotImplementedError("The {0} action has not been implemented".format(action))
def _get_param(self, param_name):
return self.querystring.get(param_name, [None])[0]
def _get_int_param(self, param_name):
val = self._get_param(param_name)
if val is not None:
return int(val)
def _get_bool_param(self, param_name):
val = self._get_param(param_name)
if val is not None:
if val.lower() == 'true':
return True
elif val.lower() == 'false':
return False
def _get_multi_param(self, param_prefix):
"""
Given a querystring of ?LaunchConfigurationNames.member.1=my-test-1&LaunchConfigurationNames.member.2=my-test-2
this will return ['my-test-1', 'my-test-2']
"""
if param_prefix.endswith("."):
prefix = param_prefix
else:
prefix = param_prefix + "."
values = []
index = 1
while True:
try:
values.append(self.querystring[prefix + str(index)][0])
except KeyError:
break
else:
index += 1
return values
def _get_dict_param(self, param_prefix):
"""
Given a parameter dict of
{
'Instances.SlaveInstanceType': ['m1.small'],
'Instances.InstanceCount': ['1']
}
returns
{
"SlaveInstanceType": "m1.small",
"InstanceCount": "1",
}
"""
params = {}
for key, value in self.querystring.items():
if key.startswith(param_prefix):
params[camelcase_to_underscores(key.replace(param_prefix, ""))] = value[0]
return params
def _get_list_prefix(self, param_prefix):
"""
Given a query dict like
{
'Steps.member.1.Name': ['example1'],
'Steps.member.1.ActionOnFailure': ['TERMINATE_JOB_FLOW'],
'Steps.member.1.HadoopJarStep.Jar': ['streaming1.jar'],
'Steps.member.2.Name': ['example2'],
'Steps.member.2.ActionOnFailure': ['TERMINATE_JOB_FLOW'],
'Steps.member.2.HadoopJarStep.Jar': ['streaming2.jar'],
}
returns
[{
'name': u'example1',
'action_on_failure': u'TERMINATE_JOB_FLOW',
'hadoop_jar_step._jar': u'streaming1.jar',
}, {
'name': u'example2',
'action_on_failure': u'TERMINATE_JOB_FLOW',
'hadoop_jar_step._jar': u'streaming2.jar',
}]
"""
results = []
param_index = 1
while True:
index_prefix = "{0}.{1}.".format(param_prefix, param_index)
new_items = {}
for key, value in self.querystring.items():
if key.startswith(index_prefix):
new_items[camelcase_to_underscores(key.replace(index_prefix, ""))] = value[0]
if not new_items:
break
results.append(new_items)
param_index += 1
return results
def metadata_response(request, full_url, headers):
"""
Mock response for localhost metadata
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
"""
parsed_url = urlparse(full_url)
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
credentials = dict(
AccessKeyId="test-key",
SecretAccessKey="test-secret-key",
Token="test-session-token",
Expiration=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ")
)
path = parsed_url.path
meta_data_prefix = "/latest/meta-data/"
# Strip prefix if it is there
if path.startswith(meta_data_prefix):
path = path[len(meta_data_prefix):]
if path == '':
result = 'iam'
elif path == 'iam':
result = json.dumps({
'security-credentials': {
'default-role': credentials
}
})
elif path == 'iam/security-credentials/':
result = 'default-role'
elif path == 'iam/security-credentials/default-role':
result = json.dumps(credentials)
else:
raise NotImplementedError("The {0} metadata path has not been implemented".format(path))
return 200, headers, result
|
# coding=utf-8
# Copyright 2019 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from tensor2tensor.trax.backend import random
from tensor2tensor.trax.layers import initializers
class InitializersTest(absltest.TestCase):
def test_random_normal(self):
initializer = initializers.RandomNormalInitializer()
input_shape = (29, 5, 7, 20)
init_value = initializer(input_shape, random.get_prng(0))
self.assertEqual(tuple(init_value.shape), input_shape)
if __name__ == "__main__":
absltest.main()
|
def swap_case(s):
return "".join([char.lower() if char.isupper() else char.upper() for char in s])
if __name__ == '__main__':
print(swap_case(input()))
|
var $ = require('jquery')
var _ = require('underscore')
var Marionette = require('marionette')
var tpl = require('tpl/servers/parameters/list_item.html')
var template = _.template(tpl)
module.exports = Marionette.ItemView.extend({
tagName: 'tr',
template: template,
events: {
'click button.delete': 'delete',
'change input#parameter': 'changed',
'click button.clone': 'clone'
},
changed: function (e) {
var val = $(e.target).val()
this.model.set(e.target.id, val)
},
delete: function (e) {
e.preventDefault()
this.model.destroy()
}
})
|
export default {
setUser(state, payload) {
state.token = payload.token
// state.userId = payload.userId
// state.imageLink = payload.imageLink
state.didAutoLogout = false
},
setAutoLogout(state) {
state.didAutoLogout = true
},
}
|
"""
Simple script for preprocessing youtube comments data.
This example show you how to clean data from negative comments.
If you want clean positive comments replace:
columns = ['id','user','date','timestamp','likes']
data['rate'] = 1
output = save as other name, such as mergetYT2.csv
"""
# Import necessary packages
import pandas as pd
import numpy as np
# Read data
data = pd.read_csv('mergedYT.csv', delimiter=',')
# Select unused columns
columns = ['date','hasReplies','id','likes','numberOfReplies','replies.commentText','replies.date','replies.id','replies.likes',
'replies.timestamp','replies.user','timestamp','user']
# Drop unused columns
data.drop(columns, inplace=True, axis=1)
# Add new column 'rate' as label for our neural network
data['rate'] = -1
# Get the length of text comments - add new column 'length' into CSV file
data['length'] = data['commentText'].str.len()
# Drop rows where len of strings are less than 20
data = data[data['commentText'].str.len() > 20]
# Drop URLs
data['commentText'] = data['commentText'].str.replace(r'http([^\s]+)','').astype('str')
# Drop words with #Hashtag
data['commentText'] = data['commentText'].str.replace(r'#([^\s]+)', '').astype('str')
# Drop Emoji from text and 'text images'
data['commentText'] = data['commentText'].str.replace(r'[^\w\s,]', '').astype('str')
# Remove lead white spaces
data['commentText'] = data['commentText'].str.lstrip()
# Rename commentText -> description for our neural network
data.rename(columns={'commentText':'description'}, inplace=True)
print(data)
# Save data after preprocessing
output = data.to_csv('mergedYT1.csv', encoding='utf8', index=False, header=True)
|
from ctypes import *
import unittest, sys
from test import support
################################################################
# This section should be moved into ctypes\__init__.py, when it's ready.
from _ctypes import PyObj_FromPtr
################################################################
try:
from sys import getrefcount as grc
except ImportError:
grc = None
if sys.version_info > (2, 4):
c_py_ssize_t = c_size_t
else:
c_py_ssize_t = c_int
@support.cpython_only
class PythonAPITestCase(unittest.TestCase):
def test_PyBytes_FromStringAndSize(self):
PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize
PyBytes_FromStringAndSize.restype = py_object
PyBytes_FromStringAndSize.argtypes = c_char_p, c_py_ssize_t
self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc")
@support.refcount_test
def test_PyString_FromString(self):
pythonapi.PyBytes_FromString.restype = py_object
pythonapi.PyBytes_FromString.argtypes = (c_char_p,)
s = b"abc"
refcnt = grc(s)
pyob = pythonapi.PyBytes_FromString(s)
self.assertEqual(grc(s), refcnt)
self.assertEqual(s, pyob)
del pyob
self.assertEqual(grc(s), refcnt)
@support.refcount_test
def test_PyLong_Long(self):
ref42 = grc(42)
pythonapi.PyLong_FromLong.restype = py_object
self.assertEqual(pythonapi.PyLong_FromLong(42), 42)
self.assertEqual(grc(42), ref42)
pythonapi.PyLong_AsLong.argtypes = (py_object,)
pythonapi.PyLong_AsLong.restype = c_long
res = pythonapi.PyLong_AsLong(42)
self.assertEqual(grc(res), ref42 + 1)
del res
self.assertEqual(grc(42), ref42)
@support.refcount_test
def test_PyObj_FromPtr(self):
s = "abc def ghi jkl"
ref = grc(s)
# id(python-object) is the address
pyobj = PyObj_FromPtr(id(s))
self.assertIs(s, pyobj)
self.assertEqual(grc(s), ref + 1)
del pyobj
self.assertEqual(grc(s), ref)
def test_PyOS_snprintf(self):
PyOS_snprintf = pythonapi.PyOS_snprintf
PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
buf = c_buffer(256)
PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes")
self.assertEqual(buf.value, b"Hello from ctypes")
PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)")
# not enough arguments
self.assertRaises(TypeError, PyOS_snprintf, buf)
def test_pyobject_repr(self):
self.assertEqual(repr(py_object()), "py_object(<NULL>)")
self.assertEqual(repr(py_object(42)), "py_object(42)")
self.assertEqual(repr(py_object(object)), "py_object(%r)" % object)
if __name__ == "__main__":
unittest.main()
|
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = 'Vendor estuvo aqui';
return element;
}
// document.body.appendChild(component());
|
// import models
const Product = require('./Product');
const Category = require('./Category');
const Tag = require('./Tag');
const ProductTag = require('./ProductTag');
Product.belongsTo(Category, {
foreignKey: 'category_id',
});
Category.hasMany(Product, {
foreignKey: 'category_id',
});
Product.belongsToMany(Tag, {
through: ProductTag,
foreignKey: 'product_id'
});
Tag.belongsToMany(Product, {
through: ProductTag,
foreignKey: 'tag_id'
});
module.exports = {
Product,
Category,
Tag,
ProductTag,
};
|
/* eslint-disable import/no-extraneous-dependencies */
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const PATHDIR = require('./paths');
const env = require('./env');
module.exports = {
context: PATHDIR.SRC,
entry: {
app: './App.jsx',
},
output: {
path: PATHDIR.DIST,
filename: '[name].bundle.[chunkHash].js',
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css'],
},
module: {
rules: [
{
enforce: 'pre',
test: /\.jsx$|\.js$/,
include: PATHDIR.SRC,
loader: 'eslint-loader',
},
{
test: /\.css$|\.map$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader',
options: {
minimize: true,
sourceMap: true,
},
}],
}),
},
{
test: /.jsx?$/,
include: PATHDIR.SRC,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(eot|ttf|svg|gif|png)$/,
loader: 'file-loader',
},
{
test: /\.(woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: 'url-loader?limit=10000',
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader',
},
],
},
plugins: [
new webpack.DefinePlugin(env),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer',
}),
new CleanWebpackPlugin(['dist'], {
root: PATHDIR.ROOT,
verbose: true,
}),
new ExtractTextPlugin({ filename: '[name].[contentHash].css' }),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Tether: 'tether',
}),
],
};
|
/*
* 1-Wire implementation for the ds2760 chip
*
* Copyright © 2004-2005, Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/idr.h>
#include <linux/gfp.h>
#include "../w1.h"
#include "../w1_int.h"
#include "../w1_family.h"
#include "w1_ds2760.h"
static int w1_ds2760_io(struct device *dev, char *buf, int addr, size_t count,
int io)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (!dev)
return 0;
mutex_lock(&sl->master->bus_mutex);
if (addr > DS2760_DATA_SIZE || addr < 0) {
count = 0;
goto out;
}
if (addr + count > DS2760_DATA_SIZE)
count = DS2760_DATA_SIZE - addr;
if (!w1_reset_select_slave(sl)) {
if (!io) {
w1_write_8(sl->master, W1_DS2760_READ_DATA);
w1_write_8(sl->master, addr);
count = w1_read_block(sl->master, buf, count);
} else {
w1_write_8(sl->master, W1_DS2760_WRITE_DATA);
w1_write_8(sl->master, addr);
w1_write_block(sl->master, buf, count);
/* XXX w1_write_block returns void, not n_written */
}
}
out:
mutex_unlock(&sl->master->bus_mutex);
return count;
}
int w1_ds2760_read(struct device *dev, char *buf, int addr, size_t count)
{
return w1_ds2760_io(dev, buf, addr, count, 0);
}
int w1_ds2760_write(struct device *dev, char *buf, int addr, size_t count)
{
return w1_ds2760_io(dev, buf, addr, count, 1);
}
static int w1_ds2760_eeprom_cmd(struct device *dev, int addr, int cmd)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (!dev)
return -EINVAL;
mutex_lock(&sl->master->bus_mutex);
if (w1_reset_select_slave(sl) == 0) {
w1_write_8(sl->master, cmd);
w1_write_8(sl->master, addr);
}
mutex_unlock(&sl->master->bus_mutex);
return 0;
}
int w1_ds2760_store_eeprom(struct device *dev, int addr)
{
return w1_ds2760_eeprom_cmd(dev, addr, W1_DS2760_COPY_DATA);
}
int w1_ds2760_recall_eeprom(struct device *dev, int addr)
{
return w1_ds2760_eeprom_cmd(dev, addr, W1_DS2760_RECALL_DATA);
}
static ssize_t w1_slave_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr, char *buf,
loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
return w1_ds2760_read(dev, buf, off, count);
}
static BIN_ATTR_RO(w1_slave, DS2760_DATA_SIZE);
static struct bin_attribute *w1_ds2760_bin_attrs[] = {
&bin_attr_w1_slave,
NULL,
};
static const struct attribute_group w1_ds2760_group = {
.bin_attrs = w1_ds2760_bin_attrs,
};
static const struct attribute_group *w1_ds2760_groups[] = {
&w1_ds2760_group,
NULL,
};
static DEFINE_IDA(bat_ida);
static int w1_ds2760_add_slave(struct w1_slave *sl)
{
int ret;
int id;
struct platform_device *pdev;
id = ida_simple_get(&bat_ida, 0, 0, GFP_KERNEL);
if (id < 0) {
ret = id;
goto noid;
}
pdev = platform_device_alloc("ds2760-battery", id);
if (!pdev) {
ret = -ENOMEM;
goto pdev_alloc_failed;
}
pdev->dev.parent = &sl->dev;
ret = platform_device_add(pdev);
if (ret)
goto pdev_add_failed;
dev_set_drvdata(&sl->dev, pdev);
goto success;
pdev_add_failed:
platform_device_put(pdev);
pdev_alloc_failed:
ida_simple_remove(&bat_ida, id);
noid:
success:
return ret;
}
static void w1_ds2760_remove_slave(struct w1_slave *sl)
{
struct platform_device *pdev = dev_get_drvdata(&sl->dev);
int id = pdev->id;
platform_device_unregister(pdev);
ida_simple_remove(&bat_ida, id);
}
static struct w1_family_ops w1_ds2760_fops = {
.add_slave = w1_ds2760_add_slave,
.remove_slave = w1_ds2760_remove_slave,
.groups = w1_ds2760_groups,
};
static struct w1_family w1_ds2760_family = {
.fid = W1_FAMILY_DS2760,
.fops = &w1_ds2760_fops,
};
static int __init w1_ds2760_init(void)
{
printk(KERN_INFO "1-Wire driver for the DS2760 battery monitor "
" chip - (c) 2004-2005, Szabolcs Gyurko\n");
ida_init(&bat_ida);
return w1_register_family(&w1_ds2760_family);
}
static void __exit w1_ds2760_exit(void)
{
w1_unregister_family(&w1_ds2760_family);
ida_destroy(&bat_ida);
}
EXPORT_SYMBOL(w1_ds2760_read);
EXPORT_SYMBOL(w1_ds2760_write);
EXPORT_SYMBOL(w1_ds2760_store_eeprom);
EXPORT_SYMBOL(w1_ds2760_recall_eeprom);
module_init(w1_ds2760_init);
module_exit(w1_ds2760_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>");
MODULE_DESCRIPTION("1-wire Driver Dallas 2760 battery monitor chip");
MODULE_ALIAS("w1-family-" __stringify(W1_FAMILY_DS2760));
|
import math
class Planet:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
self.x_vel = 0
self.y_vel = 0
self.z_vel = 0
def apply_velocity(self):
self.x += self.x_vel
self.y += self.y_vel
self.z += self.z_vel
def potential_energy(self):
return abs(self.x) + abs(self.y) + abs(self.z)
def kinetic_energy(self):
return abs(self.x_vel) + abs(self.y_vel) + abs(self.z_vel)
def total_energy(self):
return self.potential_energy() * self.kinetic_energy()
def process_input():
planets = []
with open("input.txt") as f:
for line in f:
x, y, z = line.strip().replace("<", "").replace(">", "").split(", ")
planets.append(
Planet(
int(x.split("=")[-1]), int(y.split("=")[-1]), int(z.split("=")[-1])
)
)
return planets
def apply_gravity(p1, p2):
if p1.x > p2.x:
p1.x_vel -= 1
p2.x_vel += 1
elif p1.x < p2.x:
p1.x_vel += 1
p2.x_vel -= 1
if p1.y > p2.y:
p1.y_vel -= 1
p2.y_vel += 1
elif p1.y < p2.y:
p1.y_vel += 1
p2.y_vel -= 1
if p1.z > p2.z:
p1.z_vel -= 1
p2.z_vel += 1
elif p1.z < p2.z:
p1.z_vel += 1
p2.z_vel -= 1
def current_state(planets, find):
state_string = ""
for planet in planets:
if find == "x":
state_string += str(planet.x) + str(planet.x_vel)
elif find == "y":
state_string += str(planet.y) + str(planet.y_vel)
elif find == "z":
state_string += str(planet.z) + str(planet.z_vel)
return state_string
def step(planets):
for index, planet in enumerate(planets):
for second_planet in planets[index:]:
apply_gravity(planet, second_planet)
for planet in planets:
planet.apply_velocity()
def total_energy(planets):
return sum([planet.total_energy() for planet in planets])
def find_repeats(planets):
initial_x_state = current_state(planets, "x")
initial_y_state = current_state(planets, "y")
initial_z_state = current_state(planets, "z")
x_period, y_period, z_period = 0, 0, 0
step(planets)
steps = 1
while 0 in [x_period, y_period, z_period]:
step(planets)
steps += 1
if x_period == 0 and current_state(planets, "x") == initial_x_state:
x_period = steps
if y_period == 0 and current_state(planets, "y") == initial_y_state:
y_period = steps
if z_period == 0 and current_state(planets, "z") == initial_z_state:
z_period = steps
return x_period, y_period, z_period
def lcm(a, b):
return a * b // math.gcd(a, b)
def run():
planets = process_input()
for x in range(1000):
step(planets)
print(f"part one: {total_energy(planets)} total energy\n")
x, y, z = find_repeats(planets)
print(f"part two: {lcm(lcm(x, y), z)} steps")
if __name__ == "__main__":
run()
|
# GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins
# Copyright (c) 2016-2019 Dave Jones <dave@waveform.org.uk>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
str = type('')
import sys
import pytest
import warnings
from threading import Event, Thread
from gpiozero import Device
from gpiozero.pins.mock import MockFactory, MockPWMPin
# NOTE: Work-around for python versions <3.4: in these versions the
# resetwarnings function in the warnings module doesn't do much (or doesn't do
# what most would expect). Warnings that have already been triggered still
# won't be re-triggered even after the call. To work-around this we set the
# default filter to "always" on these versions before running any tests. Note
# that this does mean you should run resetwarnings() whenever using
# catch_warnings()
if sys.version_info[:2] < (3, 4):
warnings.simplefilter('always')
@pytest.yield_fixture()
def no_default_factory(request):
save_pin_factory = Device.pin_factory
Device.pin_factory = None
try:
yield None
finally:
Device.pin_factory = save_pin_factory
@pytest.yield_fixture(scope='function')
def mock_factory(request):
save_factory = Device.pin_factory
Device.pin_factory = MockFactory()
try:
yield Device.pin_factory
# This reset() may seem redundant given we're re-constructing the
# factory for each function that requires it but MockFactory (via
# LocalFactory) stores some info at the class level which reset()
# clears.
finally:
if Device.pin_factory is not None:
Device.pin_factory.reset()
Device.pin_factory = save_factory
@pytest.fixture()
def pwm(request, mock_factory):
mock_factory.pin_class = MockPWMPin
class ThreadedTest(Thread):
def __init__(self, test_fn, *args, **kwargs):
self._fn = test_fn
self._args = args
self._kwargs = kwargs
self._result = None
super(ThreadedTest, self).__init__()
self.daemon = True
self.start()
def run(self):
self._result = self._fn(*self._args, **self._kwargs)
@property
def result(self):
self.join(1)
if not self.is_alive():
return self._result
else:
raise RuntimeError('test thread did not finish')
|
/**
* @module ol/control/ZoomSlider
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import Control from './Control.js';
import EventType from '../events/EventType.js';
import PointerEventType from '../pointer/EventType.js';
import { CLASS_CONTROL, CLASS_UNSELECTABLE } from '../css.js';
import { clamp } from '../math.js';
import { easeOut } from '../easing.js';
import { listen, unlistenByKey } from '../events.js';
import { stopPropagation } from '../events/Event.js';
/**
* The enum for available directions.
*
* @enum {number}
*/
var Direction = {
VERTICAL: 0,
HORIZONTAL: 1,
};
/**
* @typedef {Object} Options
* @property {string} [className='ol-zoomslider'] CSS class name.
* @property {number} [duration=200] Animation duration in milliseconds.
* @property {function(import("../MapEvent.js").default):void} [render] Function called when the control
* should be re-rendered. This is called in a `requestAnimationFrame` callback.
*/
/**
* @classdesc
* A slider type of control for zooming.
*
* Example:
*
* map.addControl(new ZoomSlider());
*
* @api
*/
var ZoomSlider = /** @class */ (function (_super) {
__extends(ZoomSlider, _super);
/**
* @param {Options=} opt_options Zoom slider options.
*/
function ZoomSlider(opt_options) {
var _this = this;
var options = opt_options ? opt_options : {};
_this = _super.call(this, {
element: document.createElement('div'),
render: options.render,
}) || this;
/**
* @type {!Array.<import("../events.js").EventsKey>}
* @private
*/
_this.dragListenerKeys_ = [];
/**
* Will hold the current resolution of the view.
*
* @type {number|undefined}
* @private
*/
_this.currentResolution_ = undefined;
/**
* The direction of the slider. Will be determined from actual display of the
* container and defaults to Direction.VERTICAL.
*
* @type {Direction}
* @private
*/
_this.direction_ = Direction.VERTICAL;
/**
* @type {boolean}
* @private
*/
_this.dragging_;
/**
* @type {number}
* @private
*/
_this.heightLimit_ = 0;
/**
* @type {number}
* @private
*/
_this.widthLimit_ = 0;
/**
* @type {number|undefined}
* @private
*/
_this.startX_;
/**
* @type {number|undefined}
* @private
*/
_this.startY_;
/**
* The calculated thumb size (border box plus margins). Set when initSlider_
* is called.
* @type {import("../size.js").Size}
* @private
*/
_this.thumbSize_ = null;
/**
* Whether the slider is initialized.
* @type {boolean}
* @private
*/
_this.sliderInitialized_ = false;
/**
* @type {number}
* @private
*/
_this.duration_ = options.duration !== undefined ? options.duration : 200;
var className = options.className !== undefined ? options.className : 'ol-zoomslider';
var thumbElement = document.createElement('button');
thumbElement.setAttribute('type', 'button');
thumbElement.className = className + '-thumb ' + CLASS_UNSELECTABLE;
var containerElement = _this.element;
containerElement.className =
className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
containerElement.appendChild(thumbElement);
containerElement.addEventListener(PointerEventType.POINTERDOWN, _this.handleDraggerStart_.bind(_this), false);
containerElement.addEventListener(PointerEventType.POINTERMOVE, _this.handleDraggerDrag_.bind(_this), false);
containerElement.addEventListener(PointerEventType.POINTERUP, _this.handleDraggerEnd_.bind(_this), false);
containerElement.addEventListener(EventType.CLICK, _this.handleContainerClick_.bind(_this), false);
thumbElement.addEventListener(EventType.CLICK, stopPropagation, false);
return _this;
}
/**
* Remove the control from its current map and attach it to the new map.
* Subclasses may set up event handlers to get notified about changes to
* the map here.
* @param {import("../PluggableMap.js").default} map Map.
* @api
*/
ZoomSlider.prototype.setMap = function (map) {
_super.prototype.setMap.call(this, map);
if (map) {
map.render();
}
};
/**
* Initializes the slider element. This will determine and set this controls
* direction_ and also constrain the dragging of the thumb to always be within
* the bounds of the container.
*
* @return {boolean} Initialization successful
* @private
*/
ZoomSlider.prototype.initSlider_ = function () {
var container = this.element;
var containerWidth = container.offsetWidth;
var containerHeight = container.offsetHeight;
if (containerWidth === 0 && containerHeight === 0) {
return (this.sliderInitialized_ = false);
}
var thumb = /** @type {HTMLElement} */ (container.firstElementChild);
var computedStyle = getComputedStyle(thumb);
var thumbWidth = thumb.offsetWidth +
parseFloat(computedStyle['marginRight']) +
parseFloat(computedStyle['marginLeft']);
var thumbHeight = thumb.offsetHeight +
parseFloat(computedStyle['marginTop']) +
parseFloat(computedStyle['marginBottom']);
this.thumbSize_ = [thumbWidth, thumbHeight];
if (containerWidth > containerHeight) {
this.direction_ = Direction.HORIZONTAL;
this.widthLimit_ = containerWidth - thumbWidth;
}
else {
this.direction_ = Direction.VERTICAL;
this.heightLimit_ = containerHeight - thumbHeight;
}
return (this.sliderInitialized_ = true);
};
/**
* @param {PointerEvent} event The browser event to handle.
* @private
*/
ZoomSlider.prototype.handleContainerClick_ = function (event) {
var view = this.getMap().getView();
var relativePosition = this.getRelativePosition_(event.offsetX - this.thumbSize_[0] / 2, event.offsetY - this.thumbSize_[1] / 2);
var resolution = this.getResolutionForPosition_(relativePosition);
var zoom = view.getConstrainedZoom(view.getZoomForResolution(resolution));
view.animateInternal({
zoom: zoom,
duration: this.duration_,
easing: easeOut,
});
};
/**
* Handle dragger start events.
* @param {PointerEvent} event The drag event.
* @private
*/
ZoomSlider.prototype.handleDraggerStart_ = function (event) {
if (!this.dragging_ && event.target === this.element.firstElementChild) {
var element = /** @type {HTMLElement} */ (this.element
.firstElementChild);
this.getMap().getView().beginInteraction();
this.startX_ = event.clientX - parseFloat(element.style.left);
this.startY_ = event.clientY - parseFloat(element.style.top);
this.dragging_ = true;
if (this.dragListenerKeys_.length === 0) {
var drag = this.handleDraggerDrag_;
var end = this.handleDraggerEnd_;
this.dragListenerKeys_.push(listen(document, PointerEventType.POINTERMOVE, drag, this), listen(document, PointerEventType.POINTERUP, end, this));
}
}
};
/**
* Handle dragger drag events.
*
* @param {PointerEvent} event The drag event.
* @private
*/
ZoomSlider.prototype.handleDraggerDrag_ = function (event) {
if (this.dragging_) {
var deltaX = event.clientX - this.startX_;
var deltaY = event.clientY - this.startY_;
var relativePosition = this.getRelativePosition_(deltaX, deltaY);
this.currentResolution_ = this.getResolutionForPosition_(relativePosition);
this.getMap().getView().setResolution(this.currentResolution_);
}
};
/**
* Handle dragger end events.
* @param {PointerEvent} event The drag event.
* @private
*/
ZoomSlider.prototype.handleDraggerEnd_ = function (event) {
if (this.dragging_) {
var view = this.getMap().getView();
view.endInteraction();
this.dragging_ = false;
this.startX_ = undefined;
this.startY_ = undefined;
this.dragListenerKeys_.forEach(unlistenByKey);
this.dragListenerKeys_.length = 0;
}
};
/**
* Positions the thumb inside its container according to the given resolution.
*
* @param {number} res The res.
* @private
*/
ZoomSlider.prototype.setThumbPosition_ = function (res) {
var position = this.getPositionForResolution_(res);
var thumb = /** @type {HTMLElement} */ (this.element.firstElementChild);
if (this.direction_ == Direction.HORIZONTAL) {
thumb.style.left = this.widthLimit_ * position + 'px';
}
else {
thumb.style.top = this.heightLimit_ * position + 'px';
}
};
/**
* Calculates the relative position of the thumb given x and y offsets. The
* relative position scales from 0 to 1. The x and y offsets are assumed to be
* in pixel units within the dragger limits.
*
* @param {number} x Pixel position relative to the left of the slider.
* @param {number} y Pixel position relative to the top of the slider.
* @return {number} The relative position of the thumb.
* @private
*/
ZoomSlider.prototype.getRelativePosition_ = function (x, y) {
var amount;
if (this.direction_ === Direction.HORIZONTAL) {
amount = x / this.widthLimit_;
}
else {
amount = y / this.heightLimit_;
}
return clamp(amount, 0, 1);
};
/**
* Calculates the corresponding resolution of the thumb given its relative
* position (where 0 is the minimum and 1 is the maximum).
*
* @param {number} position The relative position of the thumb.
* @return {number} The corresponding resolution.
* @private
*/
ZoomSlider.prototype.getResolutionForPosition_ = function (position) {
var fn = this.getMap().getView().getResolutionForValueFunction();
return fn(1 - position);
};
/**
* Determines the relative position of the slider for the given resolution. A
* relative position of 0 corresponds to the minimum view resolution. A
* relative position of 1 corresponds to the maximum view resolution.
*
* @param {number} res The resolution.
* @return {number} The relative position value (between 0 and 1).
* @private
*/
ZoomSlider.prototype.getPositionForResolution_ = function (res) {
var fn = this.getMap().getView().getValueForResolutionFunction();
return clamp(1 - fn(res), 0, 1);
};
/**
* Update the zoomslider element.
* @param {import("../MapEvent.js").default} mapEvent Map event.
* @override
*/
ZoomSlider.prototype.render = function (mapEvent) {
if (!mapEvent.frameState) {
return;
}
if (!this.sliderInitialized_ && !this.initSlider_()) {
return;
}
var res = mapEvent.frameState.viewState.resolution;
this.currentResolution_ = res;
this.setThumbPosition_(res);
};
return ZoomSlider;
}(Control));
export default ZoomSlider;
//# sourceMappingURL=ZoomSlider.js.map
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
Author: tjado <https://github.com/tejado>
"""
import argparse
import codecs
import json
import logging
import os
import ssl
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import time
import signal
import string
import subprocess
from datetime import timedelta
from getpass import getpass
from pgoapi.exceptions import NotLoggedInException, ServerSideRequestThrottlingException, ServerBusyOrOfflineException
from geopy.exc import GeocoderQuotaExceeded
from pokemongo_bot import inventory
from pokemongo_bot import PokemonGoBot, TreeConfigBuilder
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.health_record import BotEvent
from pokemongo_bot.plugin_loader import PluginLoader
from pokemongo_bot.api_wrapper import PermaBannedException
try:
from demjson import jsonlint
except ImportError:
# Run `pip install -r requirements.txt` to fix this
jsonlint = None
if sys.version_info >= (2, 7, 9):
ssl._create_default_https_context = ssl._create_unverified_context
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)10s] [%(levelname)s] %(message)s')
logger = logging.getLogger('cli')
logger.setLevel(logging.INFO)
class SIGINTRecieved(Exception): pass
def main():
bot = False
def handle_sigint(*args):
raise SIGINTRecieved
signal.signal(signal.SIGINT, handle_sigint)
def get_commit_hash():
try:
hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=subprocess.STDOUT)[:-1]
return hash if all(c in string.hexdigits for c in hash) else "not found"
except:
return "not found"
try:
logger.info('PokemonGO Bot v1.0')
logger.info('commit: ' + get_commit_hash())
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
config = init_config()
if not config:
return
logger.info('Configuration initialized')
health_record = BotEvent(config)
health_record.login_success()
finished = False
while not finished:
try:
bot = PokemonGoBot(config)
bot.start()
tree = TreeConfigBuilder(bot, config.raw_tasks).build()
bot.workers = tree
bot.metrics.capture_stats()
bot.health_record = health_record
bot.event_manager.emit(
'bot_start',
sender=bot,
level='info',
formatted='Starting bot...'
)
while True:
bot.tick()
except KeyboardInterrupt:
bot.event_manager.emit(
'bot_exit',
sender=bot,
level='info',
formatted='Exiting bot.'
)
finished = True
report_summary(bot)
except NotLoggedInException:
wait_time = config.reconnecting_timeout * 60
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Log logged in, reconnecting in {:d}'.format(wait_time)
)
time.sleep(wait_time)
except ServerBusyOrOfflineException:
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Server busy or offline'
)
except ServerSideRequestThrottlingException:
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Server is throttling, reconnecting in 30 seconds'
)
time.sleep(30)
except PermaBannedException:
bot.event_manager.emit(
'api_error',
sender=bot,
level='info',
formatted='Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
)
except GeocoderQuotaExceeded:
raise Exception("Google Maps API key over requests limit.")
except SIGINTRecieved:
if bot:
bot.event_manager.emit(
'bot_interrupted',
sender=bot,
level='info',
formatted='Bot caught SIGINT. Shutting down.'
)
report_summary(bot)
except Exception as e:
# always report session summary and then raise exception
if bot:
report_summary(bot)
raise
finally:
# Cache here on SIGTERM, or Exception. Check data is available and worth caching.
if bot:
if bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
cached_forts_path = os.path.join(
_base_dir, 'data', 'recent-forts-%s.json' % bot.config.username
)
try:
with open(cached_forts_path, 'w') as outfile:
json.dump(bot.recent_forts, outfile)
bot.event_manager.emit(
'cached_fort',
sender=bot,
level='debug',
formatted='Forts cached.',
)
except IOError as e:
bot.event_manager.emit(
'error_caching_forts',
sender=bot,
level='debug',
formatted='Error caching forts for {path}',
data={'path': cached_forts_path}
)
def report_summary(bot):
if bot.metrics.start_time is None:
return # Bot didn't actually start, no metrics to show.
metrics = bot.metrics
metrics.capture_stats()
logger.info('')
logger.info('Ran for {}'.format(metrics.runtime()))
logger.info('Total XP Earned: {} Average: {:.2f}/h'.format(metrics.xp_earned(), metrics.xp_per_hour()))
logger.info('Travelled {:.2f}km'.format(metrics.distance_travelled()))
logger.info('Visited {} stops'.format(metrics.visits['latest'] - metrics.visits['start']))
logger.info('Encountered {} pokemon, {} caught, {} released, {} evolved, {} never seen before'
.format(metrics.num_encounters(), metrics.num_captures(), metrics.releases,
metrics.num_evolutions(), metrics.num_new_mons()))
logger.info('Threw {} pokeball{}'.format(metrics.num_throws(), '' if metrics.num_throws() == 1 else 's'))
logger.info('Earned {} Stardust'.format(metrics.earned_dust()))
logger.info('Hatched eggs {}'.format(metrics.hatched_eggs(0)))
if (metrics.next_hatching_km(0)):
logger.info('Next egg hatches in {:.2f} km'.format(metrics.next_hatching_km(0)))
logger.info('')
if metrics.highest_cp is not None:
logger.info('Highest CP Pokemon: {}'.format(metrics.highest_cp['desc']))
if metrics.most_perfect is not None:
logger.info('Most Perfect Pokemon: {}'.format(metrics.most_perfect['desc']))
def init_config():
parser = argparse.ArgumentParser()
config_file = os.path.join(_base_dir, 'configs', 'config.json')
web_dir = "web"
# If config file exists, load variables from json
load = {}
def _json_loader(filename):
try:
with open(filename, 'rb') as data:
load.update(json.load(data))
except ValueError:
if jsonlint:
with open(filename, 'rb') as data:
lint = jsonlint()
rc = lint.main(['-v', filename])
logger.critical('Error with configuration file')
sys.exit(-1)
# Select a config file code
parser.add_argument("-cf", "--config", help="Config File to use")
config_arg = parser.parse_known_args() and parser.parse_known_args()[0].config or None
if config_arg and os.path.isfile(config_arg):
_json_loader(config_arg)
elif os.path.isfile(config_file):
logger.info('No config argument specified, checking for /configs/config.json')
_json_loader(config_file)
else:
logger.info('Error: No /configs/config.json or specified config')
# Read passed in Arguments
required = lambda x: not x in load
add_config(
parser,
load,
short_flag="-a",
long_flag="--auth_service",
help="Auth Service ('ptc' or 'google')",
required=required("auth_service"),
default=None
)
add_config(
parser,
load,
short_flag="-u",
long_flag="--username",
help="Username",
default=None
)
add_config(
parser,
load,
short_flag="-ws",
long_flag="--websocket.server_url",
help="Connect to websocket server at given url",
default=False
)
add_config(
parser,
load,
short_flag="-wss",
long_flag="--websocket.start_embedded_server",
help="Start embedded websocket server",
default=False
)
add_config(
parser,
load,
short_flag="-wsr",
long_flag="--websocket.remote_control",
help="Enable remote control through websocket (requires websocekt server url)",
default=False
)
add_config(
parser,
load,
short_flag="-p",
long_flag="--password",
help="Password",
default=None
)
add_config(
parser,
load,
short_flag="-l",
long_flag="--location",
help="Location",
type=parse_unicode_str,
default=''
)
add_config(
parser,
load,
short_flag="-lc",
long_flag="--location_cache",
help="Bot will start at last known location",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--forts.spin",
help="Enable Spinning Pokestops",
type=bool,
default=True,
)
add_config(
parser,
load,
short_flag="-wmax",
long_flag="--walk_max",
help=
"Walk instead of teleport with given speed",
type=float,
default=2.5
)
add_config(
parser,
load,
short_flag="-wmin",
long_flag="--walk_min",
help=
"Walk instead of teleport with given speed",
type=float,
default=2.5
)
add_config(
parser,
load,
short_flag="-k",
long_flag="--gmapkey",
help="Set Google Maps API KEY",
type=str,
default=None
)
add_config(
parser,
load,
short_flag="-e",
long_flag="--show_events",
help="Show events",
type=bool,
default=False
)
add_config(
parser,
load,
short_flag="-d",
long_flag="--debug",
help="Debug Mode",
type=bool,
default=False
)
add_config(
parser,
load,
short_flag="-t",
long_flag="--test",
help="Only parse the specified location",
type=bool,
default=False
)
add_config(
parser,
load,
short_flag="-du",
long_flag="--distance_unit",
help="Set the unit to display distance in (e.g, km for kilometers, mi for miles, ft for feet)",
type=str,
default='km'
)
add_config(
parser,
load,
short_flag="-rt",
long_flag="--reconnecting_timeout",
help="Timeout between reconnecting if error occured (in minutes, e.g. 15)",
type=float,
default=15.0
)
add_config(
parser,
load,
short_flag="-hr",
long_flag="--health_record",
help="Send anonymous bot event to GA for bot health record. Set \"health_record\":false if you need disable it.",
type=bool,
default=True
)
add_config(
parser,
load,
short_flag="-ac",
long_flag="--forts.avoid_circles",
help="Avoids circles (pokestops) of the max size set in max_circle_size flag",
type=bool,
default=False,
)
add_config(
parser,
load,
short_flag="-mcs",
long_flag="--forts.max_circle_size",
help="If avoid_circles flag is set, this flag specifies the maximum size of circles (pokestops) avoided",
type=int,
default=10,
)
add_config(
parser,
load,
short_flag="-crf",
long_flag="--forts.cache_recent_forts",
help="Caches recent forts used by max_circle_size",
type=bool,
default=True,
)
add_config(
parser,
load,
long_flag="--map_object_cache_time",
help="Amount of seconds to keep the map object in cache (bypass Niantic throttling)",
type=float,
default=5.0
)
add_config(
parser,
load,
long_flag="--logging_color",
help="If logging_color is set to true, colorized logging handler will be used",
type=bool,
default=True
)
add_config(
parser,
load,
long_flag="--heartbeat_threshold",
help="A threshold between each heartbeat sending to server",
type=int,
default=10
)
add_config(
parser,
load,
long_flag="--pokemon_bag.show_at_start",
help="Logs all pokemon in the bag at bot start",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--pokemon_bag.show_count",
help="Shows the amount of which pokemon (minimum 1)",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--pokemon_bag.show_candies",
help="Shows the amount of candies for each pokemon",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--pokemon_bag.pokemon_info",
help="List with the info to show for each pokemon",
type=bool,
default=[]
)
add_config(
parser,
load,
long_flag="--alt_min",
help="Minimum random altitude",
type=float,
default=500
)
add_config(
parser,
load,
long_flag="--alt_max",
help="Maximum random altitude",
type=float,
default=1000
)
add_config(
parser,
load,
long_flag="--replicate_gps_xy_noise",
help="Add noise to current position",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--replicate_gps_z_noise",
help="Add noise to current position",
type=bool,
default=False
)
add_config(
parser,
load,
long_flag="--gps_xy_noise_range",
help="Intensity of gps noise (unit is lat and lng,) high values may cause issues (default=0.000125)",
type=float,
default=0.000125
)
add_config(
parser,
load,
long_flag="--gps_z_noise_range",
help="Intensity of gps noise (unit is in meter, default=12.5)",
type=float,
default=12.5
)
add_config(
parser,
load,
long_flag="--gps_default_altitude",
help="Initial altitude (default=8.0)",
type=float,
default=8.0
)
# Start to parse other attrs
config = parser.parse_args()
if not config.username and 'username' not in load:
config.username = raw_input("Username: ")
if not config.password and 'password' not in load:
config.password = getpass("Password: ")
config.encrypt_location = load.get('encrypt_location', '')
config.catch = load.get('catch', {})
config.release = load.get('release', {})
config.plugins = load.get('plugins', [])
config.raw_tasks = load.get('tasks', [])
config.daily_catch_limit = load.get('daily_catch_limit', 800)
config.vips = load.get('vips', {})
if config.map_object_cache_time < 0.0:
parser.error("--map_object_cache_time is out of range! (should be >= 0.0)")
return None
if len(config.raw_tasks) == 0:
logging.error("No tasks are configured. Did you mean to configure some behaviors? Read https://github.com/PokemonGoF/PokemonGo-Bot/wiki/Configuration-files#configuring-tasks for more information")
return None
if config.auth_service not in ['ptc', 'google']:
logging.error("Invalid Auth service specified! ('ptc' or 'google')")
return None
def task_configuration_error(flag_name):
parser.error("""
\"{}\" was removed from the configuration options.
You can now change the behavior of the bot by modifying the \"tasks\" key.
Read https://github.com/PokemonGoF/PokemonGo-Bot/wiki/Configuration-files#configuring-tasks for more information.
""".format(flag_name))
old_flags = ['mode', 'catch_pokemon', 'spin_forts', 'forts_spin', 'hatch_eggs', 'release_pokemon', 'softban_fix',
'longer_eggs_first', 'evolve_speed', 'use_lucky_egg', 'item_filter', 'evolve_all', 'evolve_cp_min',
'max_steps', 'catch_throw_parameters.excellent_rate', 'catch_throw_parameters.great_rate',
'catch_throw_parameters.nice_rate', 'catch_throw_parameters.normal_rate',
'catch_throw_parameters.spin_success_rate']
for flag in old_flags:
if flag in load:
task_configuration_error(flag)
return None
nested_old_flags = [('forts', 'spin'), ('forts', 'move_to_spin'), ('navigator', 'path_mode'), ('navigator', 'path_file'), ('navigator', 'type')]
for outer, inner in nested_old_flags:
if load.get(outer, {}).get(inner, None):
task_configuration_error('{}.{}'.format(outer, inner))
return None
if "evolve_captured" in load:
logger.warning('The evolve_captured argument is no longer supported. Please use the EvolvePokemon task instead')
if "walk" in load:
logger.warning('The walk argument is no longer supported. Please use the walk_max and walk_min variables instead')
if config.walk_min < 1:
parser.error("--walk_min is out of range! (should be >= 1.0)")
return None
if config.alt_min < 0:
parser.error("--alt_min is out of range! (should be >= 0.0)")
return None
if not (config.location or config.location_cache):
parser.error("Needs either --use-location-cache or --location.")
return None
plugin_loader = PluginLoader()
for plugin in config.plugins:
plugin_loader.load_plugin(plugin)
# create web dir if not exists
try:
os.makedirs(web_dir)
except OSError:
if not os.path.isdir(web_dir):
raise
fix_nested_config(config)
return config
def add_config(parser, json_config, short_flag=None, long_flag=None, **kwargs):
if not long_flag:
raise Exception('add_config calls requires long_flag parameter!')
full_attribute_path = long_flag.split('--')[1]
attribute_name = full_attribute_path.split('.')[-1]
if '.' in full_attribute_path: # embedded config!
embedded_in = full_attribute_path.split('.')[0: -1]
for level in embedded_in:
json_config = json_config.get(level, {})
if 'default' in kwargs:
kwargs['default'] = json_config.get(attribute_name, kwargs['default'])
if short_flag:
args = (short_flag, long_flag)
else:
args = (long_flag,)
parser.add_argument(*args, **kwargs)
def fix_nested_config(config):
config_dict = config.__dict__
for key, value in config_dict.iteritems():
if '.' in key:
new_key = key.replace('.', '_')
config_dict[new_key] = value
del config_dict[key]
def parse_unicode_str(string):
try:
return string.decode('utf8')
except UnicodeEncodeError:
return string
if __name__ == '__main__':
main()
|
# encoding: utf-8
import os
import torch
import torch.distributed as dist
from yolox.data import get_yolox_datadir
from yolox.exp import Exp as MyExp
class Exp(MyExp):
def __init__(self):
super(Exp, self).__init__()
self.num_classes = 40
self.depth = 0.33
self.width = 0.50
self.warmup_epochs = 1
# ---------------- dataloader config ---------------- #
# set worker to 4 for shorter dataloader init time
self.data_num_workers = 4
self.input_size = (576, 768) # (height, width) # W, H shape=(504, 378) (1008, 756) (756, 567) (768, 576)
# ---------- transform config ------------ #
self.mosaic_prob = 1.0
self.mixup_prob = 1.0
self.hsv_prob = 1.0
# self.flip_prob = 0.5
self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(".")[0]
# -------------- training config --------------------- #
self.warmup_epochs = 5
self.max_epoch = 300
self.warmup_lr = 0
self.basic_lr_per_img = 0.01 / 64.0
self.scheduler = "yoloxwarmcos"
self.no_aug_epochs = 15
self.min_lr_ratio = 0.05
self.ema = True
self.weight_decay = 5e-4
self.momentum = 0.9
self.print_interval = 10
self.eval_interval = 10
self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(".")[0]
# ----------------- testing config ------------------ #
self.test_size = (576, 768)
self.test_conf = 0.25
self.nmsthre = 0.3
def get_data_loader(self, batch_size, is_distributed, no_aug=False, cache_img=False):
from yolox.data import (
VOCDetection,
TrainTransform,
YoloBatchSampler,
DataLoader,
InfiniteSampler,
MosaicDetection,
worker_init_reset_seed,
)
from yolox.utils import (
wait_for_the_master,
get_local_rank,
)
local_rank = get_local_rank()
with wait_for_the_master(local_rank):
dataset = VOCDetection(
data_dir=os.path.join(get_yolox_datadir(), "VOCdevkit"),
image_sets=[('2022', 'train')],
img_size=self.input_size,
preproc=TrainTransform(
max_labels=50,
flip_prob=self.flip_prob,
hsv_prob=self.hsv_prob),
cache=cache_img,
)
dataset = MosaicDetection(
dataset,
mosaic=not no_aug,
img_size=self.input_size,
preproc=TrainTransform(
max_labels=120,
flip_prob=self.flip_prob,
hsv_prob=self.hsv_prob),
degrees=self.degrees,
translate=self.translate,
mosaic_scale=self.mosaic_scale,
mixup_scale=self.mixup_scale,
shear=self.shear,
enable_mixup=self.enable_mixup,
mosaic_prob=self.mosaic_prob,
mixup_prob=self.mixup_prob,
)
self.dataset = dataset
if is_distributed:
batch_size = batch_size // dist.get_world_size()
sampler = InfiniteSampler(
len(self.dataset), seed=self.seed if self.seed else 0
)
batch_sampler = YoloBatchSampler(
sampler=sampler,
batch_size=batch_size,
drop_last=False,
mosaic=not no_aug,
)
dataloader_kwargs = {"num_workers": self.data_num_workers, "pin_memory": True}
dataloader_kwargs["batch_sampler"] = batch_sampler
# Make sure each process has different random seed, especially for 'fork' method
dataloader_kwargs["worker_init_fn"] = worker_init_reset_seed
train_loader = DataLoader(self.dataset, **dataloader_kwargs)
return train_loader
def get_eval_loader(self, batch_size, is_distributed, testdev=False, legacy=False):
from yolox.data import VOCDetection, ValTransform
valdataset = VOCDetection(
data_dir=os.path.join(get_yolox_datadir(), "VOCdevkit"),
image_sets=[('2022', 'val')],
img_size=self.test_size,
preproc=ValTransform(legacy=legacy),
)
if is_distributed:
batch_size = batch_size // dist.get_world_size()
sampler = torch.utils.data.distributed.DistributedSampler(
valdataset, shuffle=False
)
else:
sampler = torch.utils.data.SequentialSampler(valdataset)
dataloader_kwargs = {
"num_workers": self.data_num_workers,
"pin_memory": True,
"sampler": sampler,
}
dataloader_kwargs["batch_size"] = batch_size
val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)
return val_loader
def get_evaluator(self, batch_size, is_distributed, testdev=False, legacy=False):
from yolox.evaluators import VOCEvaluator
val_loader = self.get_eval_loader(batch_size, is_distributed, testdev, legacy)
evaluator = VOCEvaluator(
dataloader=val_loader,
img_size=self.test_size,
confthre=self.test_conf,
nmsthre=self.nmsthre,
num_classes=self.num_classes,
)
return evaluator
|
import pyclesperanto_prototype as cle
import numpy as np
def test_variance_sphere():
test1 = cle.push(np.asarray([
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]))
reference = cle.push(np.asarray([
[0, 0, 0, 0, 0],
[0, 0, 0.16, 0, 0],
[0, 0.16, 0.16, 0.16, 0],
[0, 0, 0.16, 0, 0],
[0, 0, 0, 0, 0]
]))
result = cle.create(test1)
cle.variance_sphere(test1, result, 1, 1, 0)
a = cle.pull(result)
b = cle.pull(reference)
print(a)
assert (np.allclose(a, b, 0.01))
|
# coding=utf-8
# Copyright 2020 The Edward2 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for normalization layers."""
import edward2 as ed
import numpy as np
import tensorflow as tf
class NormalizationTest(tf.test.TestCase):
def testActNorm(self):
np.random.seed(83243)
batch_size = 25
length = 15
channels = 4
inputs = 3. + 0.8 * np.random.randn(batch_size, length, channels)
inputs = tf.cast(inputs, tf.float32)
layer = ed.layers.ActNorm()
outputs = layer(inputs)
mean, variance = tf.nn.moments(outputs, axes=[0, 1])
self.assertAllClose(mean, np.zeros(channels), atol=1e-3)
self.assertAllClose(variance, np.ones(channels), atol=1e-3)
inputs = 3. + 0.8 * np.random.randn(batch_size, length, channels)
inputs = tf.cast(inputs, tf.float32)
outputs = layer(inputs)
mean, variance = tf.nn.moments(outputs, axes=[0, 1])
self.assertAllClose(mean, np.zeros(channels), atol=0.25)
self.assertAllClose(variance, np.ones(channels), atol=0.25)
if __name__ == '__main__':
tf.test.main()
|
/*-
* Copyright (c) 2007-2012 Dominique Li <dominique.li@univ-tours.fr>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: counter.h 627 2020-08-15 14:44:04Z li $
*/
#ifndef _SDTL_COUNTER_H_
#define _SDTL_COUNTER_H_
#ifndef __sdtl_counter_class
#define __sdtl_counter_class
#endif
#include <map>
#include "types.h"
namespace sdtl {
/**
* Counter.
*/
template<class T_>
class counter {
public:
counter() = default;
counter(const counter<T_> &);
virtual ~counter();
inline typename std::map<T_, size_t>::iterator begin();
inline typename std::map<T_, size_t>::const_iterator begin() const;
void clear();
inline typename std::map<T_, size_t>::iterator end();
inline typename std::map<T_, size_t>::const_iterator end() const;
counter<T_> &filter(size_t);
size_t get(const T_ &);
size_t get(const T_ &) const;
size_t put(const T_ &);
inline size_t size() const;
inline size_t operator()(const T_ &);
inline counter<T_> &operator=(const counter<T_> &);
inline size_t operator[](const T_ &);
inline size_t operator[](const T_ &) const;
private:
void copy_(const counter<T_> &);
void free_();
std::map<T_, size_t> data_;
std::map<size_t, counter<T_> *> filters_;
};
/**
* Copy constructor.
*/
template<class T_>
counter<T_>::counter(const counter<T_> &c) {
copy_(c);
}
/**
* Destructor.
*/
template<class T_>
counter<T_>::~counter() {
free_();
}
/**
* For range based iteration: begin()
*/
template<class T_>
inline typename std::map<T_, size_t>::iterator counter<T_>::begin() {
return data_.begin();
};
/**
* For range based iteration: begin()
*/
template<class T_>
inline typename std::map<T_, size_t>::const_iterator counter<T_>::begin() const {
return data_.begin();
};
/**
* Clear content.
*/
template<class T_>
void counter<T_>::clear() {
free_();
data_.clear();
filters_.clear();
}
/**
* Range based iteration: end()
*/
template<class T_>
inline typename std::map<T_, size_t>::iterator counter<T_>::end() {
return data_.end();
};
/**
* Range based iteration: end()
*/
template<class T_>
inline typename std::map<T_, size_t>::const_iterator counter<T_>::end() const {
return data_.end();
};
/**
* Return a sub-counter for specified minimum count.
*/
template<class T_>
counter<T_> &counter<T_>::filter(size_t count) {
auto &&it = filters_.find(count);
if (it == filters_.end()) {
auto *c = new counter<T_>();
for (auto &e: data_) {
if (e.second >= count) {
c->data_[e.first] = e.second;
}
}
filters_[count] = c;
return *c;
} else {
return *it->second;
}
}
/**
* Get the count of an element.
*/
template<class T_>
size_t counter<T_>::get(const T_ &t) {
auto &&it = data_.find(t);
if (it == data_.end()) {
return 0;
} else {
return it->second;
}
}
/**
* Get the count of an element.
*/
template<class T_>
size_t counter<T_>::get(const T_ &t) const {
auto &&it = data_.find(t);
if (it == data_.end()) {
return 0;
} else {
return it->second;
}
}
/**
* Put an element to the counter.
*/
template<class T_>
size_t counter<T_>::put(const T_ &t) {
auto &&it = data_.find(t);
if (it == data_.end()) {
data_.emplace(t, 1);
return 1;
} else {
return ++it->second;
}
}
/**
* Return size.
*/
template<class T_>
inline size_t counter<T_>::size() const {
return data_.size();
}
/**
* Alias of put.
*/
template<class T_>
inline size_t counter<T_>::operator()(const T_ &t) {
return this->put(t);
}
/**
*
*/
template<class T_>
inline counter<T_> &counter<T_>::operator=(const counter<T_> &c) {
copy_(c);
return *this;
}
/**
* Alias of get.
*/
template<class T_>
inline size_t counter<T_>::operator[](const T_ &t) {
return this->get(t);
}
/**
* Alias of get.
*/
template<class T_>
inline size_t counter<T_>::operator[](const T_ &t) const {
return this->get(t);
}
/**
*
*/
template<class T_>
void counter<T_>::copy_(const counter<T_> &c) {
if (this != &c) {
clear();
data_ = c.data_;
for (auto &sc: c.filters_) {
filters_[sc.first] = new counter<T_>(*sc.second);
}
}
}
/**
* Free allocated memory.
*/
template<class T_>
void counter<T_>::free_() {
for (auto &f: filters_) {
delete f.second;
}
}
}
#endif /* _SDTL_COUNTER_H_ */
|
#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This is used to validate that the library is correct.
This checks:
* All files in lib/ appear when compiling +@complete
* Runs a compiler pass over the test code to check for type errors
* Run the linter to check for style violations.
"""
import argparse
import logging
import os
import re
import build
import compiler
import shakaBuildHelpers
def complete_build_files():
"""Returns a complete set of build files."""
complete = build.Build()
# Normally we don't need to include @core, but because we look at the build
# object directly, we need to include it here. When using main(), it will
# call addCore which will ensure core is included.
if not complete.parse_build(['+@complete', '+@core'], os.getcwd()):
logging.error('Error parsing complete build')
return False
return complete.include
def get_lint_files():
"""Returns the absolute paths to all the files to run the linter over."""
match = re.compile(r'.*\.js$')
base = shakaBuildHelpers.get_source_base()
def get(*path_components):
return shakaBuildHelpers.get_all_files(
os.path.join(base, *path_components), match)
return get('test') + get('lib') + get('externs') + get('demo') + get('ui')
def check_js_lint(args):
"""Runs the JavaScript linter."""
# TODO: things not enforced: property doc requirements
logging.info('Linting JavaScript...')
base = shakaBuildHelpers.get_source_base()
config_path = os.path.join(base, '.eslintrc.js')
linter = compiler.Linter(get_lint_files(), config_path)
return linter.lint(fix=args.fix, force=args.force)
def check_css_lint(args):
"""Runs the CSS linter."""
logging.info('Linting CSS...')
match = re.compile(r'.*\.(less|css)$')
base = shakaBuildHelpers.get_source_base()
def get(*path_components):
return shakaBuildHelpers.get_all_files(
os.path.join(base, *path_components), match)
files = (get('ui') + get('demo'));
config_path = os.path.join(base, '.csslintrc')
linter = compiler.CssLinter(files, config_path)
return linter.lint(fix=args.fix, force=args.force)
def check_html_lint(args):
"""Runs the HTML linter."""
logging.info('Linting HTML...')
base = shakaBuildHelpers.get_source_base()
files = ['index.html', os.path.join('demo', 'index.html'), 'support.html']
file_paths = [os.path.join(base, x) for x in files]
config_path = os.path.join(base, '.htmlhintrc')
htmllinter = compiler.HtmlLinter(file_paths, config_path)
return htmllinter.lint(force=args.force)
def check_complete(_):
"""Checks whether the 'complete' build references every file.
This is used by the build script to ensure that every file is included in at
least one build type.
Returns:
True on success, False on failure.
"""
logging.info('Checking that the build files are complete...')
complete_build = complete_build_files()
if not complete_build:
return False
match = re.compile(r'.*\.js$')
base = shakaBuildHelpers.get_source_base()
all_files = set()
all_files.update(shakaBuildHelpers.get_all_files(
os.path.join(base, 'lib'), match))
all_files.update(shakaBuildHelpers.get_all_files(
os.path.join(base, 'ui'), match))
missing_files = all_files - complete_build
if missing_files:
logging.error('There are files missing from the complete build:')
for missing in missing_files:
# Convert to a path relative to source base.
logging.error(' ' + os.path.relpath(missing, base))
return False
return True
def check_tests(args):
"""Runs an extra compile pass over the test code to check for type errors.
Returns:
True on success, False on failure.
"""
logging.info('Checking the tests for type errors...')
complete_build = complete_build_files()
if not complete_build:
return False
match = re.compile(r'.*\.js$')
base = shakaBuildHelpers.get_source_base()
def get(*path_components):
return shakaBuildHelpers.get_all_files(
os.path.join(base, *path_components), match)
files = complete_build
files.update(set(get('externs') + get('test') +
get('third_party', 'closure')))
files.add(os.path.join(base, 'demo', 'common', 'asset.js'))
files.add(os.path.join(base, 'demo', 'common', 'assets.js'))
localizations = compiler.GenerateLocalizations(None)
localizations.generate(args.force)
files.add(localizations.output)
closure_opts = build.common_closure_opts + build.common_closure_defines
closure_opts += build.debug_closure_opts + build.debug_closure_defines
# Ignore missing goog.require since we assume the whole library is
# already included.
closure_opts += [
'--jscomp_off=missingRequire', '--jscomp_off=strictMissingRequire',
'--checks-only', '-O', 'SIMPLE'
]
# Set up a build with the build name of "dummy". With output_compiled_bundle
# set to False, the build name is irrelevant, since we won't generate any
# compiled output.
closure = compiler.ClosureCompiler(files, 'dummy')
closure.output_compiled_bundle = False
# Instead of creating a compiled bundle, we will touch a timestamp file to
# keep track of how recently we've run this check.
closure.timestamp_file = os.path.join(base, 'dist', '.testcheckstamp')
return closure.compile(closure_opts, args.force)
def main(args):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'--fix',
help='Automatically fix style violations.',
action='store_true')
parser.add_argument(
'--force',
'-f',
help='Force checks even if no files have changed.',
action='store_true')
parsed_args = parser.parse_args(args)
# Make the dist/ folder, ignore errors.
base = shakaBuildHelpers.get_source_base()
try:
os.mkdir(os.path.join(base, 'dist'))
except OSError:
pass
# Update node modules if needed.
if not shakaBuildHelpers.update_node_modules():
return 1
steps = [
check_js_lint,
check_html_lint,
check_css_lint,
check_complete,
check_tests,
]
for step in steps:
if not step(parsed_args):
return 1
return 0
if __name__ == '__main__':
shakaBuildHelpers.run_main(main)
|
// MODULES //
import React, { Component, Fragment } from 'react';
import ReactDraggable from 'react-draggable';
import ProgressBar from 'react-bootstrap/ProgressBar';
import Button from 'react-bootstrap/Button';
// MAIN //
class ScoreSetter extends Component {
constructor( props ) {
super( props );
this.state = {
progress: 50,
controlledPosition: {
x: 0, y: 0
}
};
}
onControlledDrag = ( e, position ) => {
const { x, y } = position;
this.setState({
controlledPosition: { x, y }
});
}
onControlledDragStop = ( e, position ) => {
const { x, y } = position;
this.setState({
controlledPosition: { x, y },
progress: ( ( x + 100 ) / 200 ) * 100
});
}
handleSubmit = () => {
this.props.onSubmit( this.state.progress );
}
render() {
return (
<Fragment>
<div className="score-bottom" >
<ReactDraggable
bounds={{ left: -100, right: 100, top: 0, bottom: 0 }}
onStop={this.onControlledDragStop}
position={this.state.controlledPosition}
onDrag={this.onControlledDrag}
>
<div className="score-setter" />
</ReactDraggable>
<ProgressBar style={{ marginTop: 23 }}>
<ProgressBar animated variant="success" now={this.state.progress} />
<ProgressBar animated variant="danger" now={100-this.state.progress} />
</ProgressBar>
</div>
<Button
variant="secondary" size="sm"
onClick={this.handleSubmit} style={{ marginTop: 10 }}
>
{this.props.t( 'submit' )}
</Button>
</Fragment>
);
}
}
// EXPORTS //
export default ScoreSetter;
|
/*++
Copyright (c) 1995 Microsoft Corporation
Module Name:
floatfns.h
Abstract:
Prototypes for floating point instructions.
Author:
20-Jun-1995 t-orig
Revision History:
--*/
DISPATCH(FLOAT_GP0);
DISPATCH(FLOAT_GP1);
DISPATCH(FLOAT_GP2);
DISPATCH(FLOAT_GP3);
DISPATCH(FLOAT_GP4);
DISPATCH(FLOAT_GP5);
DISPATCH(FLOAT_GP6);
DISPATCH(FLOAT_GP7);
|
import React from 'react';
import PwChangeForm from '../../components/Forms/PwChangeForm';
import * as GS from '../../components/GlobalStyle';
import HeadTitle from '../../components/HeadTitle';
import { withAuthentication } from '../../higher-order-component/with-authentication';
const PwChangePage = () => {
return (
<GS.FlexRowCenterWrap>
<HeadTitle title="비밀번호 변경" />
<GS.SmallColumnBoard>
<PwChangeForm />
</GS.SmallColumnBoard>
</GS.FlexRowCenterWrap>
);
};
export default withAuthentication(PwChangePage);
|
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import torch
from torch.autograd import Variable, grad
from torch.nn.init import xavier_normal
from torchvision import datasets, transforms
import torchvision.utils as vutils
# added[
class GeneratorDRAGAN(torch.nn.Module):
def __init__(self, input_size, output_size, hidden_dim, num_gpu):
super(GeneratorDRAGAN, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = input_size
self.layers.append(torch.nn.Linear(prev_dim, hidden_dim))
self.layers.append(torch.nn.Sigmoid())
self.layers.append(torch.nn.Linear(hidden_dim, output_size))
self.layers.append(torch.nn.Sigmoid())
self.layer_module = torch.nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
class DiscriminatorGRAGAN(torch.nn.Module):
def __init__(self, input_size, output_size, hidden_dim, num_gpu):
super(DiscriminatorGRAGAN, self).__init__()
self.num_gpu = num_gpu
self.layers = []
prev_dim = input_size
self.layers.append(torch.nn.Linear(output_size, hidden_dim))
self.layers.append(torch.nn.Sigmoid())
self.layers.append(torch.nn.Linear(hidden_dim, 1))
self.layers.append(torch.nn.Sigmoid())
self.layer_module = torch.nn.ModuleList(self.layers)
def main(self, x):
out = x
for layer in self.layer_module:
out = layer(out)
return out
def forward(self, x):
return self.main(x)
# added]
def xavier_init(model):
for param in model.parameters():
if len(param.size()) == 2:
xavier_normal(param)
dtype = torch.cuda.FloatTensor #run on GPU
if __name__ == '__main__':
batch_size = 128
z_dim = 100
h_dim = 128
y_dim = 784
max_epochs = 1000
lambda_ = 10
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor()
])),
batch_size=batch_size, shuffle=True, drop_last=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor()
])),
batch_size=batch_size, shuffle=False, drop_last=True)
generator = torch.nn.Sequential(torch.nn.Linear(z_dim, h_dim),
torch.nn.Sigmoid(),
torch.nn.Linear(h_dim, y_dim),
torch.nn.Sigmoid()).cuda()
discriminator = torch.nn.Sequential(torch.nn.Linear(y_dim, h_dim),
torch.nn.Sigmoid(),
torch.nn.Linear(h_dim, 1),
torch.nn.Sigmoid()).cuda()
# Init weight matrices (xavier_normal)
xavier_init(generator)
xavier_init(discriminator)
opt_g = torch.optim.Adam(generator.parameters())
opt_d = torch.optim.Adam(discriminator.parameters())
criterion = torch.nn.BCELoss()
X = Variable(torch.cuda.FloatTensor(batch_size, y_dim))
z = Variable(torch.cuda.FloatTensor(batch_size, z_dim))
labels = Variable(torch.cuda.FloatTensor(batch_size))
# Train
for epoch in range(max_epochs):
for batch_idx, (data, target) in enumerate(train_loader):
X.data.copy_(data)
# Update discriminator
# train with real
discriminator.zero_grad()
pred_real = discriminator(X)
labels.data.fill_(1.0)
loss_d_real = criterion(pred_real, labels)
loss_d_real.backward()
# train with fake
z.data.normal_(0, 1)
fake = generator.forward(z).detach()
pred_fake = discriminator(fake)
labels.data.fill_(0.0)
loss_d_fake = criterion(pred_fake, labels)
loss_d_fake.backward()
# gradient penalty
alpha = torch.rand(batch_size, 1).type(dtype).expand(X.size())
x_hat = Variable(alpha * X.data + (1 - alpha) * (X.data + 0.5 * X.data.std() * torch.rand(X.size()).type(dtype)), requires_grad=True)
pred_hat = discriminator(x_hat)
gradients = grad(outputs=pred_hat, inputs=x_hat, grad_outputs=torch.ones(pred_hat.size()).type(dtype),
create_graph=True, retain_graph=True, only_inputs=True)[0]
gradient_penalty = lambda_ * ((gradients.norm(2, dim=1) - 1) ** 2).mean()
gradient_penalty.backward()
loss_d = loss_d_real + loss_d_fake + gradient_penalty
opt_d.step()
# Update generator
generator.zero_grad()
z.data.normal_(0, 1)
gen = generator(z)
pred_gen = discriminator(gen)
labels.data.fill_(1.0)
loss_g = criterion(pred_gen, labels)
loss_g.backward()
opt_g.step()
print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f'
% (epoch, max_epochs, batch_idx, len(train_loader),
loss_d.data[0], loss_g.data[0]))
if batch_idx % 100 == 0:
vutils.save_image(data,
'samples/real_samples.png')
fake = generator(z)
vutils.save_image(gen.data.view(batch_size, 1, 28, 28),
'samples/fake_samples_epoch_%03d.png' % epoch)
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 48);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return normalizeComponent; });
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () { injectStyles.call(this, this.$root.$options.shadowRoot) }
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 1:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _broadcast(componentName, eventName, params) {
this.$children.forEach(function (child) {
var name = child.$options.componentName;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
_broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
var _default = {
methods: {
// 要触发那个父节点上面的那个事件
dispatch: function dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
},
broadcast: function broadcast(componentName, eventName, params) {
_broadcast(this, componentName, eventName, params);
}
}
};
exports.default = _default;
/***/ }),
/***/ 18:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ 19:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _emitter = _interopRequireDefault(__webpack_require__(1));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//
//
//
//
//
//
//
//
//
//
var keyCode = Object.freeze({
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
});
var _default = {
name: 'PaRadioGroup',
componentName: 'PaRadioGroup',
inject: {
elFormItem: {
default: ''
}
},
mixins: [_emitter.default],
props: {
value: {},
size: String,
fill: String,
textColor: String,
disabled: Boolean
},
computed: {
_elFormItemSize: function _elFormItemSize() {
return (this.elFormItem || {}).elFormItemSize;
},
_elTag: function _elTag() {
return (this.$vnode.data || {}).tag || 'div';
},
radioGroupSize: function radioGroupSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
}
},
watch: {
value: function value(_value) {
this.dispatch('PaFormItem', 'Pa.form.change', [this.value]);
}
},
created: function created() {
var _this = this;
this.$on('handleChange', function (value) {
_this.$emit('change', value);
});
},
mounted: function mounted() {
var _this2 = this;
this.$nextTick(function () {
console.log(_this2.names);
}); // 当radioGroup没有默认选项时,第一个可以选中Tab导航
var radios = this.$el.querySelectorAll('[type=radio]');
var firstLabel = this.$el.querySelectorAll('[role=radio]')[0];
console.log(firstLabel);
if (![].some.call(radios, function (radio) {
return radio.checked;
}) && firstLabel) {
firstLabel.tabIndex = 0;
}
}
};
exports.default = _default;
/***/ }),
/***/ 30:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// CONCATENATED MODULE: ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./packages/radio/src/radio-group.vue?vue&type=template&id=818a704c&
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
_vm._elTag,
{
tag: "component",
staticClass: "pa-radio-group",
attrs: { role: "radiogroup" }
},
[_vm._t("default")],
2
)
}
var staticRenderFns = []
render._withStripped = true
// CONCATENATED MODULE: ./packages/radio/src/radio-group.vue?vue&type=template&id=818a704c&
/* concated harmony reexport render */__webpack_require__.d(__webpack_exports__, "a", function() { return render; });
/* concated harmony reexport staticRenderFns */__webpack_require__.d(__webpack_exports__, "b", function() { return staticRenderFns; });
/***/ }),
/***/ 48:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _radioGroup = _interopRequireDefault(__webpack_require__(49));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_radioGroup.default.install = function (Vue) {
Vue.component(_radioGroup.default.name, _radioGroup.default);
};
var _default = _radioGroup.default;
exports.default = _default;
/***/ }),
/***/ 49:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _radio_group_vue_vue_type_template_id_818a704c___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(30);
/* harmony import */ var _radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0);
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(
_radio_group_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_radio_group_vue_vue_type_template_id_818a704c___WEBPACK_IMPORTED_MODULE_0__[/* render */ "a"],
_radio_group_vue_vue_type_template_id_818a704c___WEBPACK_IMPORTED_MODULE_0__[/* staticRenderFns */ "b"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "packages/radio/src/radio-group.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ })
/******/ });
|
# encoding: utf-8
# -*- coding: utf-8 -*-
"""==================================================================
Copyright(c) 2016-2017 Hangzhou Hikvision Digital Technology Co.,Ltd
文件名称: Base.py
简要描述: 通讯基础模块,提供通信类的创建、测试类的封装
编写测试用例时需要导入Base模块
作 者: Qiu Jiangping
完成日期: 2017-5-11
修订说明:
=================================================================="""
import ctypes
import time, traceback
from .logger import LogRecord
from .utils import *
# from PostgreSqlInterface import *
g_logRecord = LogRecord()
# 通信类
class Connect:
"""============================================================================================
函数名称: __init__
功能描述: 初始化, 加载lib目录下的dll文件
参数列表: 无
返回结果: 无
==============================================================================================="""
def __init__(self):
lib_dir = g_rootPath + "\\Lib"
os.chdir(lib_dir)
self.dll = ctypes.CDLL("ISAPITest.dll")
os.chdir(g_rootPath)
self.dll.Init()
self.login_id = 0
# 统计每条协议耗时
self.elapsed = 0
"""============================================================================================
函数名称: __del__
功能描述: 反初始化
参数列表: 无
返回结果: 无
==============================================================================================="""
def __del__(self):
pass # self.dll.Uninit()
"""============================================================================================
函数名称: login
功能描述: 登陆VSM服务器
参数列表: ip——服务器ip地址
port——服务器端口
user——用户名
pwd——用户密码
clientType—客户端类型, 0: WebClient, 1: PCClient, 2: MobileClient
httpType-http类型, 0: http, 1:https, 默认为http
返回结果: 返回登陆句柄, -1为无效值, 其他正直有效
==============================================================================================="""
def login(self, ip, port, user, pwd, clientType=0, httpType=0):
self.login_id = self.dll.Login(ip, port, user, pwd, clientType, 'http' if httpType == 0 else 'https')
if (self.login_id != -1):
error_info = '=============== [Login Success] ===============\r'
print(error_info)
g_logRecord.log_info(error_info)
else:
error_info = '=============== [Login Fail] ip: %s, port: %s, username: %s, pwd: %s, client type: %s ===============\r' % (
ip, str(port), user, pwd, str(clientType))
# g_logRecord.log_error(error_info)
print(error_info)
return self.login_id
"""============================================================================================
函数名称: logout
功能描述: 登出系统接口
参数列表: 无
返回结果: 无
==============================================================================================="""
def logout(self): # 退出登录
self.dll.LogOut(self.login_id)
# 记录日志
# g_logRecord.log_info('=============== [Logout] ===============\r')
print('=============== [Logout] ===============\r')
"""============================================================================================
函数名称: 通过login_id获取SessionID
功能描述: 获取SID
返回结果: SID
==============================================================================================="""
def getSessionID(self):
sid = self.dll.GetSessionID(self.login_id)
return self.dll.GetSessionID(self.login_id)
"""============================================================================================
函数名称: Encrypt
功能描述: AES加密方式(用于增加设备时输入密码加密)
参数列表: pwd——需要加密的密码
loginPwd——系统登录密码
返回结果: 返回加密后的密码
==============================================================================================="""
def Encrypt(self, pwd, loginPwd="Abc12345"):
self.PW = self.dll.AESEncrypt(self.login_id, pwd, loginPwd)
self.PW = ctypes.string_at(self.PW, -1)
return self.PW
"""============================================================================================
函数名称: RSA_Encrypt
功能描述: RSA加密方式
参数列表: pwd——需要加密的密码
返回结果: 返回加密后的密码
==============================================================================================="""
def RSA_Encrypt(self, pwd="Abc12345"):
self.RSA_PW = self.dll.RSAEncrypt(self.login_id, pwd)
self.RSA_PW = ctypes.string_at(self.RSA_PW, -1)
return self.RSA_PW
"""============================================================================================
函数名称: cmd
功能描述: 系统交互命令接口
参数列表: url——请求url路径;
method——请求方法:get、post、put、delete
query_param——请求Query;
need_sid——是否需要SID(session id), 1:需要 0:不需要
content——请求内容;
send_overtime——发送超时时间, 默认30s;
recv_overtime——接收超时时间, 默认30s;
返回结果: 期望Response数据
==============================================================================================="""
def cmd(self, url, method, query_param, need_sid, content, send_overtime=30000, recv_overtime=30000):
# 计时
self.elapsed = 0
start_time = time.time()
try:
ret = self.dll.SendEx(self.login_id, method, url, content, query_param, need_sid,
"application/xml; charset=\"UTF-8\"", send_overtime, recv_overtime)
self.elapsed = self.get_format_elapse(float('{0:.3} '.format((time.time() - start_time))))
# ret = self.dll.Send(self.login_id, method, url, content, query_param)
ret = ctypes.string_at(ret, -1).decode('utf-8')
except:
traceback.print_exc()
g_logRecord.writeText2Log(
'Except: dll.SendEx(\rlogin_id: %s\rmethod: %s\rurl: %s\rcontent: %s\rquery_param: %s\rneed_sid: %s\rsend_time_out:%s\rRecv_time_out:%s)'
% (str(self.login_id), method, url, content, query_param, str(need_sid), str(send_overtime),
str(recv_overtime)), 2)
return ret
def get_format_elapse(self, elapse):
integer = int(elapse)
decimal = elapse - integer
h = integer / 3600
sUp_h = integer - 3600 * h
m = sUp_h / 60
s = sUp_h - 60 * m
time_list = map(lambda x: "0%d" % x if 0 <= x < 10 else str(x), [h, m, s])
ms = '%.2f' % decimal
ms = ms[1:]
return ":".join(time_list) + ms
# 测试类
class TestGroup:
"""============================================================================================
函数名称: __init__
功能描述: 初始化
参数列表: serverType——登录服务器类型;
返回结果: 无
==============================================================================================="""
def __init__(self, serverType='VSM_Server'):
# 获取登录对应服务器的参数
# (self.ip, self.port, self.username, self.loginPw, self.clientType) = g_login_params_dict[serverType]
self.ip = "10.18.69.222"
self.port = 80
self.username = "admin"
self.loginPw = "Abc12345"
self.clientType = 0
# 定义通讯对象
self.conn = Connect()
# 定义测试结果
(self.bResult, self.failReason_list) = (True, [])
"""============================================================================================
函数名称: __del__
功能描述: 反初始化
参数列表: 无
返回结果: 无
==============================================================================================="""
def __del__(self):
pass
"""============================================================================================
函数名称: loginVsm
功能描述: 登录VSM服务器
参数列表: 无
返回结果: 无
==============================================================================================="""
def loginVsm(self):
return self.conn.login(self.ip, self.port, self.username, self.loginPw, self.clientType)
"""============================================================================================
函数名称: logoutVsm
功能描述: 登出VSM服务器
参数列表: 无
返回结果: 无
==============================================================================================="""
def logoutVsm(self):
return self.conn.logout()
"""============================================================================================
函数名称: getSessionID
功能描述: 获取sessionID
参数列表: 无
返回结果: 无
==============================================================================================="""
def getSessionID(self):
return self.conn.getSessionID()
"""============================================================================================
函数名称: initTestResult
功能描述: 初始化测试结果详情
参数列表: 无
返回结果: 无
==============================================================================================="""
def initTestResult(self):
(self.bResult, self.failReason_list) = (True, [])
"""============================================================================================
函数名称: getTestResult
功能描述: 获取测试结果详情
参数列表: 无
返回结果: 无
==============================================================================================="""
def getTestResult(self):
return (self.bResult, ''.join(self.failReason_list))
"""============================================================================================
函数名称: recordTestResult
功能描述: 记录错误详情
参数列表: bRet——Response比较结果;strMsg——Response比较结果详情
返回结果: 无
==============================================================================================="""
def recordTestResult(self, bRet, strMsg):
if bRet == False:
self.bResult = False
self.failReason_list.append(strMsg)
else:
pass
return bRet
"""============================================================================================
函数名称: getProtocalInfo
功能描述: 获取测试结果详情
参数列表: url——请求url路径;
method——请求方法:get、post、put、delete;
query_param——请求Query;
need_sid——是否需要SID(session id), 1:需要 0:不需要;
reqXmlFilename——请求xml模板文件名;
respXmlFilename——期望Response的xml模板文件名;
返回结果: 当前接口的ISAPI信息, 如/ISAPI/Bumblebee/Device/Encoders,POST,SID,MT=GET,EncodersRequest_GET.xml
==============================================================================================="""
def getProtocalInfo(self, url, method, query_param, need_sid, reqXmlFilename, respXmlFilename=''):
if need_sid == 1:
if query_param == '':
query_param = 'SID'
else:
query_param = '(SID,%s)' % (query_param)
else:
pass
# 组装protocal
req_xml_filename = reqXmlFilename + '.xml' if reqXmlFilename else ''
resp_xml_filename = respXmlFilename + '.xml' if respXmlFilename else ''
protocalInfo = ','.join([url, method, query_param])
return protocalInfo + ',' + req_xml_filename + ',' + resp_xml_filename + ',' + self.conn.elapsed
"""============================================================================================
函数名称: convertDataList
功能描述: 数据列表转换,将data_list中不确定的数据根据字典pendData_dict转换
参数列表: data_list——请求xml模板所需字段的数据列表,默认为空;
pendData_dict——数据列表中不确定数据的字典,如{$EncoderID:1, $CameraID: 5},默认为空;
xmlType——转换模板的类型,默认为Request
返回结果: data_list,替换后的数据结果列表
==============================================================================================="""
def convertDataList(self, data_list=[], pendData_dict={}, xmlType="Request"):
if len(pendData_dict) > 0:
if xmlType == "Request":
for data in pendData_dict:
if '$PW' in data: # 测试数据列表包含需要进行AES加密的字段,$PW
value = pendData_dict[data]
pendData_dict[data] = self.conn.Encrypt(value, self.loginPw)
elif '$RSA_PW' in data: # 测试数据列表包含需要进行RSA加密的字段, $RSA_PW
value = pendData_dict[data]
pendData_dict[data] = self.conn.RSA_Encrypt(value)
else:
pass
data_list = DataProcess().convert_params_list(data_list, pendData_dict)
else:
data_list = DataProcess().convert_params_list(data_list, pendData_dict)
else:
pass
return data_list
"""============================================================================================
函数名称: packageData
功能描述: 组装xml模板与数据
参数列表:xmlFilename——请求xml模板文件名,默认为空;
data_list——请求xml模板所需字段的数据列表,默认为空;
xmlType——xml模板类型,默认为Request
返回结果: 模板与数据组装后的字符串
==============================================================================================="""
def packageData(self, xmlFilename='', data_list=[], xmlType="Request"):
# 组装xml
if xmlFilename == '':
packXml = ""
else:
# 根据请求xml路径,构造xml组装对象
xmlp = XmlPacker(xmlFilename + '.xml', xmlType)
# 组装请求xml模板与数据
packXml = xmlp.get(data_list)
return packXml
"""============================================================================================
函数名称: sendRequest
功能描述: 发送请求
参数列表: index——相同协议发送序号;
url——请求url路径;
method——请求方法:get、post、put、delete;
query_param——请求Query;
need_sid——是否需要SID(session id), 1:需要 0:不需要;
reqXmlFilename——请求xml模板文件名;
reqData_list——请求xml模板所需字段的数据列表,默认为空;
reqPendData_dict——数据列表中不确定数据的字典,如{$EncoderID:1, $CameraID: 5},默认为空;
respData_dict——自定义需要比较的期望值字典, 如{xpath: [期望值]},默认为空不比较指定字段;
respPendData_dict——期望值列表中不确定的数据的字典, 如{$EncoderID:1, $CameraID: 5}
send_overtime——超时时间, 默认30s;
recv_overtime——接收超时时间, 默认30s;
返回结果: 比较结果
==============================================================================================="""
def sendRequest(self, index, url, method, query_param, need_sid=1,
reqXmlFilename='', reqData_list=[], reqPendData_dict={},
respData_dict={}, respPendData_dict={}, send_overtime=30000, recv_overtime=30000):
# 请求数据转换
reqData_list = self.convertDataList(reqData_list, reqPendData_dict)
# 组装发送请求数据
reqXml = self.packageData(reqXmlFilename, reqData_list)
# 发送请求接收响应
actualRespXml = self.conn.cmd(url, method, query_param, need_sid, reqXml, send_overtime, recv_overtime)
# 校验并返回测试结果
self.respXmlParse = XmlParser(actualRespXml)
protocolInfo = self.getProtocalInfo(url, method, query_param, need_sid, reqXmlFilename)
return self.recordTestResult(*(
XmlVerify().responseCompare(protocolInfo, reqXml, actualRespXml, respData_dict, respPendData_dict, index)))
"""============================================================================================
函数名称: sendRequest2
功能描述: 发送请求
参数列表: index——相同协议发送序号;
url——请求url路径;
method——请求方法:get、post、put、delete;
query_param——请求Query;
need_sid——是否需要SID(session id), 1:需要 0:不需要;
reqXmlFilename——请求xml模板文件名;
reqData_list——请求xml模板所需字段的数据列表,默认为空;
reqPendData_dict——数据列表中不确定数据的字典,如{$EncoderID:1, $CameraID: 5},默认为空;
expRespXmlFilename——期望响应xml模板文件名,默认为空;
expRespData_list——期望响应xml模板所需字段的数据列表,默认为空;
respPendData_dict——期望值列表中不确定的数据的字典, 如{$EncoderID:1, $CameraID: 5}
send_overtime——超时时间, 默认30s;
recv_overtime——接收超时时间, 默认30s;
返回结果: 比较结果
==============================================================================================="""
def sendRequest2(self, index, url, method, query_param, need_sid=1,
reqXmlFilename='', reqData_list=[], reqPendData_dict={},
expRespXmlFilename='', expRespData_list=[], respPendData_dict={}, send_overtime=30000,
recv_overtime=30000):
# 请求数据转换
reqData_list = self.convertDataList(reqData_list, reqPendData_dict)
# 组装发送请求数据
reqXml = self.packageData(reqXmlFilename, reqData_list)
# 发送请求接收响应
actualRespXml = self.conn.cmd(url, method, query_param, need_sid, reqXml, send_overtime, recv_overtime)
# 期望数据转换
expRespData_list = self.convertDataList(expRespData_list, respPendData_dict, 'Response')
# 组装期望响应数据
expRespXml = self.packageData(expRespXmlFilename, expRespData_list, 'Response')
# 校验并返回测试结果
self.respXmlParse = XmlParser(actualRespXml)
protocolInfo = self.getProtocalInfo(url, method, query_param, need_sid, reqXmlFilename, expRespXmlFilename)
return self.recordTestResult(
*(XmlVerify().responseCompare2(protocolInfo, reqXml, expRespXml, actualRespXml, index)))
"""============================================================================================
函数名称: sendRequest_ParamsList
功能描述: 根据参数列表,发送请求
参数列表: params_list——接口参数列表;
返回结果: 比较结果
==============================================================================================="""
def sendRequest_ParamsList(self, params_list):
(index, url, method, query_param, need_sid, reqXmlFilename, reqData_list, reqPendData_dict, respData_dict,
respPendData_dict) = params_list
self.sendRequest(index, url, method, query_param, need_sid, reqXmlFilename, reqData_list, reqPendData_dict,
respData_dict, respPendData_dict)
"""============================================================================================
函数名称: getSpecifiedData
功能描述: 发送GET请求, 获取指定xpath下指定字段为指定值节点下的, 要查找字段的数值
参数列表: query_params_list——GET请求数据列表;xpath——xpath路径;findTagName——需要查找的标签名;
tagName——指定的标签名;value——tagName的值
返回结果: 数据(字符串)
==============================================================================================="""
def getSpecifiedData(self, query_params_list, xpath, findTagName, tagName, value):
# 先刷新
self.sendRequest_ParamsList(query_params_list)
# 再获取数据
return self.respXmlParse.get_value_by_specified_tagName(xpath, findTagName, tagName, value)
"""============================================================================================
函数名称: getSpecifiedDataList
功能描述: 发送GET请求, 获取指定xpath下指定标签下的所有数据
参数列表: query_params_list——GET请求数据列表;xpath——xpath路径;findTagName——需要查找的标签名
返回结果: 数据列表
==============================================================================================="""
def getSpecifiedDataList(self, query_params_list, xpath, findTagName):
# 先刷新
self.sendRequest_ParamsList(query_params_list)
# 再获取数据列表
return self.respXmlParse.get_value_list_by_specified_tagName(xpath, findTagName)
"""============================================================================================
函数名称: getSpecifiedDataList1(新增,包含getSpecifiedDataList方法的功能)
功能描述: 发送GET请求, 获取指定xpath下指定标签下的所有数据
参数列表: query_params_list——GET请求数据列表;xpath——xpath路径;findTagName——需要查找的标签名
tagName——指定的标签;value——tagName的值(指定标签为空,则查找xpath节点下的标签为findTagName的所有值)
返回结果: 数据列表
==============================================================================================="""
def getSpecifiedDataList1(self, query_params_list, xpath, findTagName, tagName='', value=''):
# 先刷新
self.sendRequest_ParamsList(query_params_list)
# 再获取数据列表
return self.respXmlParse.get_dataList_by_specified_tagName(xpath, findTagName, tagName, value)
"""============================================================================================
函数名称: getSpecifiedDataList2
功能描述: 发送GET请求, 获取指定xpath下指定标签下的所有数据
参数列表: query_params_list——GET请求数据列表;xpath——xpath路径;tagName——指定的标签;value——tagName的值
findXpath——定位指定xpath的节点路径; findTagName——需要查找的标签名
返回结果: 数据列表
==============================================================================================="""
def getSpecifiedDataList2(self, query_params_list, xpath, tagName, value, findXpath, findTagName):
# 先刷新
self.sendRequest_ParamsList(query_params_list)
# 再获取数据列表
return self.respXmlParse.get_value_list_by_specified_xpath(xpath, tagName, value, findXpath, findTagName)
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <chregu@php.net> |
| Rob Richards <rrichards@php.net> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_LIBXML && HAVE_DOM
#include "php_dom.h"
#include "nodelist_arginfo.h"
/*
* class DOMNodeList
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-536297177
* Since:
*/
const zend_function_entry php_dom_nodelist_class_functions[] = {
PHP_ME(domnodelist, item, arginfo_class_DOMNodeList_item, ZEND_ACC_PUBLIC)
PHP_ME(domnodelist, count, arginfo_class_DOMNodeList_count, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* {{{ length int
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-203510337
Since:
*/
int dom_nodelist_length_read(dom_object *obj, zval *retval)
{
dom_nnodemap_object *objmap;
xmlNodePtr nodep, curnode;
int count = 0;
HashTable *nodeht;
objmap = (dom_nnodemap_object *)obj->ptr;
if (objmap != NULL) {
if (objmap->ht) {
count = xmlHashSize(objmap->ht);
} else {
if (objmap->nodetype == DOM_NODESET) {
nodeht = HASH_OF(&objmap->baseobj_zv);
count = zend_hash_num_elements(nodeht);
} else {
nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
if (objmap->nodetype == XML_ATTRIBUTE_NODE || objmap->nodetype == XML_ELEMENT_NODE) {
curnode = nodep->children;
if (curnode) {
count++;
while (curnode->next != NULL) {
count++;
curnode = curnode->next;
}
}
} else {
if (nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDoc *) nodep);
} else {
nodep = nodep->children;
}
curnode = dom_get_elements_by_tag_name_ns_raw(
nodep, (char *) objmap->ns, (char *) objmap->local, &count, -1);
}
}
}
}
}
ZVAL_LONG(retval, count);
return SUCCESS;
}
/* {{{ proto int|bool dom_nodelist_count();
*/
PHP_METHOD(domnodelist, count)
{
zval *id;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(id);
if(dom_nodelist_length_read(intern, return_value) == FAILURE) {
RETURN_FALSE;
}
}
/* }}} end dom_nodelist_count */
/* }}} */
/* {{{ proto DOMNode dom_nodelist_item(int index);
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-844377136
Since:
*/
PHP_METHOD(domnodelist, item)
{
zval *id;
zend_long index;
int ret;
dom_object *intern;
xmlNodePtr itemnode = NULL;
dom_nnodemap_object *objmap;
xmlNodePtr nodep, curnode;
int count = 0;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &index) == FAILURE) {
RETURN_THROWS();
}
if (index >= 0) {
intern = Z_DOMOBJ_P(id);
objmap = (dom_nnodemap_object *)intern->ptr;
if (objmap != NULL) {
if (objmap->ht) {
if (objmap->nodetype == XML_ENTITY_NODE) {
itemnode = php_dom_libxml_hash_iter(objmap->ht, index);
} else {
itemnode = php_dom_libxml_notation_iter(objmap->ht, index);
}
} else {
if (objmap->nodetype == DOM_NODESET) {
HashTable *nodeht = HASH_OF(&objmap->baseobj_zv);
zval *entry = zend_hash_index_find(nodeht, index);
if (entry) {
ZVAL_COPY(return_value, entry);
return;
}
} else if (objmap->baseobj) {
nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
if (objmap->nodetype == XML_ATTRIBUTE_NODE || objmap->nodetype == XML_ELEMENT_NODE) {
curnode = nodep->children;
while (count < index && curnode != NULL) {
count++;
curnode = curnode->next;
}
itemnode = curnode;
} else {
if (nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDoc *) nodep);
} else {
nodep = nodep->children;
}
itemnode = dom_get_elements_by_tag_name_ns_raw(nodep, (char *) objmap->ns, (char *) objmap->local, &count, index);
}
}
}
}
}
if (itemnode) {
DOM_RET_OBJ(itemnode, &ret, objmap->baseobj);
return;
}
}
RETVAL_NULL();
}
/* }}} end dom_nodelist_item */
#endif
|
import os
import pathlib
import pytest
import hetnetpy.hetnet
import hetnetpy.readwrite
from .readwrite_test import extensions, formats
def test_creation(tmpdir):
# Convert py._path.local.LocalPath to a string
tmpdir = str(tmpdir)
# Construct metagraph
metaedge_tuples = [
("compound", "disease", "treats", "both"),
("disease", "gene", "associates", "both"),
("compound", "gene", "targets", "both"),
("gene", "gene", "interacts", "both"),
("gene", "gene", "transcribes", "forward"),
]
metanode_ids = "compound", "disease", "gene"
metagraph = hetnetpy.hetnet.MetaGraph.from_edge_tuples(metaedge_tuples)
# check that nodes got added to metagraph_node_dict
assert frozenset(metagraph.node_dict) == frozenset(metanode_ids)
for metanode in metagraph.node_dict.values():
assert isinstance(metanode, hetnetpy.hetnet.MetaNode)
# check that metanode.get_id() and hash(metanode) are working as expected
for metanode_id in metanode_ids:
metanode = metagraph.node_dict[metanode_id]
assert metanode.identifier == metanode_id
assert metanode.get_id() == metanode_id
assert hash(metanode) == hash(metanode_id)
# Check metanode and metaedge counts
assert metagraph.n_nodes == len(metanode_ids)
assert metagraph.n_edges == len(metaedge_tuples)
assert metagraph.n_inverts == 4
# Create a graph
graph = hetnetpy.hetnet.Graph(metagraph)
# Create a node for multiple sclerosis
ms = graph.add_node("disease", "DOID:2377", "multiple sclerosis")
assert ms.metanode.identifier == "disease"
assert ms.identifier == "DOID:2377"
assert ms.name == "multiple sclerosis"
assert ms.get_id() == ("disease", "DOID:2377")
# Create gene nodes
IL7R = graph.add_node("gene", 3575, "IL7R")
SPI1 = graph.add_node(
"gene", 6688, name="SPI1", data={"description": "Spi-1 proto-oncogene"}
)
# Attempt to add a duplicate node
with pytest.raises(AssertionError):
graph.add_node("gene", 3575, "IL7R")
# Misordered node creation arguments
with pytest.raises(KeyError):
graph.add_node("DOID:2377", "multiple sclerosis", "disease")
graph.add_edge(IL7R.get_id(), SPI1.get_id(), "transcribes", "forward")
graph.add_edge(IL7R, SPI1.get_id(), "interacts", "both")
graph.add_edge(ms.get_id(), IL7R, "associates", "both")
# Enable in future to check that creating a duplicate edge throws an error
with pytest.raises(AssertionError):
graph.add_edge(IL7R, SPI1, "transcribes", "forward")
# excinfo.match(r'edge already exists') # Disabled since new pytest feature
with pytest.raises(AssertionError):
graph.add_edge(SPI1, IL7R, "transcribes", "backward")
# Add bidirectional self loop
graph.add_edge(IL7R, IL7R, "interacts", "both")
# Test node and edge counts
assert graph.n_nodes == 3
assert graph.n_edges == 4
assert graph.n_inverts == 3
assert graph.n_nodes == len(list(graph.get_nodes()))
assert graph.n_edges == len(list(graph.get_edges(exclude_inverts=True)))
assert graph.n_edges + graph.n_inverts == len(
list(graph.get_edges(exclude_inverts=False))
)
# Test writing then reading graph
for extension in extensions:
for format_ in formats:
ext = f".{format_}{extension}"
# Write metagraph
path = os.path.join(tmpdir, "metagraph" + ext)
hetnetpy.readwrite.write_metagraph(metagraph, path)
hetnetpy.readwrite.read_metagraph(path)
# Write graph
path = os.path.join(tmpdir, "graph" + ext)
hetnetpy.readwrite.write_graph(graph, path)
hetnetpy.readwrite.read_graph(path)
def test_disase_gene_example():
"""
Recreate hetnet from https://doi.org/10.1371/journal.pcbi.1004259.g002.
"""
metaedge_id_GaD = "Gene", "Disease", "association", "both"
metaedge_tuples = [
metaedge_id_GaD,
("Gene", "Tissue", "expression", "both"),
("Disease", "Tissue", "localization", "both"),
("Gene", "Gene", "interaction", "both"),
]
metagraph = hetnetpy.hetnet.MetaGraph.from_edge_tuples(metaedge_tuples)
# Test metagraph getter methods
gene_metanode = metagraph.node_dict["Gene"]
# Test metagraph.get_metanode
assert metagraph.get_metanode(gene_metanode) == gene_metanode
assert metagraph.get_metanode("Gene") == gene_metanode
assert metagraph.get_metanode("G") == gene_metanode
# Test metanode properties
assert gene_metanode.abbrev == "G"
assert gene_metanode.neo4j_label == "Gene"
metaedge_GaD = metagraph.get_edge(metaedge_id_GaD)
# Test metagraph.get_metaedge
assert metagraph.get_metaedge(metaedge_GaD) == metaedge_GaD
assert metaedge_id_GaD == metaedge_GaD.get_id()
assert metagraph.get_metaedge(metaedge_id_GaD) == metaedge_GaD
assert metagraph.get_metaedge("ASSOCIATION_GaD") == metaedge_GaD
assert metagraph.get_metaedge("GaD") == metaedge_GaD
# Test metaedge properties
assert metaedge_GaD.abbrev == "GaD"
assert metaedge_GaD.neo4j_rel_type == "ASSOCIATION_GaD"
# Test metagraph.get_metapath
metapath_abbrev = "TlDaGiG"
metapath = metagraph.metapath_from_abbrev(metapath_abbrev)
assert metagraph.get_metapath(metapath) == metapath
assert metagraph.get_metapath(metapath_abbrev) == metapath
assert metagraph.get_metapath(metapath.edges) == metapath
# Test metapath.abbrev property
assert metapath.abbrev == metapath_abbrev
# Create graph
graph = hetnetpy.hetnet.Graph(metagraph)
nodes = dict()
# Add gene nodes
for symbol in ["STAT3", "IRF1", "SUMO1", "IL2RA", "IRF8", "ITCH", "CXCR4"]:
node = graph.add_node("Gene", symbol)
nodes[symbol] = node
# Add tissue nodes
for tissue in ["Lung", "Leukocyte"]:
node = graph.add_node("Tissue", tissue)
nodes[tissue] = node
# Add disease nodes
for disease in ["Crohn's Disease", "Multiple Sclerosis"]:
node = graph.add_node("Disease", disease)
nodes[disease] = node
assert graph.n_nodes == 11
# Add GiG edges
graph.add_edge(nodes["IRF1"], nodes["SUMO1"], "interaction", "both")
graph.add_edge(nodes["IRF1"], nodes["IL2RA"], "interaction", "both")
graph.add_edge(nodes["IRF1"], nodes["IRF8"], "interaction", "both")
graph.add_edge(nodes["IRF1"], nodes["CXCR4"], "interaction", "both")
graph.add_edge(nodes["ITCH"], nodes["CXCR4"], "interaction", "both")
# Add GaD edges
meta = "association", "both"
graph.add_edge(nodes["IRF1"], nodes["Crohn's Disease"], *meta)
graph.add_edge(nodes["Crohn's Disease"], nodes["STAT3"], *meta)
graph.add_edge(nodes["STAT3"], nodes["Multiple Sclerosis"], *meta)
graph.add_edge(nodes["IL2RA"], nodes["Multiple Sclerosis"], *meta)
graph.add_edge(nodes["IRF8"], nodes["Multiple Sclerosis"], *meta)
graph.add_edge(nodes["CXCR4"], nodes["Multiple Sclerosis"], *meta)
# Add TeG edges
graph.add_edge(nodes["IRF1"], nodes["Lung"], "expression", "both")
graph.add_edge(nodes["IRF1"], nodes["Leukocyte"], "expression", "both")
# Add DlT edges
graph.add_edge(
nodes["Multiple Sclerosis"], nodes["Leukocyte"], "localization", "both"
)
assert graph.n_edges == 14
assert graph.count_nodes("Disease") == 2
assert graph.count_nodes(gene_metanode) == 7
def get_hetionet_metagraph():
"""
Return the Hetionet v1.0 metagraph
"""
path = pathlib.Path(__file__).parent / "data/hetionet-v1.0-metagraph.json"
return hetnetpy.readwrite.read_metagraph(path)
@pytest.mark.parametrize(
["metapath", "symmetry"],
[
("GiG", True),
("GiGiG", True),
("GiGiGiG", True),
("GaD", False),
("GaDaG", True),
("GaDrD", False),
("GpPWpGpPWpG", True),
("Gr>Gr>G", False),
("Gr>G<rG", True),
("Gr>GiG<rG", True),
("G<rGiGr>G", True),
("G<rGiG<rG", False),
],
)
def test_metapath_symmetry(metapath, symmetry):
"""
https://github.com/hetio/hetnetpy/issues/38
"""
metagraph = get_hetionet_metagraph()
metapath = metagraph.get_metapath(metapath)
assert metapath.is_symmetric() == symmetry
if symmetry:
# Test only single metapath object is created
# https://github.com/hetio/hetnetpy/issues/38
assert metapath is metapath.inverse
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/blog-website-spa'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
'use strict';
const Blockchain = require('./blockchain');
const dappConfig = require('./dapp-config.json');
const ClipboardJS = require('clipboard');
const BN = require('bn.js'); // Required for injected code
const manifest = require('../manifest.json');
///+import
module.exports = class DappLib {
/*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/
static async isContractAdmin(data) {
let result = await Blockchain.get({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'isContractAdmin',
data.account
);
return {
type: DappLib.DAPP_RESULT_BOOLEAN,
label: 'Is Contract Admin',
result: result.callData,
hint: null
}
}
static async addContractAdmin(data) {
let result = await Blockchain.post({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'addContractAdmin',
data.account
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: 'Transaction Hash',
result: DappLib.getTransactionHash(result.callData),
hint: `Verify ${DappLib.formatAccount(data.account)} is an administrator by using "Is Contract Admin."`
}
}
static async removeContractAdmin(data) {
let result = await Blockchain.post({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'removeContractAdmin',
data.account
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: 'Transaction Hash',
result: DappLib.getTransactionHash(result.callData),
hint: `Verify ${DappLib.formatAccount(data.account)} is no longer an administrator by using "Is Contract Admin."`
}
}
static async removeLastContractAdmin(data) {
let result = await Blockchain.post({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'removeLastContractAdmin',
data.account
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: 'Transaction Hash',
result: DappLib.getTransactionHash(result.callData),
hint: `Verify that all functions that require an administrator no longer work."`
}
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> NFT: COMPOSER <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
static async getURI(data) {
let result = await Blockchain.get(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"getURI"
);
return {
type: DappLib.DAPP_RESULT_STRING,
label: "Result is",
result: result.callData,
hint: null,
};
}
static async supportsInterface(data) {
let result = await Blockchain.get(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"supportsInterface",
data.interfaceId
);
return {
type: DappLib.DAPP_RESULT_BOOLEAN,
label: "Is supported",
result: result.callData,
hint: null,
};
}
static async safeTransferFrom(data) {
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
},
},
"safeTransferFrom",
data.from,
data.to,
data.id,
data.amount,
data.data
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
result: DappLib.getTransactionHash(result.callData),
raw: result.callData,
hint: `Verify transfer by using "Balance for Account" to check the balance of ${DappLib.formatAccount(
data.to
)}.`,
};
}
static async safeBatchTransferFrom(data) {
let idsArray = [data.id1, data.id2, data.id3];
let amountsArray = [data.amount1, data.amount2, data.amount3];
if (typeof data.ids === "undefined") {
data.ids = idsArray;
}
if (typeof data.amounts === "undefined") {
data.amounts = amountsArray;
}
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
gas: 2000000
},
},
"safeBatchTransferFrom",
data.from,
data.to,
data.ids,
data.amounts,
data.data
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async balanceOf(data) {
let result = await Blockchain.get(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"balanceOf",
data.account,
data.id
);
let balance = result.callData;
return {
type: DappLib.DAPP_RESULT_STRING,
label: "Result is",
result: result.callData,
hint: null,
};
}
static async balanceOfBatch(data) {
let accountsArray = [data.account1, data.account2, data.account3];
let idsArray = [data.id1, data.id2, data.id3];
if (typeof data.ids === "undefined") {
data.ids = idsArray;
}
if (typeof data.accounts === "undefined") {
data.accounts = accountsArray;
}
let result = await Blockchain.get(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"balanceOfBatch",
data.accounts,
data.ids
);
return {
type: DappLib.DAPP_RESULT_ARRAY,
label: 'Batch balances',
result: result.callData
}
}
static async setApprovalForAll(data) {
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"setApprovalForAll",
data.operator,
data.approved
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async isApprovedForAll(data) {
let result = await Blockchain.get(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.from,
},
},
"isApprovedForAll",
data.account,
data.operator
);
return {
type: DappLib.DAPP_RESULT_BOOLEAN,
label: "Is approved for all",
result: result.callData,
hint: null,
};
}
static async setURI(data) {
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
},
},
"setURI",
data.newURI
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
result: DappLib.getTransactionHash(result.callData)
};
}
static async mint(data) {
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
},
},
"mint",
data.account,
data.id,
data.amount,
data.data
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async mintNFT(data) {
console.log("DappLib Input: ", { data });
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
gas: 2000000
},
},
"mintNFT",
data.account,
data.id,
1,
data.metaData
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async mintBatch(data) {
let idsArray = [data.id1, data.id2, data.id3];
let amountsArray = [data.amount1, data.amount2, data.amount3];
if (typeof data.ids === "undefined") {
data.ids = idsArray;
}
if (typeof data.amounts === "undefined") {
data.amounts = amountsArray;
}
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
gas: 2000000
},
},
"mintBatch",
data.account,
data.ids,
data.amounts,
data.data
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async burn(data) {
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
},
},
"burn",
data.account,
data.id,
data.amount
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
static async burnBatch(data) {
let idsArray = [data.id1, data.id2, data.id3];
let amountsArray = [data.amount1, data.amount2, data.amount3];
if (typeof data.ids === "undefined") {
data.ids = idsArray;
}
if (typeof data.amounts === "undefined") {
data.amounts = amountsArray;
}
let result = await Blockchain.post(
{
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: data.authorized,
gas: 2000000
},
},
"burnBatch",
data.account,
data.ids,
data.amounts
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: "Transaction Hash",
raw: result.callData,
result: DappLib.getTransactionHash(result.callData)
};
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/
static async isContractAuthorized(data) {
let result = await Blockchain.get({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'isContractAuthorized',
data.account
);
return {
type: DappLib.DAPP_RESULT_BOOLEAN,
label: 'Is Contract Authorized',
result: result.callData,
hint: null
}
}
static async authorizeContract(data) {
let result = await Blockchain.post({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'authorizeContract',
data.account
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: 'Transaction Hash',
result: DappLib.getTransactionHash(result.callData),
hint: `Verify ${DappLib.formatAccount(data.account)} is authorized by using "Is Contract Authorized."`
}
}
static async deauthorizeContract(data) {
let result = await Blockchain.post({
config: DappLib.getConfig(),
contract: DappLib.DAPP_STATE_CONTRACT,
params: {
from: null
}
},
'deauthorizeContract',
data.account
);
return {
type: DappLib.DAPP_RESULT_TX_HASH,
label: 'Transaction Hash',
result: DappLib.getTransactionHash(result.callData),
hint: `Verify ${DappLib.formatAccount(data.account)} is no longer authorized by using "Is Contract Authorized."`
}
}
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DAPP LIBRARY <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
static get DAPP_STATE_CONTRACT() {
return 'dappStateContract'
}
static get DAPP_CONTRACT() {
return 'dappContract'
}
static get DAPP_STATE_CONTRACT_WS() {
return 'dappStateContractWs'
}
static get DAPP_CONTRACT_WS() {
return 'dappContractWs'
}
static get DAPP_RESULT_BIG_NUMBER() {
return 'big-number'
}
static get DAPP_RESULT_ACCOUNT() {
return 'account'
}
static get DAPP_RESULT_TX_HASH() {
return 'tx-hash'
}
static get DAPP_RESULT_IPFS_HASH_ARRAY() {
return 'ipfs-hash-array'
}
static get DAPP_RESULT_SIA_HASH_ARRAY() {
return 'sia-hash-array'
}
static get DAPP_RESULT_ARRAY() {
return 'array'
}
static get DAPP_RESULT_OBJECT() {
return 'object'
}
static get DAPP_RESULT_STRING() {
return 'string'
}
static get DAPP_RESULT_ERROR() {
return 'error'
}
static async addEventHandler(contract, event, params, callback) {
Blockchain.handleEvent({
config: DappLib.getConfig(),
contract: contract,
params: params || {}
},
event,
(error, result) => {
if (error) {
callback({
event: event,
type: DappLib.DAPP_RESULT_ERROR,
label: 'Error Message',
result: error
});
} else {
callback({
event: event,
type: DappLib.DAPP_RESULT_OBJECT,
label: 'Event ' + event,
result: DappLib.getObjectNamedProperties(result)
});
}
}
);
}
static getTransactionHash(t) {
if (!t) { return ''; }
let value = '';
if (typeof t === 'string') {
value = t;
} else if (typeof t === 'object') {
if (t.hasOwnProperty('transactionHash')) {
value = t.transactionHash; // Ethereum
} else {
value = JSON.stringify(t);
}
}
return value;
}
static formatHint(hint) {
if (hint) {
return `<p class="mt-3 grey-text"><strong>Hint:</strong> ${hint}</p>`;
} else {
return '';
}
}
static formatNumber(n) {
var parts = n.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return `<strong class="p-1 blue-grey-text number copy-target" style="font-size:1.1rem;" title="${n}">${parts.join(".")}</strong>`;
}
static formatAccount(a) {
return `<strong class="green accent-1 p-1 blue-grey-text number copy-target" title="${a}">${DappLib.toCondensed(a, 6, 4)}</strong>${DappLib.addClippy(a)}`;
}
static formatTxHash(a) {
let value = DappLib.getTransactionHash(a);
return `<strong class="teal lighten-5 p-1 blue-grey-text number copy-target" title="${value}">${DappLib.toCondensed(value, 6, 4)}</strong>${DappLib.addClippy(value)}`;
}
static formatBoolean(a) {
return (a ? 'YES' : 'NO');
}
static formatText(a, copyText) {
if (!a) { return; }
if (a.startsWith('<')) {
return a;
}
return `<span class="copy-target" title="${copyText ? copyText : a}">${a}</span>${DappLib.addClippy(copyText ? copyText : a)}`;
}
static formatStrong(a) {
return `<strong>${a}</strong>`;
}
static formatPlain(a) {
return a;
}
static formatObject(a) {
let data = [];
let labels = ['Item', 'Value'];
let keys = ['item', 'value'];
let formatters = ['Strong', 'Text-20-5']; // 'Strong': Bold, 'Text-20-5': Compress a 20 character long string down to 5
let reg = new RegExp('^\\d+$'); // only digits
for (let key in a) {
if (!reg.test(key)) {
data.push({
item: key.substr(0, 1).toUpperCase() + key.substr(1),
value: a[key]
});
}
}
return DappLib.formatArray(data, formatters, labels, keys);
}
static formatArray(h, dataFormatters, dataLabels, dataKeys) {
let output = '<table class="table table-striped">';
if (dataLabels) {
output += '<thead><tr>';
for (let d = 0; d < dataLabels.length; d++) {
output += `<th scope="col">${dataLabels[d]}</th>`;
}
output += '</tr></thead>';
}
output += '<tbody>';
h.map((item) => {
output += '<tr>';
for (let d = 0; d < dataFormatters.length; d++) {
let text = String(dataKeys && dataKeys[d] ? item[dataKeys[d]] : item);
let copyText = dataKeys && dataKeys[d] ? item[dataKeys[d]] : item;
if (text.startsWith('<')) {
output += (d == 0 ? '<th scope="row">' : '<td>') + text + (d == 0 ? '</th>' : '</td>');
} else {
let formatter = 'format' + dataFormatters[d];
if (formatter.startsWith('formatText')) {
let formatterFrags = formatter.split('-');
if (formatterFrags.length === 3) {
text = DappLib.toCondensed(text, Number(formatterFrags[1]), Number(formatterFrags[2]));
} else if (formatterFrags.length === 2) {
text = DappLib.toCondensed(text, Number(formatterFrags[1]));
}
formatter = formatterFrags[0];
}
output += (d == 0 ? '<th scope="row">' : '<td>') + DappLib[formatter](text, copyText) + (d == 0 ? '</th>' : '</td>');
}
}
output += '</tr>';
})
output += '</tbody></table>';
return output;
}
static getFormattedResultNode(retVal, key) {
let returnKey = 'result';
if (key && (key !== null) && (key !== 'null') && (typeof (key) === 'string')) {
returnKey = key;
}
let formatted = '';
switch (retVal.type) {
case DappLib.DAPP_RESULT_BIG_NUMBER:
formatted = DappLib.formatNumber(retVal[returnKey].toString(10));
break;
case DappLib.DAPP_RESULT_TX_HASH:
formatted = DappLib.formatTxHash(retVal[returnKey]);
break;
case DappLib.DAPP_RESULT_ACCOUNT:
formatted = DappLib.formatAccount(retVal[returnKey]);
break;
case DappLib.DAPP_RESULT_BOOLEAN:
formatted = DappLib.formatBoolean(retVal[returnKey]);
break;
case DappLib.DAPP_RESULT_IPFS_HASH_ARRAY:
formatted = DappLib.formatArray(
retVal[returnKey],
['TxHash', 'IpfsHash', 'Text-10-5'], //Formatter
['Transaction', 'IPFS URL', 'Doc Id'], //Label
['transactionHash', 'ipfsHash', 'docId'] //Values
);
break;
case DappLib.DAPP_RESULT_SIA_HASH_ARRAY:
formatted = DappLib.formatArray(
retVal[returnKey],
['TxHash', 'SiaHash', 'Text-10-5'], //Formatter
['Transaction', 'Sia URL', 'Doc Id'], //Label
['transactionHash', 'docId', 'docId'] //Values
);
break;
case DappLib.DAPP_RESULT_ARRAY:
formatted = DappLib.formatArray(
retVal[returnKey],
retVal.formatter ? retVal.formatter : ['Text'],
null,
null
);
break;
case DappLib.DAPP_RESULT_STRING:
formatted = DappLib.formatPlain(
retVal[returnKey]
);
break;
case DappLib.DAPP_RESULT_OBJECT:
formatted = DappLib.formatObject(retVal[returnKey]);
break;
default:
formatted = retVal[returnKey];
break;
}
let resultNode = document.createElement('div');
resultNode.className = `note text-xs ${retVal.type === DappLib.DAPP_RESULT_ERROR ? 'bg-red-400' : 'bg-green-400'} m-3 p-3`;
let closeMarkup = '<div class="float-right" onclick="this.parentNode.parentNode.removeChild(this.parentNode)" title="Dismiss" class="text-right mb-1 mr-2" style="cursor:pointer;">X</div>';
resultNode.innerHTML = `<span class='text-xl break-words'>${closeMarkup} ${retVal.type === DappLib.DAPP_RESULT_ERROR ? '☹️' : '👍️'} ${(Array.isArray(retVal[returnKey]) ? 'Result' : retVal.label)} : ${formatted} ${DappLib.formatHint(retVal.hint)}</span>`
// Wire-up clipboard copy
new ClipboardJS('.copy-target', {
text: function (trigger) {
return trigger.getAttribute('data-copy');
}
});
return resultNode;
}
static getObjectNamedProperties(a) {
let reg = new RegExp('^\\d+$'); // only digits
let newObj = {};
for (let key in a) {
if (!reg.test(key)) {
newObj[key] = a[key];
}
}
return newObj;
}
static addClippy(data) {
return `
<svg data-copy="${data}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 22.1 23.5" style="enable-background:new 0 0 22.1 23.5;cursor:pointer;" class="copy-target" width="19px" height="20.357px" xml:space="preserve">
<style type="text/css">
.st99{fill:#777777;stroke:none;stroke-linecap:round;stroke-linejoin:round;}
</style>
<path class="st99" d="M3.9,17.4h5.4v1.4H3.9V17.4z M10.7,9.2H3.9v1.4h6.8V9.2z M13.4,13.3v-2.7l-4.1,4.1l4.1,4.1V16h6.8v-2.7H13.4z
M7.3,12H3.9v1.4h3.4V12z M3.9,16h3.4v-1.4H3.9V16z M16.1,17.4h1.4v2.7c0,0.4-0.1,0.7-0.4,1c-0.3,0.3-0.6,0.4-1,0.4H2.6
c-0.7,0-1.4-0.6-1.4-1.4V5.2c0-0.7,0.6-1.4,1.4-1.4h4.1c0-1.5,1.2-2.7,2.7-2.7s2.7,1.2,2.7,2.7h4.1c0.7,0,1.4,0.6,1.4,1.4V12h-1.4
V7.9H2.6v12.2h13.6V17.4z M3.9,6.5h10.9c0-0.7-0.6-1.4-1.4-1.4h-1.4c-0.7,0-1.4-0.6-1.4-1.4s-0.6-1.4-1.4-1.4S8,3.1,8,3.8
S7.4,5.2,6.6,5.2H5.3C4.5,5.2,3.9,5.8,3.9,6.5z"/>
</svg>
`;
}
static getAccounts() {
let accounts = dappConfig.accounts;
return accounts;
}
static fromAscii(str, padding) {
if (Array.isArray(str)) {
return DappLib.arrayToHex(str);
}
if (str.startsWith('0x') || !padding) {
return str;
}
if (str.length > padding) {
str = str.substr(0, padding);
}
var hex = '0x';
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
var n = code.toString(16);
hex += n.length < 2 ? '0' + n : n;
}
return hex + '0'.repeat(padding * 2 - hex.length + 2);
};
static toAscii(hex) {
var str = '',
i = 0,
l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i += 2) {
var code = parseInt(hex.substr(i, 2), 16);
if (code === 0) continue; // this is added
str += String.fromCharCode(code);
}
return str;
};
static arrayToHex(bytes) {
if (Array.isArray(bytes)) {
return '0x' +
Array.prototype.map.call(bytes, function (byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
} else {
return bytes;
}
}
static hexToArray(hex) {
if ((typeof hex === 'string') && (hex.beginsWith('0x'))) {
let bytes = [];
for (let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
return bytes;
} else {
return hex;
}
}
static toCondensed(s, begin, end) {
if (!s) { return; }
if (s.length && s.length <= begin + end) {
return s;
} else {
if (end) {
return `${s.substr(0, begin)}...${s.substr(s.length - end, end)}`;
} else {
return `${s.substr(0, begin)}...`;
}
}
}
static getManifest() {
return manifest;
}
// https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
static getUniqueId() {
return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
static getConfig() {
return dappConfig;
}
// Return value of this function is used to dynamically re-define getConfig()
// for use during testing. With this approach, even though getConfig() is static
// it returns the correct contract addresses as its definition is re-written
// before each test run. Look for the following line in test scripts to see it done:
// DappLib.getConfig = Function(`return ${ JSON.stringify(DappLib.getTestConfig(testDappStateContract, testDappContract, testAccounts))}`);
static getTestConfig(testDappStateContract, testDappContract, testAccounts) {
return Object.assign(
{},
dappConfig,
{
dappStateContractAddress: testDappStateContract.address,
dappContractAddress: testDappContract.address,
accounts: testAccounts,
owner: testAccounts[0],
admins: [
testAccounts[1],
testAccounts[2],
testAccounts[3]
],
users: [
testAccounts[4],
testAccounts[5],
testAccounts[6],
testAccounts[7],
testAccounts[8]
]
///+test
}
);
}
}
|
import tensorflow as tf
def model_fn(features, labels, mode, params):
input = features["input"]
# TODO: put this in a file and use index_table_from_file instead (set up graph using init op)
vocabulary = tf.constant(list(" abcdefghijklmnopqrstuvwxyz"), name="vocab")
# use the vocabulary lookup table
vocab = tf.contrib.lookup.index_table_from_tensor(vocabulary)
# split input strings into characters
with tf.name_scope("encoder"):
split = tf.string_split(input, delimiter='')
# for each character, lookup the index
encoded = vocab.lookup(split)
# perform one_hot encoding
dense_encoding = tf.sparse_tensor_to_dense(encoded, default_value=-1)
one_hot = tf.one_hot(dense_encoding, vocabulary.get_shape()[0])
# TODO: better way of computing sequence lengths in the graph?
lengths = tf.cast(tf.reduce_sum(one_hot, reduction_indices=[1, 2]), tf.int32)
def rnn_layer(size):
keep_prob = 1.0 - params["rnn_dropout"]
l = tf.contrib.rnn.GRUCell(size)
if keep_prob < 1.0 and mode is tf.estimator.ModeKeys.TRAIN:
l = tf.contrib.rnn.DropoutWrapper(l, output_keep_prob=keep_prob)
return l
rnn_layers = []
rnn_cell_sizes = params["rnn_cells"]
for size in rnn_cell_sizes:
rnn_layers.append(rnn_layer(size))
multi_rnn_cell = tf.contrib.rnn.MultiRNNCell(rnn_layers)
rnn_raw_out, _ = tf.nn.dynamic_rnn(cell=multi_rnn_cell,
inputs=one_hot,
sequence_length=lengths,
dtype=tf.float32,
scope="rnn_layers")
with tf.name_scope("rnn_output_relevant"):
# get the last relevant output from the rnn outputs
batch = tf.range(0, tf.shape(rnn_raw_out)[0]) # generate 0->batch_size
coordinates = tf.stack([batch, lengths - 1], 1) # stack the 0->batch_size sequence with the sequence lengths
rnn_out = tf.gather_nd(rnn_raw_out, coordinates) # perform a gather using those coordinates
# output sigmoid layers
output_cell_sizes = params["output_cells"]
output_dropout = params["output_dropout"]
def output_layer(last_layer, last_layer_size, layer_size, dropout):
W = tf.Variable(tf.random_uniform((last_layer_size, layer_size), -1, 1), dtype=tf.float32, name="W")
b = tf.Variable(tf.random_uniform((1, layer_size), -1, 1), name="b")
sig = tf.sigmoid(tf.matmul(last_layer, W) + b)
output = sig
keep_prob = 1.0-dropout
if keep_prob > 0.0:
output = tf.nn.dropout(output, 1.0-dropout)
return output
last_layer = rnn_out
last_layer_size = rnn_cell_sizes[-1]
with tf.name_scope("output_layers"):
for idx in range(0, len(output_cell_sizes)):
with tf.name_scope("layer"+str(idx)):
last_layer = output_layer(last_layer, last_layer_size, output_cell_sizes[idx], output_dropout)
last_layer_size = output_cell_sizes[idx]
# final prediction output
with tf.name_scope("final"):
predictions = output_layer(last_layer, last_layer_size, 3, False)
# predict
predictions_dict = {
"color": predictions,
}
# export outputs
exports_dict = {
"color": tf.estimator.export.PredictOutput(predictions_dict),
}
loss = None
train_op = None
if mode in [tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL]:
# calculate loss
rsme=tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(labels, predictions)), axis=1))
loss = tf.reduce_sum(rsme)/(tf.cast(tf.shape(input)[0], tf.float32))
# metrics for each mode (train, eval)
tf.summary.scalar("loss/"+mode, loss)
tf.summary.histogram("loss/"+mode, rsme)
if mode is tf.estimator.ModeKeys.TRAIN:
learning_rate = params["learning_rate"]
# set up optimizer
optimizer = tf.train.AdamOptimizer(learning_rate)
grads_and_vars = optimizer.compute_gradients(loss)
# clip gradients to help with exploding gradients in RNN's
grad_clip = params["grad_clip"]
grads_and_vars = [(tf.clip_by_value(g, -grad_clip, grad_clip), v) for g, v in grads_and_vars]
# train
global_step = tf.train.get_global_step()
train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)
# training summaries (picked up by tf.Estimator)
tf.summary.scalar("learning_rate", learning_rate)
for g,v in grads_and_vars:
tf.summary.histogram("grads/"+v.name.replace(":","_"), g)
for v in tf.trainable_variables():
tf.summary.histogram("vars/"+v.name.replace(":","_"), v)
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions_dict,
export_outputs=exports_dict,
loss=loss,
train_op=train_op,
)
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Contributor(s):
*
* Garen J. Torikian <gjtorikian AT gmail DOT com>
*
*
*
* ***** END LICENSE BLOCK ***** */
/*
THIS FILE WAS AUTOGENERATED BY mode_highlight_rules.tmpl.js (UUID: 21e323af-f665-4161-96e7-5087d262557e) */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var TypeScriptHighlightRules = function(options) {
var tsRules = [
// Match stuff like: module name {...}
{
token: ["keyword.operator.ts", "text", "variable.parameter.function.ts", "text"],
regex: "\\b(module)(\\s*)([a-zA-Z0-9_?.$][\\w?.$]*)(\\s*\\{)"
},
// Match stuff like: super(argument, list)
{
token: ["storage.type.variable.ts", "text", "keyword.other.ts", "text"],
regex: "(super)(\\s*\\()([a-zA-Z0-9,_?.$\\s]+\\s*)(\\))"
},
// Match stuff like: function() {...}
{
token: ["entity.name.function.ts","paren.lparen", "paren.rparen"],
regex: "([a-zA-Z_?.$][\\w?.$]*)(\\()(\\))"
},
// Match stuff like: (function: return type)
{
token: ["variable.parameter.function.ts", "text", "variable.parameter.function.ts"],
regex: "([a-zA-Z0-9_?.$][\\w?.$]*)(\\s*:\\s*)([a-zA-Z0-9_?.$][\\w?.$]*)"
},
{
token: ["keyword.operator.ts"],
regex: "(?:\\b(constructor|declare|interface|as|AS|public|private|class|extends|export|super)\\b)"
},
{
token: ["storage.type.variable.ts"],
regex: "(?:\\b(this\\.|string\\b|bool\\b|number)\\b)"
},
{
token: ["keyword.operator.ts", "storage.type.variable.ts", "keyword.operator.ts", "storage.type.variable.ts"],
regex: "(class)(\\s+[a-zA-Z0-9_?.$][\\w?.$]*\\s+)(extends)(\\s+[a-zA-Z0-9_?.$][\\w?.$]*\\s+)?"
},
{
token: "keyword",
regex: "(?:super|export|class|extends|import)\\b"
}
];
var JSRules = new JavaScriptHighlightRules({jsx: (options && options.jsx) == true}).getRules();
JSRules.start = tsRules.concat(JSRules.start);
this.$rules = JSRules;
};
oop.inherits(TypeScriptHighlightRules, JavaScriptHighlightRules);
exports.TypeScriptHighlightRules = TypeScriptHighlightRules;
});
|
import React, { Component } from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { login } from '../../actions/auth';
export class Login extends Component {
state = {
username: '',
password: '',
};
static propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool,
};
onSubmit = (e) => {
e.preventDefault();
this.props.login(this.state.username, this.state.password);
};
onChange = (e) => this.setState({ [e.target.name]: e.target.value });
render() {
if (this.props.isAuthenticated) {
return <Redirect to="/" />;
}
const { username, password } = this.state;
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Login</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
onChange={this.onChange}
value={username}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
name="password"
onChange={this.onChange}
value={password}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Login
</button>
</div>
<p>
Don't have an account? <Link to="/register">Register</Link>
</p>
</form>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps, { login })(Login);
|
from django.forms import ModelForm
from kombi.models import Freighter
class RegisterForm(ModelForm):
class Meta:
model = Freighter
fields = ['name','code','phone']
|
#!/usr/bin/env python3
import math
import torch
from torch.distributions import MultivariateNormal as TMultivariateNormal
from torch.distributions.kl import register_kl
from torch.distributions.utils import _standard_normal, lazy_property
from .. import settings
from ..lazy import DiagLazyTensor, LazyTensor, delazify, lazify
from ..utils.broadcasting import _mul_broadcast_shape
from .distribution import Distribution
class MultivariateNormal(TMultivariateNormal, Distribution):
"""
Constructs a multivariate normal random variable, based on mean and covariance.
Can be multivariate, or a batch of multivariate normals
Passing a vector mean corresponds to a multivariate normal.
Passing a matrix mean corresponds to a batch of multivariate normals.
:param torch.tensor mean: Vector n or matrix b x n mean of mvn distribution.
:param ~gpytorch.lazy.LazyTensor covar: Matrix n x n or batch matrix b x n x n covariance of
mvn distribution.
"""
def __init__(self, mean, covariance_matrix, validate_args=False):
self._islazy = isinstance(mean, LazyTensor) or isinstance(covariance_matrix, LazyTensor)
if self._islazy:
if validate_args:
ms = mean.size(-1)
cs1 = covariance_matrix.size(-1)
cs2 = covariance_matrix.size(-2)
if not (ms == cs1 and ms == cs2):
raise ValueError(f"Wrong shapes in {self._repr_sizes(mean, covariance_matrix)}")
self.loc = mean
self._covar = covariance_matrix
self.__unbroadcasted_scale_tril = None
self._validate_args = validate_args
batch_shape = _mul_broadcast_shape(self.loc.shape[:-1], covariance_matrix.shape[:-2])
event_shape = self.loc.shape[-1:]
# TODO: Integrate argument validation for LazyTensors into torch.distribution validation logic
super(TMultivariateNormal, self).__init__(batch_shape, event_shape, validate_args=False)
else:
super().__init__(loc=mean, covariance_matrix=covariance_matrix, validate_args=validate_args)
@property
def _unbroadcasted_scale_tril(self):
if self.islazy and self.__unbroadcasted_scale_tril is None:
# cache root decoposition
ust = delazify(self.lazy_covariance_matrix.cholesky())
self.__unbroadcasted_scale_tril = ust
return self.__unbroadcasted_scale_tril
@_unbroadcasted_scale_tril.setter
def _unbroadcasted_scale_tril(self, ust):
if self.islazy:
raise NotImplementedError("Cannot set _unbroadcasted_scale_tril for lazy MVN distributions")
else:
self.__unbroadcasted_scale_tril = ust
def expand(self, batch_size):
new_loc = self.loc.expand(torch.Size(batch_size) + self.loc.shape[-1:])
new_covar = self._covar.expand(torch.Size(batch_size) + self._covar.shape[-2:])
res = self.__class__(new_loc, new_covar)
return res
def confidence_region(self):
"""
Returns 2 standard deviations above and below the mean.
:rtype: (torch.Tensor, torch.Tensor)
:return: pair of tensors of size (b x d) or (d), where
b is the batch size and d is the dimensionality of the random
variable. The first (second) Tensor is the lower (upper) end of
the confidence region.
"""
std2 = self.stddev.mul_(2)
mean = self.mean
return mean.sub(std2), mean.add(std2)
@staticmethod
def _repr_sizes(mean, covariance_matrix):
return f"MultivariateNormal(loc: {mean.size()}, scale: {covariance_matrix.size()})"
@lazy_property
def covariance_matrix(self):
if self.islazy:
return self._covar.evaluate()
else:
return super().covariance_matrix
def get_base_samples(self, sample_shape=torch.Size()):
"""Get i.i.d. standard Normal samples (to be used with rsample(base_samples=base_samples))"""
with torch.no_grad():
shape = self._extended_shape(sample_shape)
base_samples = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device)
return base_samples
@lazy_property
def lazy_covariance_matrix(self):
"""
The covariance_matrix, represented as a LazyTensor
"""
if self.islazy:
return self._covar
else:
return lazify(super().covariance_matrix)
def log_prob(self, value):
if settings.fast_computations.log_prob.off():
return super().log_prob(value)
if self._validate_args:
self._validate_sample(value)
mean, covar = self.loc, self.lazy_covariance_matrix
diff = value - mean
# Repeat the covar to match the batch shape of diff
if diff.shape[:-1] != covar.batch_shape:
if len(diff.shape[:-1]) < len(covar.batch_shape):
diff = diff.expand(covar.shape[:-1])
else:
padded_batch_shape = (*(1 for _ in range(diff.dim() + 1 - covar.dim())), *covar.batch_shape)
covar = covar.repeat(
*(diff_size // covar_size for diff_size, covar_size in zip(diff.shape[:-1], padded_batch_shape)),
1,
1,
)
# Get log determininat and first part of quadratic form
inv_quad, logdet = covar.inv_quad_logdet(inv_quad_rhs=diff.unsqueeze(-1), logdet=True)
res = -0.5 * sum([inv_quad, logdet, diff.size(-1) * math.log(2 * math.pi)])
return res
def rsample(self, sample_shape=torch.Size(), base_samples=None):
covar = self.lazy_covariance_matrix
if base_samples is None:
# Create some samples
num_samples = sample_shape.numel() or 1
# Get samples
res = covar.zero_mean_mvn_samples(num_samples) + self.loc.unsqueeze(0)
res = res.view(sample_shape + self.loc.shape)
else:
# Make sure that the base samples agree with the distribution
if self.loc.shape != base_samples.shape[-self.loc.dim() :]:
raise RuntimeError(
"The size of base_samples (minus sample shape dimensions) should agree with the size "
"of self.loc. Expected ...{} but got {}".format(self.loc.shape, base_samples.shape)
)
# Determine what the appropriate sample_shape parameter is
sample_shape = base_samples.shape[: base_samples.dim() - self.loc.dim()]
# Reshape samples to be batch_size x num_dim x num_samples
# or num_bim x num_samples
base_samples = base_samples.view(-1, *self.loc.shape)
base_samples = base_samples.permute(*range(1, self.loc.dim() + 1), 0)
# Now reparameterize those base samples
covar_root = covar.root_decomposition().root
# If necessary, adjust base_samples for rank of root decomposition
if covar_root.shape[-1] < base_samples.shape[-2]:
base_samples = base_samples[..., : covar_root.shape[-1], :]
elif covar_root.shape[-1] > base_samples.shape[-2]:
raise RuntimeError("Incompatible dimension of `base_samples`")
res = covar_root.matmul(base_samples) + self.loc.unsqueeze(-1)
# Permute and reshape new samples to be original size
res = res.permute(-1, *range(self.loc.dim())).contiguous()
res = res.view(sample_shape + self.loc.shape)
return res
def sample(self, sample_shape=torch.Size(), base_samples=None):
with torch.no_grad():
return self.rsample(sample_shape=sample_shape, base_samples=base_samples)
@property
def variance(self):
if self.islazy:
# overwrite this since torch MVN uses unbroadcasted_scale_tril for this
diag = self.lazy_covariance_matrix.diag()
diag = diag.view(diag.shape[:-1] + self._event_shape)
return diag.expand(self._batch_shape + self._event_shape)
else:
return super().variance
def __add__(self, other):
if isinstance(other, MultivariateNormal):
return self.__class__(
mean=self.mean + other.mean,
covariance_matrix=(self.lazy_covariance_matrix + other.lazy_covariance_matrix),
)
elif isinstance(other, int) or isinstance(other, float):
return self.__class__(self.mean + other, self.lazy_covariance_matrix)
else:
raise RuntimeError("Unsupported type {} for addition w/ MultivariateNormal".format(type(other)))
def __radd__(self, other):
if other == 0:
return self
return self.__add__(other)
def __mul__(self, other):
if not (isinstance(other, int) or isinstance(other, float)):
raise RuntimeError("Can only multiply by scalars")
if other == 1:
return self
return self.__class__(mean=self.mean * other, covariance_matrix=self.lazy_covariance_matrix * (other ** 2))
def __truediv__(self, other):
return self.__mul__(1.0 / other)
def __getitem__(self, idx):
if not isinstance(idx, tuple):
idx = (idx,)
rest_idx = idx[:-1]
last_idx = idx[-1]
new_mean = self.mean[idx]
if len(idx) <= self.mean.dim() - 1 and (Ellipsis not in rest_idx):
new_cov = self.lazy_covariance_matrix[idx]
elif len(idx) > self.mean.dim():
raise IndexError(f"Index {idx} has too many dimensions")
else:
# In this case we know last_idx corresponds to the last dimension
# of mean and the last two dimensions of lazy_covariance_matrix
if isinstance(last_idx, int):
new_cov = DiagLazyTensor(self.lazy_covariance_matrix.diag()[(*rest_idx, last_idx)])
elif isinstance(last_idx, slice):
new_cov = self.lazy_covariance_matrix[(*rest_idx, last_idx, last_idx)]
elif last_idx is (...):
new_cov = self.lazy_covariance_matrix[rest_idx]
else:
new_cov = self.lazy_covariance_matrix[(*rest_idx, last_idx, slice(None, None, None))][..., last_idx]
return self.__class__(mean=new_mean, covariance_matrix=new_cov)
@register_kl(MultivariateNormal, MultivariateNormal)
def kl_mvn_mvn(p_dist, q_dist):
output_shape = _mul_broadcast_shape(p_dist.batch_shape, q_dist.batch_shape)
if output_shape != p_dist.batch_shape:
p_dist = p_dist.expand(output_shape)
if output_shape != q_dist.batch_shape:
q_dist = q_dist.expand(output_shape)
q_mean = q_dist.loc
q_covar = q_dist.lazy_covariance_matrix
p_mean = p_dist.loc
p_covar = p_dist.lazy_covariance_matrix
root_p_covar = p_covar.root_decomposition().root.evaluate()
mean_diffs = p_mean - q_mean
if isinstance(root_p_covar, LazyTensor):
# right now this just catches if root_p_covar is a DiagLazyTensor,
# but we may want to be smarter about this in the future
root_p_covar = root_p_covar.evaluate()
inv_quad_rhs = torch.cat([mean_diffs.unsqueeze(-1), root_p_covar], -1)
logdet_p_covar = p_covar.logdet()
trace_plus_inv_quad_form, logdet_q_covar = q_covar.inv_quad_logdet(inv_quad_rhs=inv_quad_rhs, logdet=True)
# Compute the KL Divergence.
res = 0.5 * sum([logdet_q_covar, logdet_p_covar.mul(-1), trace_plus_inv_quad_form, -float(mean_diffs.size(-1))])
return res
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:22:23 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/HealthToolbox.framework/HealthToolbox
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <HealthUI/HKInteractiveChartDataFormatter.h>
@interface WDSleepAnalysisInteractiveChartDataFormatter : HKInteractiveChartDataFormatter
-(id)formattedSelectedRangeLabelDataWithChartData:(id)arg1 ;
@end
|
#define _XOPEN_SOURCE 500
#include <string.h>
#include "sway/commands.h"
#include "log.h"
struct cmd_results *bar_cmd_id(int argc, char **argv) {
struct cmd_results *error = NULL;
if ((error = checkarg(argc, "id", EXPECTED_EQUAL_TO, 1))) {
return error;
}
const char *name = argv[0];
const char *oldname = config->current_bar->id;
if (strcmp(name, oldname) == 0) {
return cmd_results_new(CMD_SUCCESS, NULL, NULL); // NOP
}
// check if id is used by a previously defined bar
for (int i = 0; i < config->bars->length; ++i) {
struct bar_config *find = config->bars->items[i];
if (strcmp(name, find->id) == 0 && config->current_bar != find) {
return cmd_results_new(CMD_FAILURE, "id",
"Id '%s' already defined for another bar. Id unchanged (%s).",
name, oldname);
}
}
wlr_log(WLR_DEBUG, "Renaming bar: '%s' to '%s'", oldname, name);
// free old bar id
free(config->current_bar->id);
config->current_bar->id = strdup(name);
return cmd_results_new(CMD_SUCCESS, NULL, NULL);
}
|
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.preorder = None
self.reverses = None
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
pre_size = len(preorder)
in_size = len(inorder)
if pre_size != in_size:
return None
self.preorder = preorder
self.reverses = dict()
for i in range(in_size):
self.reverses[inorder[i]] = i
return self.__build_tree(0, pre_size - 1, 0, in_size - 1)
def __build_tree(self, pre_left, pre_right, in_left, in_right):
if pre_left > pre_right or in_left > in_right:
return None
pivot = self.preorder[pre_left]
root = TreeNode(pivot)
pivot_index = self.reverses[pivot]
root.left = self.__build_tree(pre_left + 1, pivot_index - in_left + pre_left, in_left, pivot_index - 1)
root.right = self.__build_tree(pivot_index - in_left + pre_left + 1, pre_right, pivot_index + 1, in_right)
return root
if __name__ == '__main__':
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
solution = Solution()
res = solution.buildTree(preorder, inorder)
print(res.val)
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/redshift/RedshiftRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
namespace Redshift
{
namespace Model
{
/**
* <p/><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ModifyEventSubscriptionMessage">AWS
* API Reference</a></p>
*/
class AWS_REDSHIFT_API ModifyEventSubscriptionRequest : public RedshiftRequest
{
public:
ModifyEventSubscriptionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ModifyEventSubscription"; }
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline const Aws::String& GetSubscriptionName() const{ return m_subscriptionName; }
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline bool SubscriptionNameHasBeenSet() const { return m_subscriptionNameHasBeenSet; }
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline void SetSubscriptionName(const Aws::String& value) { m_subscriptionNameHasBeenSet = true; m_subscriptionName = value; }
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline void SetSubscriptionName(Aws::String&& value) { m_subscriptionNameHasBeenSet = true; m_subscriptionName = std::move(value); }
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline void SetSubscriptionName(const char* value) { m_subscriptionNameHasBeenSet = true; m_subscriptionName.assign(value); }
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSubscriptionName(const Aws::String& value) { SetSubscriptionName(value); return *this;}
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSubscriptionName(Aws::String&& value) { SetSubscriptionName(std::move(value)); return *this;}
/**
* <p>The name of the modified Amazon Redshift event notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSubscriptionName(const char* value) { SetSubscriptionName(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline const Aws::String& GetSnsTopicArn() const{ return m_snsTopicArn; }
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline bool SnsTopicArnHasBeenSet() const { return m_snsTopicArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline void SetSnsTopicArn(const Aws::String& value) { m_snsTopicArnHasBeenSet = true; m_snsTopicArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline void SetSnsTopicArn(Aws::String&& value) { m_snsTopicArnHasBeenSet = true; m_snsTopicArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline void SetSnsTopicArn(const char* value) { m_snsTopicArnHasBeenSet = true; m_snsTopicArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSnsTopicArn(const Aws::String& value) { SetSnsTopicArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSnsTopicArn(Aws::String&& value) { SetSnsTopicArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the SNS topic to be used by the event
* notification subscription.</p>
*/
inline ModifyEventSubscriptionRequest& WithSnsTopicArn(const char* value) { SetSnsTopicArn(value); return *this;}
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline const Aws::String& GetSourceType() const{ return m_sourceType; }
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline bool SourceTypeHasBeenSet() const { return m_sourceTypeHasBeenSet; }
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline void SetSourceType(const Aws::String& value) { m_sourceTypeHasBeenSet = true; m_sourceType = value; }
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline void SetSourceType(Aws::String&& value) { m_sourceTypeHasBeenSet = true; m_sourceType = std::move(value); }
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline void SetSourceType(const char* value) { m_sourceTypeHasBeenSet = true; m_sourceType.assign(value); }
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline ModifyEventSubscriptionRequest& WithSourceType(const Aws::String& value) { SetSourceType(value); return *this;}
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline ModifyEventSubscriptionRequest& WithSourceType(Aws::String&& value) { SetSourceType(std::move(value)); return *this;}
/**
* <p>The type of source that will be generating the events. For example, if you
* want to be notified of events generated by a cluster, you would set this
* parameter to cluster. If this value is not specified, events are returned for
* all Amazon Redshift objects in your AWS account. You must specify a source type
* in order to specify source IDs.</p> <p>Valid values: cluster,
* cluster-parameter-group, cluster-security-group, and cluster-snapshot.</p>
*/
inline ModifyEventSubscriptionRequest& WithSourceType(const char* value) { SetSourceType(value); return *this;}
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline const Aws::Vector<Aws::String>& GetSourceIds() const{ return m_sourceIds; }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline bool SourceIdsHasBeenSet() const { return m_sourceIdsHasBeenSet; }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline void SetSourceIds(const Aws::Vector<Aws::String>& value) { m_sourceIdsHasBeenSet = true; m_sourceIds = value; }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline void SetSourceIds(Aws::Vector<Aws::String>&& value) { m_sourceIdsHasBeenSet = true; m_sourceIds = std::move(value); }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline ModifyEventSubscriptionRequest& WithSourceIds(const Aws::Vector<Aws::String>& value) { SetSourceIds(value); return *this;}
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline ModifyEventSubscriptionRequest& WithSourceIds(Aws::Vector<Aws::String>&& value) { SetSourceIds(std::move(value)); return *this;}
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline ModifyEventSubscriptionRequest& AddSourceIds(const Aws::String& value) { m_sourceIdsHasBeenSet = true; m_sourceIds.push_back(value); return *this; }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline ModifyEventSubscriptionRequest& AddSourceIds(Aws::String&& value) { m_sourceIdsHasBeenSet = true; m_sourceIds.push_back(std::move(value)); return *this; }
/**
* <p>A list of one or more identifiers of Amazon Redshift source objects. All of
* the objects must be of the same type as was specified in the source type
* parameter. The event subscription will return only events generated by the
* specified objects. If not specified, then events are returned for all objects
* within the source type specified.</p> <p>Example: my-cluster-1, my-cluster-2</p>
* <p>Example: my-snapshot-20131010</p>
*/
inline ModifyEventSubscriptionRequest& AddSourceIds(const char* value) { m_sourceIdsHasBeenSet = true; m_sourceIds.push_back(value); return *this; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline const Aws::Vector<Aws::String>& GetEventCategories() const{ return m_eventCategories; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline bool EventCategoriesHasBeenSet() const { return m_eventCategoriesHasBeenSet; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline void SetEventCategories(const Aws::Vector<Aws::String>& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories = value; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline void SetEventCategories(Aws::Vector<Aws::String>&& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories = std::move(value); }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline ModifyEventSubscriptionRequest& WithEventCategories(const Aws::Vector<Aws::String>& value) { SetEventCategories(value); return *this;}
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline ModifyEventSubscriptionRequest& WithEventCategories(Aws::Vector<Aws::String>&& value) { SetEventCategories(std::move(value)); return *this;}
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline ModifyEventSubscriptionRequest& AddEventCategories(const Aws::String& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(value); return *this; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline ModifyEventSubscriptionRequest& AddEventCategories(Aws::String&& value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(std::move(value)); return *this; }
/**
* <p>Specifies the Amazon Redshift event categories to be published by the event
* notification subscription.</p> <p>Values: configuration, management, monitoring,
* security</p>
*/
inline ModifyEventSubscriptionRequest& AddEventCategories(const char* value) { m_eventCategoriesHasBeenSet = true; m_eventCategories.push_back(value); return *this; }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline const Aws::String& GetSeverity() const{ return m_severity; }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline bool SeverityHasBeenSet() const { return m_severityHasBeenSet; }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(const Aws::String& value) { m_severityHasBeenSet = true; m_severity = value; }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(Aws::String&& value) { m_severityHasBeenSet = true; m_severity = std::move(value); }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline void SetSeverity(const char* value) { m_severityHasBeenSet = true; m_severity.assign(value); }
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline ModifyEventSubscriptionRequest& WithSeverity(const Aws::String& value) { SetSeverity(value); return *this;}
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline ModifyEventSubscriptionRequest& WithSeverity(Aws::String&& value) { SetSeverity(std::move(value)); return *this;}
/**
* <p>Specifies the Amazon Redshift event severity to be published by the event
* notification subscription.</p> <p>Values: ERROR, INFO</p>
*/
inline ModifyEventSubscriptionRequest& WithSeverity(const char* value) { SetSeverity(value); return *this;}
/**
* <p>A Boolean value indicating if the subscription is enabled. <code>true</code>
* indicates the subscription is enabled </p>
*/
inline bool GetEnabled() const{ return m_enabled; }
/**
* <p>A Boolean value indicating if the subscription is enabled. <code>true</code>
* indicates the subscription is enabled </p>
*/
inline bool EnabledHasBeenSet() const { return m_enabledHasBeenSet; }
/**
* <p>A Boolean value indicating if the subscription is enabled. <code>true</code>
* indicates the subscription is enabled </p>
*/
inline void SetEnabled(bool value) { m_enabledHasBeenSet = true; m_enabled = value; }
/**
* <p>A Boolean value indicating if the subscription is enabled. <code>true</code>
* indicates the subscription is enabled </p>
*/
inline ModifyEventSubscriptionRequest& WithEnabled(bool value) { SetEnabled(value); return *this;}
private:
Aws::String m_subscriptionName;
bool m_subscriptionNameHasBeenSet;
Aws::String m_snsTopicArn;
bool m_snsTopicArnHasBeenSet;
Aws::String m_sourceType;
bool m_sourceTypeHasBeenSet;
Aws::Vector<Aws::String> m_sourceIds;
bool m_sourceIdsHasBeenSet;
Aws::Vector<Aws::String> m_eventCategories;
bool m_eventCategoriesHasBeenSet;
Aws::String m_severity;
bool m_severityHasBeenSet;
bool m_enabled;
bool m_enabledHasBeenSet;
};
} // namespace Model
} // namespace Redshift
} // namespace Aws
|
from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.core.anyof import any_of
from hamcrest.core.helpers.hasmethod import hasmethod
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
__author__ = "Jon Reid"
__copyright__ = "Copyright 2011 hamcrest.org"
__license__ = "BSD, see License.txt"
class IsSequenceOnlyContaining(BaseMatcher):
def __init__(self, matcher):
self.matcher = matcher
def _matches(self, sequence):
try:
sequence = list(sequence)
if len(sequence) == 0:
return False
for item in sequence:
if not self.matcher.matches(item):
return False
return True
except TypeError:
return False
def describe_to(self, description):
description.append_text('a sequence containing items matching ') \
.append_description_of(self.matcher)
def only_contains(*items):
"""Matches if each element of sequence satisfies any of the given matchers.
:param match1,...: A comma-separated list of matchers.
This matcher iterates the evaluated sequence, confirming whether each
element satisfies any of the given matchers.
Example::
only_contains(less_than(4))
will match ``[3,1,2]``.
Any argument that is not a matcher is implicitly wrapped in an
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
equality.
"""
matchers = []
for item in items:
matchers.append(wrap_matcher(item))
return IsSequenceOnlyContaining(any_of(*matchers))
|
const assert = require('assert');
const path = require('path');
const util = require('./utils');
const async = require('async');
const BigNumber = require("bignumber.js");
const testdata = require('./data/secp2561k_data.json');
var secp256k1;
const bytecode = "0x6060604052611286806100126000396000f3606060405260e060020a600035046304e960d7811461004757806323e47a01146101955780634f5dde4c146101e75780639f6fc3c014610222578063da8b0d711461029d575b005b60408051808201825261034991600480359290916064919060249060029083908390808284378051808201825292979660a4965092945091929184915083908082843750909550505050505060006103a184848460006000600060006060604051908101604052806003905b60008152602001906001900390816100b357505060408051606081019091526003815b60008152602001906001900390816100d657505060408051606081019091526003815b60008152602001906001900390816100f9575050885170014551231950b75fc4402da1732fc9bebe1996506401000003d019955060009081148061013f57508951879010155b8061014e575060208a01516000145b8061017d575060208a01517f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a090115b156103bf57600097505b505050505050509392505050565b60408051808201825261035d9160049160449183906002908390839080828437509095505050505050600060006103a9836000808281508051915060016020919091015181161461063e576000610641565b604080518082018252610349916004916044918390600290839083908082843750909550505050505060006103b2825b60006103b282610252565b604080518082018252610349916004916044918390600290839083908082843750909550505050505060006103b2825b60006401000003d01981808481505181148061026e5750845183145b8061027d575060208501516000145b8061028b5750602085015183145b1561064857600093505b505050919050565b61037d6004356024356040604051908101604052806002905b60008152602001906001900390816102b6579050506103b883836040604051908101604052806002905b60008152602001906001900390816102e057506401000003d0199050600080808360078180898009890908925061066f837f3fffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff0c86600060008460001415610e06575b509392505050565b604080519115158252519081900360200190f35b604051808360ff1681526020018281526020019250505060405180910390f35b60408051908190839080838184600060046021f15090500191505060405180910390f35b949350505050565b91509150915091565b92915050565b9392505050565b6103c889610217565b15156103d75760009750610187565b60208a015161041190885b60006000600060006000600087600014806103fc57508688145b806104075750866000145b156106af57610002565b945061055187868d09604080518082019091527f79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179881527f483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b860208201525b6060604051908101604052806003905b600081526020019060019003908161047e57905050600060006000610300604051908101604052806008905b6060604051908101604052806003905b60008152602001906001900390816104ba579050508152602001906001900390816104aa57505060408051606081019091526003815b60008152602001906001900390816104f05750506040805161020081019091526010815b6000815260200190600190039081610514579050506000600060006401000003d01998508b600014156106ff575b50505050505050505092915050565b935061056687868c600050508c51098a61046e565b92506105fd84845b6060604051908101604052806003905b600081526020019060019003908161057e5790505060006080604051908101604052806004905b60008152602001906001900390816105a557505060408051608081019091526004815b60008152602001906001900390816105c8575060009050808080808a60029090602002015160001415610cee57899850610ce0565b6040810151909250600014156106165760009750610187565b604082015161062590876103e2565b905085868283098351098a518882061498509050610187565b60015b9150915091565b60208501518390800985519092508390600790829081818009090890508082149350610295565b8686529150506001811660ff8716186000811461068e57818403610690565b815b6020860152509295945050505050565b8495505b505050505092915050565b868811156106bd5796869006965b600193508692508791505b600082146106e95750919282820480850290910392918183029003906106c8565b60008512156106a05784600003870395506106a4565b6000604051985061020089016040525b8c156107475760018d1615610736575060208c06808989015360206010821102818e03019c505b60028d049c5060018801975061070f565b50604080516060810182528c51815260208d8101519082015260019181019190915280875261077590610830565b9450610877858c6060604051908101604052806003905b600081526020019060019003908161078c5790505060006040604051908101604052806002905b60008152602001906001900390816107b357505060408051608081019091526004815b60008152602001906001900390816107d6575060009050808080808a60029090602002015160001415610ef657604080516060810182528b51815260208c810151908201526001918101919091529850610ce0565b610dff8b5b6060604051908101604052806003905b600081526020019060019003908161084057506401000003d0199050600080808080808860025060400151811415610e8557610eea565b6020870181905261088990869061056e565b6040870181905261089b90869061056e565b606087018190526108ad90869061056e565b608087018190526108bf90869061056e565b60a087018190526108d190869061056e565b60c087018190526108e390869061056e565b60e087015260208601516040015180855289908760025050604088810151015109602085018190526060870151604001518a9190096040858101829052608088015101518a9190096060850181905260a0870151604001518a9190096080850181905260c0870151604001518a91900960a0850181905260e0870151604001518a91900960c08501819052610978908a6103e2565b60e08501819052610100850181905260a08501518a9190096101e0850152600692505b60028310610a025761010084015189908760018601600881101561000257602002015160400151096101008501819052899085600119860160108110156100025760200201510984846008016010811015610002576020020152600019929092019161099b565b6040868101516101008601519101518a919009610120850152600092505b6007831015610c1b57610aa686846001016008811015610002576020020151856009860160108110156100025760200201518b87600988016010811015610002576020020151886009890160108110156100025760200201510982518d908190839009845280808385096020860151096020850152505060016040929092019190915250565b60019290920191610a20565b6010821115610bb757600282601f030490508050610c1b8a60406040519081016040528089856008811015610002575050602085028a015160009090602002015181526020018985600881101561000257505060208581028b015101518d0390525b60006040604051908101604052806002905b6000815260200190600190039081610b2657505060408051608081019091526004815b6000815260200190600190039081610b495750600090508080808089600190906020020151600014156111a25788518a52602089810151908b0152600160408b0152611196565b6112818a5b6401000003d01960008080808080876002506040015181141561108e576110f3565b6000821115610c1b576002600183030490508050610c1b8a60406040519081016040528089856008811015610002575050602085028a015160009090602002015181526020018985600881101561000257505060208581028b015101519052610b14565b6000871115610542578688016000199081015197019660001a9150610ab28a610b95565b8551604087015189918203900860208701516060880151919650899190820390089350878586099250878584099150878289038986870908905087808085896000505089510960020989038208808a5286519091508890819083820390829087900908850960208a8101919091528601518890819084900981038a6001909060200201510860208a015260408a810151908c01518991829109860960408a01525b505050505050505092915050565b60408a015160001415610d03578a9850610ce0565b60408b01516401000003d01998508890800980885260408c015189919009602088015260408a01518890800960408881018290528b015189919009606088015260408051608081018252908801518c5182918b9109815260200189896003600481101561000257505060608a015160208f015109815260200189896000600481101561000257505089518d5109815260200189896001600481101561000257505060208a810151908e0151099052955085600290906020020151866000600481101561000257909060200201511415610c3f57856003909060200201518660016004811015610002579090602002015114151561082b57610ce0565b9850610ce0565b8360001415610e185760019150610341565b8260001415610e2657610002565b506001905060ff60020a5b801561034157828185161515860a84848509099150826002820485161515860a84848509099150826004820485161515860a84848509099150826008820485161515860a8484850909915060109004610e31565b885160208a015190965094508685800993508687858809600409925086878788096003099150868784850888038884850908808952905086808086800960080988038889848b0387088509086020890152604089015187908190870960020960408901525b50505050505050919050565b60208a015160001415610f0b578a9850610ce0565b60408b01516401000003d01998508890800980885260408c015189919009602088810191909152604080516080810182528d5181528d83015192810192909252810189896000505089518d5109815260200189896001600281101561000257505060208a810151908e0151099052955085600290906020020151866000600481101561000257909060200201511415610fe1578560039090602002015186600160048110156100025790906020020151141515610fd8576000808c5260208c0181905260408c0152610ce0565b6110888b610830565b8551604087015189918203900860208701516060880151919650899190820390089350878586099250878584099150878289038986870908905087808085896000505089510960020989038208808a5286519091508890819083820390829087900908850960208a8101919091528601518890819084900981038a6001909060200201510860208a015260408b01518890860960408a015250969998505050505050505050565b50610ce0565b8751602089015190965094508685800993508687858809600409925086878788096003099150868784850888038884850908808952905086808086800960080988038889848b0387088509086020890152604088015187908190870960020960408901525b5050505050505050565b8551604087015189918203900860208701516060880151919650899190820390089350878586099250878584099150878289038986870908905087808085896000505089510960020989038208808b5286519091508890819083820390829087900908850960208b8101919091528601518890819084900981038b6001909060200201510860208b015260408a01518890860960408b01525b50505050505050505050565b6020890151600014156111b457611196565b60408a01516401000003d01998508890800980885260408b015189919009602088810191909152604080516080810182528c5181528c83015192810192909252810189896000505089518c5109815260200189896001600281101561000257505060208a810151908d01510990529550856002909060200201518660006004811015610002579090602002015114156110fd578560039090602002015186600160048110156100025790906020020151141515610b90576000808b5260208b0181905260408b0152611196565b61119656";
const ABI = [{
"constant": true,
"inputs": [{"name": "h", "type": "bytes32"}, {"name": "rs", "type": "uint256[2]"}, {
"name": "Q",
"type": "uint256[2]"
}],
"name": "validateSignature",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
}, {
"constant": true,
"inputs": [{"name": "P", "type": "uint256[2]"}],
"name": "compress",
"outputs": [{"name": "yBit", "type": "uint8"}, {"name": "x", "type": "uint256"}],
"type": "function"
}, {
"constant": true,
"inputs": [{"name": "P", "type": "uint256[2]"}],
"name": "isPubKey",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
}, {
"constant": true,
"inputs": [{"name": "P", "type": "uint256[2]"}],
"name": "onCurve",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
}, {
"constant": true,
"inputs": [{"name": "yBit", "type": "uint8"}, {"name": "Px", "type": "uint256"}],
"name": "decompress",
"outputs": [{"name": "", "type": "uint256[2]"}],
"type": "function"
}];
describe('Crypto', function () {
describe('Secp256k1Curve', function () {
before(function (done) {
this.timeout(300000); // 5 minutes.
console.log("\tInitializing web3 and deploying the Secp256k1 test contract.");
util.initWeb3(function (err) {
if (err)
return done(err);
util.deploy(ABI, bytecode, function (err, contract) {
if (err)
return done(err);
secp256k1 = contract;
done();
});
});
});
describe('#onCurve()', function () {
it('should detect that the given points are on the curve', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.randomPoints, function (point, idx, cb) {
secp256k1.onCurve(point, function (err, result) {
assert.ifError(err);
assert(result);
cb();
})
}, function () {
done();
}
);
});
it('should detect that the given points are not on the curve', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.randomPoints, function (point, idx, cb) {
secp256k1.onCurve([point[0], point[0]], function (err, result) {
assert.ifError(err);
assert(!result);
cb();
})
}, function () {
done();
}
);
});
});
describe('#isPubKey()', function () {
it('should detect that the given points are valid public keys', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.randomPoints, function (point, idx, cb) {
secp256k1.isPubKey(point, function (err, result) {
assert.ifError(err);
assert(result);
cb();
})
}, function () {
done();
}
);
});
it('should detect that the given points are not valid public keys', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.randomPoints, function (point, idx, cb) {
secp256k1.isPubKey([point[0], point[0]], function (err, result) {
assert.ifError(err);
assert(!result);
cb();
})
}, function () {
done();
}
);
});
});
describe('#validateSignature()', function () {
it('should detect that the given signatures are valid', function (done) {
this.timeout(10000);
var message = testdata.message;
async.forEachOfSeries(testdata.keypairs, function (keypair, idx, cb) {
var signature = testdata.signatures[idx];
secp256k1.validateSignature(message, signature, keypair.pub, function (err, result) {
assert.ifError(err);
assert(result);
cb();
})
}, function () {
done();
}
);
});
it('should detect that the public key does not correspond to the given signature', function (done) {
this.timeout(10000);
var message = testdata.message;
async.forEachOfSeries(testdata.keypairs, function (keypair, idx, cb) {
var signature = testdata.signatures[17 - idx];
secp256k1.validateSignature(message, signature, keypair.pub, function (err, result) {
assert.ifError(err);
assert(!result);
cb();
})
}, function () {
done();
}
);
});
it('should detect that the given signatures and pubkeys are wrong for the given message', function (done) {
this.timeout(10000);
var message = "0x1234123412341234123412341234123412341234123412341234123412341234";
async.forEachOfSeries(testdata.keypairs, function (keypair, idx, cb) {
var signature = testdata.signatures[idx];
secp256k1.validateSignature(message, signature, keypair.pub, function (err, result) {
assert.ifError(err);
assert(!result);
cb();
})
}, function () {
done();
}
);
});
it('should compress a set of points successfully', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.keypairs, function (keypair, idx, cb) {
secp256k1.compress(keypair.pub, function (err, result) {
assert.ifError(err);
var x = new BigNumber(keypair.pub[0]);
var yBit = new BigNumber(keypair.pub[1]).mod(2);
assert(yBit.eq(result[0]));
assert(x.eq(result[1]));
cb();
})
}, function () {
done();
}
);
});
it('should decompress a set of points successfully', function (done) {
this.timeout(10000);
async.forEachOfSeries(testdata.keypairs, function (keypair, idx, cb) {
var x = new BigNumber(keypair.pub[0]);
var yBit = new BigNumber(keypair.pub[1]).mod(2);
secp256k1.decompress(yBit, x, function (err, result) {
assert.ifError(err);
assert(new BigNumber(keypair.pub[0]).eq(result[0]));
assert(new BigNumber(keypair.pub[1]).eq(result[1]));
cb();
})
}, function () {
done();
}
);
});
});
});
});
|
/*!
Chosen, a Select Box Enhancer for jQuery and Prototype
by Patrick Filler for Harvest, http://getharvest.com
Version 1.6.2
Full source at https://github.com/harvesthq/chosen
Copyright (c) 2011-2016 Harvest http://getharvest.com
MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
This file is generated by `grunt build`, do not edit it by hand.
*/
(function () {
var $, AbstractChosen, Chosen, SelectParser, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SelectParser = (function () {
function SelectParser() {
this.options_index = 0;
this.parsed = [];
}
SelectParser.prototype.add_node = function (child) {
if (child.nodeName.toUpperCase() === "OPTGROUP") {
return this.add_group(child);
} else {
return this.add_option(child);
}
};
SelectParser.prototype.add_group = function (group) {
var group_position, option, _i, _len, _ref, _results;
group_position = this.parsed.length;
this.parsed.push({
array_index: group_position,
group: true,
label: this.escapeExpression(group.label),
title: group.title ? group.title : void 0,
children: 0,
disabled: group.disabled,
classes: group.className
});
_ref = group.childNodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
_results.push(this.add_option(option, group_position, group.disabled));
}
return _results;
};
SelectParser.prototype.add_option = function (option, group_position, group_disabled) {
if (option.nodeName.toUpperCase() === "OPTION") {
if (option.text !== "") {
if (group_position != null) {
this.parsed[group_position].children += 1;
}
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
title: option.title ? option.title : void 0,
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
group_label: group_position != null ? this.parsed[group_position].label : null,
classes: option.className,
style: option.style.cssText
});
} else {
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
empty: true
});
}
return this.options_index += 1;
}
};
SelectParser.prototype.escapeExpression = function (text) {
var map, unsafe_chars;
if ((text == null) || text === false) {
return "";
}
if (!/[\&\<\>\"\'\`]/.test(text)) {
return text;
}
map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g;
return text.replace(unsafe_chars, function (chr) {
return map[chr] || "&";
});
};
return SelectParser;
})();
SelectParser.select_to_array = function (select) {
var child, parser, _i, _len, _ref;
parser = new SelectParser();
_ref = select.childNodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
parser.add_node(child);
}
return parser.parsed;
};
AbstractChosen = (function () {
function AbstractChosen(form_field, options) {
this.form_field = form_field;
this.options = options != null ? options : {};
if (!AbstractChosen.browser_is_supported()) {
return;
}
this.is_multiple = this.form_field.multiple;
this.set_default_text();
this.set_default_values();
this.setup();
this.set_up_html();
this.register_observers();
this.on_ready();
}
AbstractChosen.prototype.set_default_values = function () {
var _this = this;
this.click_test_action = function (evt) {
return _this.test_active_click(evt);
};
this.activate_action = function (evt) {
return _this.activate_field(evt);
};
this.active_field = false;
this.mouse_on_container = false;
this.results_showing = false;
this.result_highlighted = null;
this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
this.disable_search_threshold = this.options.disable_search_threshold || 0;
this.disable_search = this.options.disable_search || false;
this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
this.group_search = this.options.group_search != null ? this.options.group_search : true;
this.search_contains = this.options.search_contains || false;
this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
this.max_selected_options = this.options.max_selected_options || Infinity;
this.inherit_select_classes = this.options.inherit_select_classes || false;
this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
this.include_group_label_in_selected = this.options.include_group_label_in_selected || false;
this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY;
return this.case_sensitive_search = this.options.case_sensitive_search || false;
};
AbstractChosen.prototype.set_default_text = function () {
if (this.form_field.getAttribute("data-placeholder")) {
this.default_text = this.form_field.getAttribute("data-placeholder");
} else if (this.is_multiple) {
this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
} else {
this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
}
return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
};
AbstractChosen.prototype.choice_label = function (item) {
if (this.include_group_label_in_selected && (item.group_label != null)) {
return "<b class='group-name'>" + item.group_label + "</b>" + item.html;
} else {
return item.html;
}
};
AbstractChosen.prototype.mouse_enter = function () {
return this.mouse_on_container = true;
};
AbstractChosen.prototype.mouse_leave = function () {
return this.mouse_on_container = false;
};
AbstractChosen.prototype.input_focus = function (evt) {
var _this = this;
if (this.is_multiple) {
if (!this.active_field) {
return setTimeout((function () {
return _this.container_mousedown();
}), 50);
}
} else {
if (!this.active_field) {
return this.activate_field();
}
}
};
AbstractChosen.prototype.input_blur = function (evt) {
var _this = this;
if (!this.mouse_on_container) {
this.active_field = false;
return setTimeout((function () {
return _this.blur_test();
}), 100);
}
};
AbstractChosen.prototype.results_option_build = function (options) {
var content, data, data_content, shown_results, _i, _len, _ref;
content = '';
shown_results = 0;
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
data_content = '';
if (data.group) {
data_content = this.result_add_group(data);
} else {
data_content = this.result_add_option(data);
}
if (data_content !== '') {
shown_results++;
content += data_content;
}
if (options != null ? options.first : void 0) {
if (data.selected && this.is_multiple) {
this.choice_build(data);
} else if (data.selected && !this.is_multiple) {
this.single_set_selected_text(this.choice_label(data));
}
}
if (shown_results >= this.max_shown_results) {
break;
}
}
return content;
};
AbstractChosen.prototype.result_add_option = function (option) {
var classes, option_el;
if (!option.search_match) {
return '';
}
if (!this.include_option_in_results(option)) {
return '';
}
classes = [];
if (!option.disabled && !(option.selected && this.is_multiple)) {
classes.push("active-result");
}
if (option.disabled && !(option.selected && this.is_multiple)) {
classes.push("disabled-result");
}
if (option.selected) {
classes.push("result-selected");
}
if (option.group_array_index != null) {
classes.push("group-option");
}
if (option.classes !== "") {
classes.push(option.classes);
}
option_el = document.createElement("li");
option_el.className = classes.join(" ");
option_el.style.cssText = option.style;
option_el.setAttribute("data-option-array-index", option.array_index);
option_el.innerHTML = option.search_text;
if (option.title) {
option_el.title = option.title;
}
return this.outerHTML(option_el);
};
AbstractChosen.prototype.result_add_group = function (group) {
var classes, group_el;
if (!(group.search_match || group.group_match)) {
return '';
}
if (!(group.active_options > 0)) {
return '';
}
classes = [];
classes.push("group-result");
if (group.classes) {
classes.push(group.classes);
}
group_el = document.createElement("li");
group_el.className = classes.join(" ");
group_el.innerHTML = group.search_text;
if (group.title) {
group_el.title = group.title;
}
return this.outerHTML(group_el);
};
AbstractChosen.prototype.results_update_field = function () {
this.set_default_text();
if (!this.is_multiple) {
this.results_reset_cleanup();
}
this.result_clear_highlight();
this.results_build();
if (this.results_showing) {
return this.winnow_results();
}
};
AbstractChosen.prototype.reset_single_select_options = function () {
var result, _i, _len, _ref, _results;
_ref = this.results_data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
result = _ref[_i];
if (result.selected) {
_results.push(result.selected = false);
} else {
_results.push(void 0);
}
}
return _results;
};
AbstractChosen.prototype.results_toggle = function () {
if (this.results_showing) {
return this.results_hide();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.results_search = function (evt) {
if (this.results_showing) {
return this.winnow_results();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.winnow_results = function () {
var escapedSearchText, option, regex, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
this.no_results_clear();
results = 0;
searchText = this.get_search_text();
escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
zregex = new RegExp(escapedSearchText, 'i');
regex = this.get_search_regex(escapedSearchText);
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
option.search_match = false;
results_group = null;
if (this.include_option_in_results(option)) {
if (option.group) {
option.group_match = false;
option.active_options = 0;
}
if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
results_group = this.results_data[option.group_array_index];
if (results_group.active_options === 0 && results_group.search_match) {
results += 1;
}
results_group.active_options += 1;
}
option.search_text = option.group ? option.label : option.html;
if (!(option.group && !this.group_search)) {
option.search_match = this.search_string_match(option.search_text, regex);
if (option.search_match && !option.group) {
results += 1;
}
if (option.search_match) {
if (searchText.length) {
startpos = option.search_text.search(zregex);
text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
}
if (results_group != null) {
results_group.group_match = true;
}
} else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
option.search_match = true;
}
}
}
}
this.result_clear_highlight();
if (results < 1 && searchText.length) {
this.update_results_content("");
return this.no_results(searchText);
} else {
this.update_results_content(this.results_option_build());
return this.winnow_results_set_highlight();
}
};
AbstractChosen.prototype.get_search_regex = function (escaped_search_string) {
var regex_anchor, regex_flag;
regex_anchor = this.search_contains ? "" : "^";
regex_flag = this.case_sensitive_search ? "" : "i";
return new RegExp(regex_anchor + escaped_search_string, regex_flag);
};
AbstractChosen.prototype.search_string_match = function (search_string, regex) {
var part, parts, _i, _len;
if (regex.test(search_string)) {
return true;
} else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) {
parts = search_string.replace(/\[|\]/g, "").split(" ");
if (parts.length) {
for (_i = 0, _len = parts.length; _i < _len; _i++) {
part = parts[_i];
if (regex.test(part)) {
return true;
}
}
}
}
};
AbstractChosen.prototype.choices_count = function () {
var option, _i, _len, _ref;
if (this.selected_option_count != null) {
return this.selected_option_count;
}
this.selected_option_count = 0;
_ref = this.form_field.options;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (option.selected) {
this.selected_option_count += 1;
}
}
return this.selected_option_count;
};
AbstractChosen.prototype.choices_click = function (evt) {
evt.preventDefault();
if (!(this.results_showing || this.is_disabled)) {
return this.results_show();
}
};
AbstractChosen.prototype.keyup_checker = function (evt) {
var stroke, _ref;
stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
this.search_field_scale();
switch (stroke) {
case 8:
if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
return this.keydown_backstroke();
} else if (!this.pending_backstroke) {
this.result_clear_highlight();
return this.results_search();
}
break;
case 13:
evt.preventDefault();
if (this.results_showing) {
return this.result_select(evt);
}
break;
case 27:
if (this.results_showing) {
this.results_hide();
}
return true;
case 9:
case 38:
case 40:
case 16:
case 91:
case 17:
case 18:
break;
default:
return this.results_search();
}
};
AbstractChosen.prototype.clipboard_event_checker = function (evt) {
var _this = this;
return setTimeout((function () {
return _this.results_search();
}), 50);
};
AbstractChosen.prototype.container_width = function () {
if (this.options.width != null) {
return this.options.width;
} else {
return "" + this.form_field.offsetWidth + "px";
}
};
AbstractChosen.prototype.include_option_in_results = function (option) {
if (this.is_multiple && (!this.display_selected_options && option.selected)) {
return false;
}
if (!this.display_disabled_options && option.disabled) {
return false;
}
if (option.empty) {
return false;
}
return true;
};
AbstractChosen.prototype.search_results_touchstart = function (evt) {
this.touch_started = true;
return this.search_results_mouseover(evt);
};
AbstractChosen.prototype.search_results_touchmove = function (evt) {
this.touch_started = false;
return this.search_results_mouseout(evt);
};
AbstractChosen.prototype.search_results_touchend = function (evt) {
if (this.touch_started) {
return this.search_results_mouseup(evt);
}
};
AbstractChosen.prototype.outerHTML = function (element) {
var tmp;
if (element.outerHTML) {
return element.outerHTML;
}
tmp = document.createElement("div");
tmp.appendChild(element);
return tmp.innerHTML;
};
AbstractChosen.browser_is_supported = function () {
if ("Microsoft Internet Explorer" === window.navigator.appName) {
return document.documentMode >= 8;
}
if (/iP(od|hone)/i.test(window.navigator.userAgent) || /IEMobile/i.test(window.navigator.userAgent) || /Windows Phone/i.test(window.navigator.userAgent) || /BlackBerry/i.test(window.navigator.userAgent) || /BB10/i.test(window.navigator.userAgent) || /Android.*Mobile/i.test(window.navigator.userAgent)) {
return false;
}
return true;
};
AbstractChosen.default_multiple_text = "Select Some Options";
AbstractChosen.default_single_text = "Select an Option";
AbstractChosen.default_no_result_text = "No results match";
return AbstractChosen;
})();
$ = jQuery;
$.fn.extend({
chosen: function (options) {
if (!AbstractChosen.browser_is_supported()) {
return this;
}
return this.each(function (input_field) {
var $this, chosen;
$this = $(this);
chosen = $this.data('chosen');
if (options === 'destroy') {
if (chosen instanceof Chosen) {
chosen.destroy();
}
return;
}
if (!(chosen instanceof Chosen)) {
$this.data('chosen', new Chosen(this, options));
}
});
}
});
Chosen = (function (_super) {
__extends(Chosen, _super);
function Chosen() {
_ref = Chosen.__super__.constructor.apply(this, arguments);
return _ref;
}
Chosen.prototype.setup = function () {
this.form_field_jq = $(this.form_field);
this.current_selectedIndex = this.form_field.selectedIndex;
return this.is_rtl = this.form_field_jq.hasClass("chosen-rtl");
};
Chosen.prototype.set_up_html = function () {
var container_classes, container_props;
container_classes = ["chosen-container"];
container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
if (this.inherit_select_classes && this.form_field.className) {
container_classes.push(this.form_field.className);
}
if (this.is_rtl) {
container_classes.push("chosen-rtl");
}
container_props = {
'class': container_classes.join(' '),
'style': "width: " + (this.container_width()) + ";",
'title': this.form_field.title
};
if (this.form_field.id.length) {
container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
}
this.container = $("<div />", container_props);
if (this.is_multiple) {
this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>');
} else {
this.container.html('<a class="chosen-single chosen-default"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>');
}
this.form_field_jq.hide().after(this.container);
this.dropdown = this.container.find('div.chosen-drop').first();
this.search_field = this.container.find('input').first();
this.search_results = this.container.find('ul.chosen-results').first();
this.search_field_scale();
this.search_no_results = this.container.find('li.no-results').first();
if (this.is_multiple) {
this.search_choices = this.container.find('ul.chosen-choices').first();
this.search_container = this.container.find('li.search-field').first();
} else {
this.search_container = this.container.find('div.chosen-search').first();
this.selected_item = this.container.find('.chosen-single').first();
}
this.results_build();
this.set_tab_index();
return this.set_label_behavior();
};
Chosen.prototype.on_ready = function () {
return this.form_field_jq.trigger("chosen:ready", {
chosen: this
});
};
Chosen.prototype.register_observers = function () {
var _this = this;
this.container.bind('touchstart.chosen', function (evt) {
_this.container_mousedown(evt);
return evt.preventDefault();
});
this.container.bind('touchend.chosen', function (evt) {
_this.container_mouseup(evt);
return evt.preventDefault();
});
this.container.bind('mousedown.chosen', function (evt) {
_this.container_mousedown(evt);
});
this.container.bind('mouseup.chosen', function (evt) {
_this.container_mouseup(evt);
});
this.container.bind('mouseenter.chosen', function (evt) {
_this.mouse_enter(evt);
});
this.container.bind('mouseleave.chosen', function (evt) {
_this.mouse_leave(evt);
});
this.search_results.bind('mouseup.chosen', function (evt) {
_this.search_results_mouseup(evt);
});
this.search_results.bind('mouseover.chosen', function (evt) {
_this.search_results_mouseover(evt);
});
this.search_results.bind('mouseout.chosen', function (evt) {
_this.search_results_mouseout(evt);
});
this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen', function (evt) {
_this.search_results_mousewheel(evt);
});
this.search_results.bind('touchstart.chosen', function (evt) {
_this.search_results_touchstart(evt);
});
this.search_results.bind('touchmove.chosen', function (evt) {
_this.search_results_touchmove(evt);
});
this.search_results.bind('touchend.chosen', function (evt) {
_this.search_results_touchend(evt);
});
this.form_field_jq.bind("chosen:updated.chosen", function (evt) {
_this.results_update_field(evt);
});
this.form_field_jq.bind("chosen:activate.chosen", function (evt) {
_this.activate_field(evt);
});
this.form_field_jq.bind("chosen:open.chosen", function (evt) {
_this.container_mousedown(evt);
});
this.form_field_jq.bind("chosen:close.chosen", function (evt) {
_this.input_blur(evt);
});
this.search_field.bind('blur.chosen', function (evt) {
_this.input_blur(evt);
});
this.search_field.bind('keyup.chosen', function (evt) {
_this.keyup_checker(evt);
});
this.search_field.bind('keydown.chosen', function (evt) {
_this.keydown_checker(evt);
});
this.search_field.bind('focus.chosen', function (evt) {
_this.input_focus(evt);
});
this.search_field.bind('cut.chosen', function (evt) {
_this.clipboard_event_checker(evt);
});
this.search_field.bind('paste.chosen', function (evt) {
_this.clipboard_event_checker(evt);
});
if (this.is_multiple) {
return this.search_choices.bind('click.chosen', function (evt) {
_this.choices_click(evt);
});
} else {
return this.container.bind('click.chosen', function (evt) {
evt.preventDefault();
});
}
};
Chosen.prototype.destroy = function () {
$(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action);
if (this.search_field[0].tabIndex) {
this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex;
}
this.container.remove();
this.form_field_jq.removeData('chosen');
return this.form_field_jq.show();
};
Chosen.prototype.search_field_disabled = function () {
this.is_disabled = this.form_field_jq[0].disabled;
if (this.is_disabled) {
this.container.addClass('chosen-disabled');
this.search_field[0].disabled = true;
if (!this.is_multiple) {
this.selected_item.unbind("focus.chosen", this.activate_action);
}
return this.close_field();
} else {
this.container.removeClass('chosen-disabled');
this.search_field[0].disabled = false;
if (!this.is_multiple) {
return this.selected_item.bind("focus.chosen", this.activate_action);
}
}
};
Chosen.prototype.container_mousedown = function (evt) {
if (!this.is_disabled) {
if (evt && evt.type === "mousedown" && !this.results_showing) {
evt.preventDefault();
}
if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
if (!this.active_field) {
if (this.is_multiple) {
this.search_field.val("");
}
$(this.container[0].ownerDocument).bind('click.chosen', this.click_test_action);
this.results_show();
} else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) {
evt.preventDefault();
this.results_toggle();
}
return this.activate_field();
}
}
};
Chosen.prototype.container_mouseup = function (evt) {
if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
return this.results_reset(evt);
}
};
Chosen.prototype.search_results_mousewheel = function (evt) {
var delta;
if (evt.originalEvent) {
delta = evt.originalEvent.deltaY || -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
}
if (delta != null) {
evt.preventDefault();
if (evt.type === 'DOMMouseScroll') {
delta = delta * 40;
}
return this.search_results.scrollTop(delta + this.search_results.scrollTop());
}
};
Chosen.prototype.blur_test = function (evt) {
if (!this.active_field && this.container.hasClass("chosen-container-active")) {
return this.close_field();
}
};
Chosen.prototype.close_field = function () {
$(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action);
this.active_field = false;
this.results_hide();
this.container.removeClass("chosen-container-active");
this.clear_backstroke();
this.show_search_field_default();
return this.search_field_scale();
};
Chosen.prototype.activate_field = function () {
this.container.addClass("chosen-container-active");
this.active_field = true;
this.search_field.val(this.search_field.val());
return this.search_field.focus();
};
Chosen.prototype.test_active_click = function (evt) {
var active_container;
active_container = $(evt.target).closest('.chosen-container');
if (active_container.length && this.container[0] === active_container[0]) {
return this.active_field = true;
} else {
return this.close_field();
}
};
Chosen.prototype.results_build = function () {
this.parsing = true;
this.selected_option_count = null;
this.results_data = SelectParser.select_to_array(this.form_field);
if (this.is_multiple) {
this.search_choices.find("li.search-choice").remove();
} else if (!this.is_multiple) {
this.single_set_selected_text();
if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
this.search_field[0].readOnly = true;
this.container.addClass("chosen-container-single-nosearch");
} else {
this.search_field[0].readOnly = false;
this.container.removeClass("chosen-container-single-nosearch");
}
}
this.update_results_content(this.results_option_build({
first: true
}));
this.search_field_disabled();
this.show_search_field_default();
this.search_field_scale();
return this.parsing = false;
};
Chosen.prototype.result_do_highlight = function (el) {
var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
if (el.length) {
this.result_clear_highlight();
this.result_highlight = el;
this.result_highlight.addClass("highlighted");
maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
visible_top = this.search_results.scrollTop();
visible_bottom = maxHeight + visible_top;
high_top = this.result_highlight.position().top + this.search_results.scrollTop();
high_bottom = high_top + this.result_highlight.outerHeight();
if (high_bottom >= visible_bottom) {
return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
} else if (high_top < visible_top) {
return this.search_results.scrollTop(high_top);
}
}
};
Chosen.prototype.result_clear_highlight = function () {
if (this.result_highlight) {
this.result_highlight.removeClass("highlighted");
}
return this.result_highlight = null;
};
Chosen.prototype.results_show = function () {
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field_jq.trigger("chosen:maxselected", {
chosen: this
});
return false;
}
this.container.addClass("chosen-with-drop");
this.results_showing = true;
this.search_field.focus();
this.search_field.val(this.search_field.val());
this.winnow_results();
return this.form_field_jq.trigger("chosen:showing_dropdown", {
chosen: this
});
};
Chosen.prototype.update_results_content = function (content) {
return this.search_results.html(content);
};
Chosen.prototype.results_hide = function () {
if (this.results_showing) {
this.result_clear_highlight();
this.container.removeClass("chosen-with-drop");
this.form_field_jq.trigger("chosen:hiding_dropdown", {
chosen: this
});
}
return this.results_showing = false;
};
Chosen.prototype.set_tab_index = function (el) {
var ti;
if (this.form_field.tabIndex) {
ti = this.form_field.tabIndex;
this.form_field.tabIndex = -1;
return this.search_field[0].tabIndex = ti;
}
};
Chosen.prototype.set_label_behavior = function () {
var _this = this;
this.form_field_label = this.form_field_jq.parents("label");
if (!this.form_field_label.length && this.form_field.id.length) {
this.form_field_label = $("label[for='" + this.form_field.id + "']");
}
if (this.form_field_label.length > 0) {
return this.form_field_label.bind('click.chosen', function (evt) {
if (_this.is_multiple) {
return _this.container_mousedown(evt);
} else {
return _this.activate_field();
}
});
}
};
Chosen.prototype.show_search_field_default = function () {
if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
this.search_field.val(this.default_text);
return this.search_field.addClass("default");
} else {
this.search_field.val("");
return this.search_field.removeClass("default");
}
};
Chosen.prototype.search_results_mouseup = function (evt) {
var target;
target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
if (target.length) {
this.result_highlight = target;
this.result_select(evt);
return this.search_field.focus();
}
};
Chosen.prototype.search_results_mouseover = function (evt) {
var target;
target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
if (target) {
return this.result_do_highlight(target);
}
};
Chosen.prototype.search_results_mouseout = function (evt) {
if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) {
return this.result_clear_highlight();
}
};
Chosen.prototype.choice_build = function (item) {
var choice, close_link,
_this = this;
choice = $('<li />', {
"class": "search-choice"
}).html("<span>" + (this.choice_label(item)) + "</span>");
if (item.disabled) {
choice.addClass('search-choice-disabled');
} else {
close_link = $('<a />', {
"class": 'search-choice-close',
'data-option-array-index': item.array_index
});
close_link.bind('click.chosen', function (evt) {
return _this.choice_destroy_link_click(evt);
});
choice.append(close_link);
}
return this.search_container.before(choice);
};
Chosen.prototype.choice_destroy_link_click = function (evt) {
evt.preventDefault();
evt.stopPropagation();
if (!this.is_disabled) {
return this.choice_destroy($(evt.target));
}
};
Chosen.prototype.choice_destroy = function (link) {
if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) {
this.show_search_field_default();
if (this.is_multiple && this.choices_count() > 0 && this.search_field.val().length < 1) {
this.results_hide();
}
link.parents('li').first().remove();
return this.search_field_scale();
}
};
Chosen.prototype.results_reset = function () {
this.reset_single_select_options();
this.form_field.options[0].selected = true;
this.single_set_selected_text();
this.show_search_field_default();
this.results_reset_cleanup();
this.form_field_jq.trigger("change");
if (this.active_field) {
return this.results_hide();
}
};
Chosen.prototype.results_reset_cleanup = function () {
this.current_selectedIndex = this.form_field.selectedIndex;
return this.selected_item.find("abbr").remove();
};
Chosen.prototype.result_select = function (evt) {
var high, item;
if (this.result_highlight) {
high = this.result_highlight;
this.result_clear_highlight();
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field_jq.trigger("chosen:maxselected", {
chosen: this
});
return false;
}
if (this.is_multiple) {
high.removeClass("active-result");
} else {
this.reset_single_select_options();
}
high.addClass("result-selected");
item = this.results_data[high[0].getAttribute("data-option-array-index")];
item.selected = true;
this.form_field.options[item.options_index].selected = true;
this.selected_option_count = null;
if (this.is_multiple) {
this.choice_build(item);
} else {
this.single_set_selected_text(this.choice_label(item));
}
if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) {
this.results_hide();
}
this.show_search_field_default();
if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
this.form_field_jq.trigger("change", {
'selected': this.form_field.options[item.options_index].value
});
}
this.current_selectedIndex = this.form_field.selectedIndex;
evt.preventDefault();
return this.search_field_scale();
}
};
Chosen.prototype.single_set_selected_text = function (text) {
if (text == null) {
text = this.default_text;
}
if (text === this.default_text) {
this.selected_item.addClass("chosen-default");
} else {
this.single_deselect_control_build();
this.selected_item.removeClass("chosen-default");
}
return this.selected_item.find("span").html(text);
};
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
if (!this.form_field.options[result_data.options_index].disabled) {
result_data.selected = false;
this.form_field.options[result_data.options_index].selected = false;
this.selected_option_count = null;
this.result_clear_highlight();
if (this.results_showing) {
this.winnow_results();
}
this.form_field_jq.trigger("change", {
deselected: this.form_field.options[result_data.options_index].value
});
this.search_field_scale();
return true;
} else {
return false;
}
};
Chosen.prototype.single_deselect_control_build = function () {
if (!this.allow_single_deselect) {
return;
}
if (!this.selected_item.find("abbr").length) {
this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
}
return this.selected_item.addClass("chosen-single-with-deselect");
};
Chosen.prototype.get_search_text = function () {
return $('<div/>').text($.trim(this.search_field.val())).html();
};
Chosen.prototype.winnow_results_set_highlight = function () {
var do_high, selected_results;
selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
if (do_high != null) {
return this.result_do_highlight(do_high);
}
};
Chosen.prototype.no_results = function (terms) {
var no_results_html;
no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
no_results_html.find("span").first().html(terms);
this.search_results.append(no_results_html);
return this.form_field_jq.trigger("chosen:no_results", {
chosen: this
});
};
Chosen.prototype.no_results_clear = function () {
return this.search_results.find(".no-results").remove();
};
Chosen.prototype.keydown_arrow = function () {
var next_sib;
if (this.results_showing && this.result_highlight) {
next_sib = this.result_highlight.nextAll("li.active-result").first();
if (next_sib) {
return this.result_do_highlight(next_sib);
}
} else {
return this.results_show();
}
};
Chosen.prototype.keyup_arrow = function () {
var prev_sibs;
if (!this.results_showing && !this.is_multiple) {
return this.results_show();
} else if (this.result_highlight) {
prev_sibs = this.result_highlight.prevAll("li.active-result");
if (prev_sibs.length) {
return this.result_do_highlight(prev_sibs.first());
} else {
if (this.choices_count() > 0) {
this.results_hide();
}
return this.result_clear_highlight();
}
}
};
Chosen.prototype.keydown_backstroke = function () {
var next_available_destroy;
if (this.pending_backstroke) {
this.choice_destroy(this.pending_backstroke.find("a").first());
return this.clear_backstroke();
} else {
next_available_destroy = this.search_container.siblings("li.search-choice").last();
if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
this.pending_backstroke = next_available_destroy;
if (this.single_backstroke_delete) {
return this.keydown_backstroke();
} else {
return this.pending_backstroke.addClass("search-choice-focus");
}
}
}
};
Chosen.prototype.clear_backstroke = function () {
if (this.pending_backstroke) {
this.pending_backstroke.removeClass("search-choice-focus");
}
return this.pending_backstroke = null;
};
Chosen.prototype.keydown_checker = function (evt) {
var stroke, _ref1;
stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode;
this.search_field_scale();
if (stroke !== 8 && this.pending_backstroke) {
this.clear_backstroke();
}
switch (stroke) {
case 8:
this.backstroke_length = this.search_field.val().length;
break;
case 9:
if (this.results_showing && !this.is_multiple) {
this.result_select(evt);
}
this.mouse_on_container = false;
break;
case 13:
if (this.results_showing) {
evt.preventDefault();
}
break;
case 32:
if (this.disable_search) {
evt.preventDefault();
}
break;
case 38:
evt.preventDefault();
this.keyup_arrow();
break;
case 40:
evt.preventDefault();
this.keydown_arrow();
break;
}
};
Chosen.prototype.search_field_scale = function () {
var div, f_width, h, style, style_block, styles, w, _i, _len;
if (this.is_multiple) {
h = 0;
w = 0;
style_block = "position:absolute; left: -1000px; top: -1000px; display:none;";
styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
for (_i = 0, _len = styles.length; _i < _len; _i++) {
style = styles[_i];
style_block += style + ":" + this.search_field.css(style) + ";";
}
div = $('<div />', {
'style': style_block
});
div.text(this.search_field.val());
$('body').append(div);
w = div.width() + 25;
div.remove();
f_width = this.container.outerWidth();
if (w > f_width - 10) {
w = f_width - 10;
}
return this.search_field.css({
'width': w + 'px'
});
}
};
return Chosen;
})(AbstractChosen);
}).call(this);
|
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "paddle/phi/core/dense_tensor.h"
namespace phi {
template <typename T, typename Context>
void LayerNormGradKernel(const Context& ctx,
const DenseTensor& x,
paddle::optional<const DenseTensor&> scale,
paddle::optional<const DenseTensor&> bias,
const DenseTensor& mean,
const DenseTensor& variance,
const DenseTensor& out_grad,
float epsilon,
int begin_norm_axis,
bool is_test,
DenseTensor* x_grad,
DenseTensor* scale_grad,
DenseTensor* bias_grad);
} // namespace phi
|
import torch
import numpy as np
def get_positional_table(d_pos_vec, n_position=1024):
position_enc = np.array([
[pos / np.power(10000, 2*i/d_pos_vec) for i in range(d_pos_vec)]
if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)])
position_enc[1:, 0::2] = np.sin(position_enc[1:, 0::2]) # dim 2i
position_enc[1:, 1::2] = np.cos(position_enc[1:, 1::2]) # dim 2i+1
return torch.from_numpy(position_enc).type(torch.FloatTensor)
def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None):
''' Sinusoid position encoding table '''
def cal_angle(position, hid_idx):
return position / np.power(10000, 2 * (hid_idx // 2) / d_hid)
def get_posi_angle_vec(position):
return [cal_angle(position, hid_j) for hid_j in range(d_hid)]
sinusoid_table = np.array([get_posi_angle_vec(pos_i)
for pos_i in range(n_position)])
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
if padding_idx is not None:
# zero vector for padding dimension
sinusoid_table[padding_idx] = 0.
return torch.FloatTensor(sinusoid_table)
|
import time,requests,subprocess,select,re,yaml
TARGET_FILE='/var/log/apache2/access.log'
ip_re = re.compile("(\d{1,3}\.){3}\d{1,3}")
payload_re = re.compile("^.+\.hta.+$")
headers = {'Content-Type' : 'application/x-www-form-urlencoded'}
try:
conf = yaml.safe_load(open('config.yaml'))
except IOError as e:
print(dir(e))
quit("Error opening config file. Does it exist?")
try:
file = subprocess.Popen(['tail', '-f', '-n', '0', TARGET_FILE], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = select.poll()
p.register(file.stdout)
source_ips = []
while True:
if p.poll(1):
line = file.stdout.readline().strip()
parts = line.split()
ip_result = ip_re.search(line)
payload_result = payload_re.search(line)
if ip_result and payload_result:
for usertoken in conf['usertokens'].keys():
ip_info = requests.get("https://ipinfo.io/%s" % ip_result.group().strip()).json()
payload = {'token' : conf['apptoken']}
payload.update({'user' : usertoken})
payload.update({'title' : 'New Payload Notification'})
payload.update({'sound' : 'cashregister'})
payload.update({'priority' : '1'})
payload.update({'message' : 'The payload has been accessed!\nIP: %s | Location: %s, %s | Org: %s' % (ip_info['ip'], ip_info['city'], ip_info['region'], ip_info['org'])})
r = requests.post('https://api.pushover.net/1/messages', headers=headers, data=payload)
elif ip_result and not payload_result:
for usertoken in conf['usertokens'].keys():
if ip_result.group() not in source_ips:
ip_info = requests.get("https://ipinfo.io/%s" % ip_result.group().strip()).json()
payload = {'token' : conf['apptoken']}
payload.update({'user' : usertoken})
payload.update({'title' : 'New IP Notification'})
payload.update({'sound' : 'cashregister'})
payload.update({'message' : 'IP: %s | Location: %s, %s | Org: %s' % (ip_info['ip'], ip_info['city'], ip_info['region'], ip_info['org'])})
r = requests.post('https://api.pushover.net/1/messages', headers=headers, data=payload)
source_ips.append(ip_result.group())
time.sleep(1)
except IOError as e:
quit("Quitting due to IOError: %s." % e.strerror)
except KeyboardInterrupt:
exit("Cleaning up...")
|
"use strict"
const fs = require('fs');
const path = require('path');
var print = {};
var cssPagedMedia = (function() {
var style = document.createElement('style');
document.head.appendChild(style);
return function(rule) {
style.innerHTML = rule;
};
}());
print.toPDF = (filename, filepath) => {
if (!filename.endsWith('.pdf')) {
filename = filename + '.pdf'
}
var viewDescription = $('#pdf-description').prop('checked');
var configElectron = require(path.join(app.dataPath, 'config', 'electron.json'));
let {
width,
height,
} = configElectron.windowBounds;
$('#description').parents('.visible-print').attr('style', 'display:block!important')
var offsetHeight = $('#description')[0].offsetHeight;
$('#description').parents('.visible-print').attr('style', '')
// var pageWidth = width - 319 + 240 + 50;
var pageWidth = width + 50;
var pageHeight = 90 + (viewDescription ? height + offsetHeight : height);
var dataDialog = $('#data-dialog').hasClass('in');
if (dataDialog) {
$('#data-dialog').removeClass('fade')
$('#data-dialog').modal('hide')
}
$('#description').toggle(viewDescription)
$('#description').css('margin-top', (height - 30) + 'px')
cssPagedMedia('@page {size: ' + pageWidth + 'px ' + pageHeight + 'px' + '}');
require('electron').remote.require('./main').printToPDF(path.join(filepath, filename))
setTimeout(() => {
app.message.show('Info', 'PDF successfully saved.')
$('#description').attr('style', '')
if (dataDialog) {
$('#data-dialog').modal('show')
$('#data-dialog').addClass('fade')
}
}, 200)
}
print.events = () => {
$('.printToPDF').on('click', (e) => {
var configApp = app.config.app();
var filename = app.data._id + '.pdf';
var filepath = path.join(app.dataPath, 'exports');
$('#pdf-form #pdf-filename').val(filename).focus();
$('#pdf-form #pdf-filepath').val(filepath);
$('#pdf-description').prop('checked', app.data.description != undefined)
$('#pdf-description').prop('disabled', app.data.description == undefined)
})
$('#pdf-submit').on('click', function(e) {
var filename = $('#pdf-form #pdf-filename').val();
var filepath = $('#pdf-form #pdf-filepath').val();
print.toPDF(filename, filepath);
})
}
module.exports = print;
|
import NoCache from "./cache/no-cache";
import InMemoryCache from "./cache/in-memory-cache";
import LocalStorageCache from "./cache/local-storage-cache";
const encode = encodeURIComponent;
const formatUrl = (method, query) => {
const queryStr = Object.keys(query)
.map((key) => {
const val = query[key];
if (val === undefined) { return ""; }
if (val === null) { return encode(key); }
return encode(key) + "=" + encode(val);
}).join("&");
return `https://translate.yandex.net/api/v1.5/tr.json/${method}?${queryStr}`;
};
const methodType = {
TRANSLATE: "translate",
DETECT: "detect"
};
const cacheType = {
NONE: "none",
IN_MEMORY: "in-memory",
LOCAL_STORAGE: "local-storage"
};
class TranslateService {
constructor(apiKey, supportedLangs, cache = cacheType.IN_MEMORY) {
this.apiKey = apiKey;
this.supportedLangs = supportedLangs || [];
switch (cache) {
case cacheType.IN_MEMORY:
this.cache = new InMemoryCache();
break;
case cacheType.LOCAL_STORAGE:
this.cache = new LocalStorageCache();
break;
case cacheType.NONE:
default:
this.cache = new NoCache();
}
}
isSupported(lang) {
return (!!lang && this.supportedLangs[lang]);
}
translate(phrase, lang) {
if (!phrase || !lang || !this.isSupported(lang)) {
return Promise.resolve(phrase);
}
const cached = this.cache.get(phrase, lang);
if (cached && cached.length > 0) {
return Promise.resolve(cached);
}
const request = {
text: phrase,
lang: lang
};
return this.fetchData(methodType.TRANSLATE, request)
.then((data) => {
const translation = data.text[0];
this.cache.put(phrase, lang, translation);
return translation;
})
.catch((err) => {
console.error(err);
return phrase;
});
}
detect(phrase, ...hints) {
const request = { text: phrase };
if (!!hints && hints.length) {
request["hint"] = hints.join(",");
}
return this.fetchData(methodType.DETECT, request)
.then((data) => data.lang);
}
fetchData(method, request) {
request["key"] = this.apiKey;
const url = formatUrl(method, request);
return fetch(url, { method: "POST" })
.then((response) => response.json())
.then((data) => {
if (data.code !== 200) {
throw new Error(`Failed request for ${method}. Status code: ${data.code}`);
}
return data;
});
}
};
export default TranslateService;
|
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: tower_job_template
author: "Wayne Witzel III (@wwitzel3)"
short_description: create, update, or destroy Ansible Tower job templates.
description:
- Create, update, or destroy Ansible Tower job templates. See
U(https://www.ansible.com/tower) for an overview.
options:
name:
description:
- Name to use for the job template.
required: True
type: str
new_name:
description:
- Setting this option will change the existing name (looed up via the name field.
type: str
description:
description:
- Description to use for the job template.
type: str
job_type:
description:
- The job type to use for the job template.
choices: ["run", "check"]
type: str
inventory:
description:
- Name of the inventory to use for the job template.
type: str
organization:
description:
- Organization the job template exists in.
- Used to help lookup the object, cannot be modified using this module.
- The Organization is inferred from the associated project
- If not provided, will lookup by name only, which does not work with duplicates.
- Requires Tower Version 3.7.0 or AWX 10.0.0 IS NOT backwards compatible with earlier versions.
type: str
project:
description:
- Name of the project to use for the job template.
type: str
playbook:
description:
- Path to the playbook to use for the job template within the project provided.
type: str
credential:
description:
- Name of the credential to use for the job template.
- Deprecated, use 'credentials'.
type: str
credentials:
description:
- List of credentials to use for the job template.
type: list
elements: str
vault_credential:
description:
- Name of the vault credential to use for the job template.
- Deprecated, use 'credentials'.
type: str
execution_environment:
description:
- Execution Environment to use for the JT.
type: str
forks:
description:
- The number of parallel or simultaneous processes to use while executing the playbook.
type: int
limit:
description:
- A host pattern to further constrain the list of hosts managed or affected by the playbook
type: str
verbosity:
description:
- Control the output level Ansible produces as the playbook runs. 0 - Normal, 1 - Verbose, 2 - More Verbose, 3 - Debug, 4 - Connection Debug.
choices: [0, 1, 2, 3, 4]
default: 0
type: int
extra_vars:
description:
- Specify C(extra_vars) for the template.
type: dict
job_tags:
description:
- Comma separated list of the tags to use for the job template.
type: str
force_handlers:
description:
- Enable forcing playbook handlers to run even if a task fails.
type: bool
default: 'no'
aliases:
- force_handlers_enabled
skip_tags:
description:
- Comma separated list of the tags to skip for the job template.
type: str
start_at_task:
description:
- Start the playbook at the task matching this name.
type: str
diff_mode:
description:
- Enable diff mode for the job template.
type: bool
aliases:
- diff_mode_enabled
default: 'no'
use_fact_cache:
description:
- Enable use of fact caching for the job template.
type: bool
default: 'no'
aliases:
- fact_caching_enabled
host_config_key:
description:
- Allow provisioning callbacks using this host config key.
type: str
ask_scm_branch_on_launch:
description:
- Prompt user for (scm branch) on launch.
type: bool
default: 'False'
ask_diff_mode_on_launch:
description:
- Prompt user to enable diff mode (show changes) to files when supported by modules.
type: bool
default: 'False'
aliases:
- ask_diff_mode
ask_variables_on_launch:
description:
- Prompt user for (extra_vars) on launch.
type: bool
default: 'False'
aliases:
- ask_extra_vars
ask_limit_on_launch:
description:
- Prompt user for a limit on launch.
type: bool
default: 'False'
aliases:
- ask_limit
ask_tags_on_launch:
description:
- Prompt user for job tags on launch.
type: bool
default: 'False'
aliases:
- ask_tags
ask_skip_tags_on_launch:
description:
- Prompt user for job tags to skip on launch.
type: bool
default: 'False'
aliases:
- ask_skip_tags
ask_job_type_on_launch:
description:
- Prompt user for job type on launch.
type: bool
default: 'False'
aliases:
- ask_job_type
ask_verbosity_on_launch:
description:
- Prompt user to choose a verbosity level on launch.
type: bool
default: 'False'
aliases:
- ask_verbosity
ask_inventory_on_launch:
description:
- Prompt user for inventory on launch.
type: bool
default: 'False'
aliases:
- ask_inventory
ask_credential_on_launch:
description:
- Prompt user for credential on launch.
type: bool
default: 'False'
aliases:
- ask_credential
survey_enabled:
description:
- Enable a survey on the job template.
type: bool
default: 'no'
survey_spec:
description:
- JSON/YAML dict formatted survey definition.
type: dict
become_enabled:
description:
- Activate privilege escalation.
type: bool
default: 'no'
allow_simultaneous:
description:
- Allow simultaneous runs of the job template.
type: bool
default: 'no'
aliases:
- concurrent_jobs_enabled
timeout:
description:
- Maximum time in seconds to wait for a job to finish (server-side).
type: int
job_slice_count:
description:
- The number of jobs to slice into at runtime. Will cause the Job Template to launch a workflow if value is greater than 1.
type: int
default: '1'
webhook_service:
description:
- Service that webhook requests will be accepted from
type: str
choices:
- ''
- 'github'
- 'gitlab'
webhook_credential:
description:
- Personal Access Token for posting back the status to the service API
type: str
scm_branch:
description:
- Branch to use in job run. Project default used if blank. Only allowed if project allow_override field is set to true.
type: str
default: ''
labels:
description:
- The labels applied to this job template
type: list
elements: str
state:
description:
- Desired state of the resource.
default: "present"
choices: ["present", "absent"]
type: str
notification_templates_started:
description:
- list of notifications to send on start
type: list
elements: str
notification_templates_success:
description:
- list of notifications to send on success
type: list
elements: str
notification_templates_error:
description:
- list of notifications to send on error
type: list
elements: str
extends_documentation_fragment: awx.awx.auth
notes:
- JSON for survey_spec can be found in Tower API Documentation. See
U(https://docs.ansible.com/ansible-tower/latest/html/towerapi/api_ref.html#/Job_Templates/Job_Templates_job_templates_survey_spec_create)
for POST operation payload example.
'''
EXAMPLES = '''
- name: Create Tower Ping job template
tower_job_template:
name: "Ping"
job_type: "run"
organization: "Default"
inventory: "Local"
project: "Demo"
playbook: "ping.yml"
credentials:
- "Local"
state: "present"
tower_config_file: "~/tower_cli.cfg"
survey_enabled: yes
survey_spec: "{{ lookup('file', 'my_survey.json') }}"
- name: Add start notification to Job Template
tower_job_template:
name: "Ping"
notification_templates_started:
- Notification1
- Notification2
- name: Remove Notification1 start notification from Job Template
tower_job_template:
name: "Ping"
notification_templates_started:
- Notification2
'''
from ..module_utils.tower_api import TowerAPIModule
import json
def update_survey(module, last_request):
spec_endpoint = last_request.get('related', {}).get('survey_spec')
if module.params.get('survey_spec') == {}:
response = module.delete_endpoint(spec_endpoint)
if response['status_code'] != 200:
# Not sure how to make this actually return a non 200 to test what to dump in the respinse
module.fail_json(msg="Failed to delete survey: {0}".format(response['json']))
else:
response = module.post_endpoint(spec_endpoint, **{'data': module.params.get('survey_spec')})
if response['status_code'] != 200:
module.fail_json(msg="Failed to update survey: {0}".format(response['json']['error']))
module.exit_json(**module.json_output)
def main():
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
name=dict(required=True),
new_name=dict(),
description=dict(),
organization=dict(),
job_type=dict(choices=['run', 'check']),
inventory=dict(),
project=dict(),
playbook=dict(),
credential=dict(),
vault_credential=dict(),
credentials=dict(type='list', elements='str'),
execution_environment=dict(),
forks=dict(type='int'),
limit=dict(),
verbosity=dict(type='int', choices=[0, 1, 2, 3, 4], default=0),
extra_vars=dict(type='dict'),
job_tags=dict(),
force_handlers=dict(type='bool', default=False, aliases=['force_handlers_enabled']),
skip_tags=dict(),
start_at_task=dict(),
timeout=dict(type='int', default=0),
use_fact_cache=dict(type='bool', aliases=['fact_caching_enabled']),
host_config_key=dict(),
ask_diff_mode_on_launch=dict(type='bool', aliases=['ask_diff_mode']),
ask_variables_on_launch=dict(type='bool', aliases=['ask_extra_vars']),
ask_limit_on_launch=dict(type='bool', aliases=['ask_limit']),
ask_tags_on_launch=dict(type='bool', aliases=['ask_tags']),
ask_skip_tags_on_launch=dict(type='bool', aliases=['ask_skip_tags']),
ask_job_type_on_launch=dict(type='bool', aliases=['ask_job_type']),
ask_verbosity_on_launch=dict(type='bool', aliases=['ask_verbosity']),
ask_inventory_on_launch=dict(type='bool', aliases=['ask_inventory']),
ask_credential_on_launch=dict(type='bool', aliases=['ask_credential']),
survey_enabled=dict(type='bool'),
survey_spec=dict(type="dict"),
become_enabled=dict(type='bool'),
diff_mode=dict(type='bool', aliases=['diff_mode_enabled']),
allow_simultaneous=dict(type='bool', aliases=['concurrent_jobs_enabled']),
scm_branch=dict(),
ask_scm_branch_on_launch=dict(type='bool'),
job_slice_count=dict(type='int', default='1'),
webhook_service=dict(choices=['github', 'gitlab', '']),
webhook_credential=dict(),
labels=dict(type="list", elements='str'),
notification_templates_started=dict(type="list", elements='str'),
notification_templates_success=dict(type="list", elements='str'),
notification_templates_error=dict(type="list", elements='str'),
state=dict(choices=['present', 'absent'], default='present'),
)
# Create a module for ourselves
module = TowerAPIModule(argument_spec=argument_spec)
# Extract our parameters
name = module.params.get('name')
new_name = module.params.get("new_name")
state = module.params.get('state')
# Deal with legacy credential and vault_credential
credential = module.params.get('credential')
vault_credential = module.params.get('vault_credential')
credentials = module.params.get('credentials')
if vault_credential:
if credentials is None:
credentials = []
credentials.append(vault_credential)
if credential:
if credentials is None:
credentials = []
credentials.append(credential)
new_fields = {}
search_fields = {}
# Attempt to look up the related items the user specified (these will fail the module if not found)
organization_id = None
organization = module.params.get('organization')
if organization:
organization_id = module.resolve_name_to_id('organizations', organization)
search_fields['organization'] = new_fields['organization'] = organization_id
ee = module.params.get('execution_environment')
if ee:
new_fields['execution_environment'] = module.resolve_name_to_id('execution_environments', ee)
# Attempt to look up an existing item based on the provided data
existing_item = module.get_one('job_templates', name_or_id=name, **{'data': search_fields})
if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
module.delete_if_needed(existing_item)
# Create the data that gets sent for create and update
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
for field_name in (
'description', 'job_type', 'playbook', 'scm_branch', 'forks', 'limit', 'verbosity',
'job_tags', 'force_handlers', 'skip_tags', 'start_at_task', 'timeout', 'use_fact_cache',
'host_config_key', 'ask_scm_branch_on_launch', 'ask_diff_mode_on_launch', 'ask_variables_on_launch',
'ask_limit_on_launch', 'ask_tags_on_launch', 'ask_skip_tags_on_launch', 'ask_job_type_on_launch',
'ask_verbosity_on_launch', 'ask_inventory_on_launch', 'ask_credential_on_launch', 'survey_enabled',
'become_enabled', 'diff_mode', 'allow_simultaneous', 'job_slice_count', 'webhook_service',
):
field_val = module.params.get(field_name)
if field_val is not None:
new_fields[field_name] = field_val
# Special treatment of extra_vars parameter
extra_vars = module.params.get('extra_vars')
if extra_vars is not None:
new_fields['extra_vars'] = json.dumps(extra_vars)
# Attempt to look up the related items the user specified (these will fail the module if not found)
inventory = module.params.get('inventory')
project = module.params.get('project')
webhook_credential = module.params.get('webhook_credential')
if inventory is not None:
new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory)
if project is not None:
if organization_id is not None:
project_data = module.get_one('projects', name_or_id=project, **{
'data': {
'organization': organization_id,
}
})
if project_data is None:
module.fail_json(msg="The project {0} in organization {1} was not found on the Tower server".format(
project, organization
))
new_fields['project'] = project_data['id']
else:
new_fields['project'] = module.resolve_name_to_id('projects', project)
if webhook_credential is not None:
new_fields['webhook_credential'] = module.resolve_name_to_id('credentials', webhook_credential)
association_fields = {}
if credentials is not None:
association_fields['credentials'] = []
for item in credentials:
association_fields['credentials'].append(module.resolve_name_to_id('credentials', item))
labels = module.params.get('labels')
if labels is not None:
association_fields['labels'] = []
for item in labels:
association_fields['labels'].append(module.resolve_name_to_id('labels', item))
# Code to use once Issue #7567 is resolved
# search_fields = {'name': item}
# if organization:
# search_fields['organization'] = organization_id
# label_id = module.get_one('labels', **{'data': search_fields})
# association_fields['labels'].append(label_id)
notifications_start = module.params.get('notification_templates_started')
if notifications_start is not None:
association_fields['notification_templates_started'] = []
for item in notifications_start:
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
notifications_success = module.params.get('notification_templates_success')
if notifications_success is not None:
association_fields['notification_templates_success'] = []
for item in notifications_success:
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
notifications_error = module.params.get('notification_templates_error')
if notifications_error is not None:
association_fields['notification_templates_error'] = []
for item in notifications_error:
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
on_change = None
new_spec = module.params.get('survey_spec')
if new_spec is not None:
existing_spec = None
if existing_item:
spec_endpoint = existing_item.get('related', {}).get('survey_spec')
existing_spec = module.get_endpoint(spec_endpoint)['json']
if new_spec != existing_spec:
module.json_output['changed'] = True
if existing_item and module.has_encrypted_values(existing_spec):
module._encrypted_changed_warning('survey_spec', existing_item, warning=True)
on_change = update_survey
# If the state was present and we can let the module build or update the existing item, this will return on its own
module.create_or_update_if_needed(
existing_item, new_fields,
endpoint='job_templates', item_type='job_template',
associations=association_fields,
on_create=on_change, on_update=on_change,
)
if __name__ == '__main__':
main()
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from './components/home/App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register();
|
/* libhs - public domain
Niels Martignène <niels.martignene@protonmail.com>
https://koromix.dev/libhs
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy,
distribute, and modify this file as you see fit.
See the LICENSE file for more details. */
#ifdef _WIN32
#include "common_priv.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
_HS_BEGIN_C
#include <hidsdi.h>
_HS_END_C
#include <winioctl.h>
#include "device_priv.h"
#include "hid.h"
#include "platform.h"
// Copied from hidclass.h in the MinGW-w64 headers
#define HID_OUT_CTL_CODE(id) \
CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
#define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
ssize_t hs_hid_read(hs_port *port, uint8_t *buf, size_t size, int timeout)
{
assert(port);
assert(port->dev->type == HS_DEVICE_TYPE_HID);
assert(port->mode & HS_PORT_MODE_READ);
assert(buf);
assert(size);
if (port->u.handle.read_status < 0) {
// Could be a transient error, try to restart it
_hs_win32_start_async_read(port);
if (port->u.handle.read_status < 0)
return port->u.handle.read_status;
}
_hs_win32_finalize_async_read(port, timeout);
if (port->u.handle.read_status <= 0)
return port->u.handle.read_status;
/* HID communication is message-based. So if the caller does not provide a big enough
buffer, we can just discard the extra data, unlike for serial communication. */
if (port->u.handle.read_len) {
if (size > port->u.handle.read_len)
size = port->u.handle.read_len;
memcpy(buf, port->u.handle.read_buf, size);
} else {
size = 0;
}
hs_error_mask(HS_ERROR_IO);
_hs_win32_start_async_read(port);
hs_error_unmask();
return (ssize_t)size;
}
ssize_t hs_hid_write(hs_port *port, const uint8_t *buf, size_t size)
{
assert(port);
assert(port->dev->type == HS_DEVICE_TYPE_HID);
assert(port->mode & HS_PORT_MODE_WRITE);
assert(buf);
if (size < 2)
return 0;
ssize_t r = _hs_win32_write_sync(port, buf, size, 5000);
if (!r)
return hs_error(HS_ERROR_IO, "Timed out while writing to '%s'", port->dev->path);
return r;
}
ssize_t hs_hid_get_feature_report(hs_port *port, uint8_t report_id, uint8_t *buf, size_t size)
{
assert(port);
assert(port->dev->type == HS_DEVICE_TYPE_HID);
assert(port->mode & HS_PORT_MODE_READ);
assert(buf);
assert(size);
OVERLAPPED ov = {0};
DWORD len;
BOOL success;
buf[0] = report_id;
len = (DWORD)size;
success = DeviceIoControl(port->u.handle.h, IOCTL_HID_GET_FEATURE, buf, (DWORD)size, buf,
(DWORD)size, NULL, &ov);
if (!success && GetLastError() != ERROR_IO_PENDING) {
CancelIo(port->u.handle.h);
return hs_error(HS_ERROR_IO, "I/O error while writing to '%s'", port->dev->path);
}
success = GetOverlappedResult(port->u.handle.h, &ov, &len, TRUE);
if (!success)
return hs_error(HS_ERROR_IO, "I/O error while writing to '%s'", port->dev->path);
/* Apparently the length returned by the IOCTL_HID_GET_FEATURE ioctl does not account
for the report ID byte. */
return (ssize_t)len + 1;
}
ssize_t hs_hid_send_feature_report(hs_port *port, const uint8_t *buf, size_t size)
{
assert(port);
assert(port->dev->type == HS_DEVICE_TYPE_HID);
assert(port->mode & HS_PORT_MODE_WRITE);
assert(buf);
if (size < 2)
return 0;
// Timeout behavior?
BOOL success = HidD_SetFeature(port->u.handle.h, (char *)buf, (DWORD)size);
if (!success)
return hs_error(HS_ERROR_IO, "I/O error while writing to '%s'", port->dev->path);
return (ssize_t)size;
}
#endif
|
# Copyright 2020 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pytest
CIRQ_MAINTAINERS = ('TEAM', "@quantumlib/cirq-maintainers")
BASE_MAINTAINERS = {CIRQ_MAINTAINERS, ('USERNAME', "@vtomole"), ('USERNAME', "@cduck")}
DOCS_MAINTAINERS = BASE_MAINTAINERS.union({('USERNAME', '@rmlarose')})
GOOGLE_TEAM = {('USERNAME', "@wcourtney")}
GOOGLE_MAINTAINERS = BASE_MAINTAINERS.union(GOOGLE_TEAM)
IONQ_TEAM = {('USERNAME', u) for u in ["@dabacon", "@ColemanCollins", "@nakardo", "@gmauricio"]}
IONQ_MAINTAINERS = BASE_MAINTAINERS.union(IONQ_TEAM)
PASQAL_TEAM = {('USERNAME', u) for u in ["@HGSilveri"]}
PASQAL_MAINTAINERS = BASE_MAINTAINERS.union(PASQAL_TEAM)
AQT_TEAM = {('USERNAME', u) for u in ["@ma5x", "@pschindler", "@alfrisch"]}
AQT_MAINTAINERS = BASE_MAINTAINERS.union(AQT_TEAM)
QCVV_TEAM = {('USERNAME', "@mrwojtek")}
QCVV_MAINTAINERS = BASE_MAINTAINERS.union(QCVV_TEAM)
@pytest.mark.parametrize(
"filepath,expected",
[
("setup.py", BASE_MAINTAINERS),
("dev_tools/codeowners_test.py", BASE_MAINTAINERS),
("cirq-core/setup.py", BASE_MAINTAINERS),
("cirq-core/cirq/contrib/__init__.py", BASE_MAINTAINERS),
("docs/_book.yaml", DOCS_MAINTAINERS),
# qcvv
("cirq-core/cirq/experiments/__init__.py", QCVV_MAINTAINERS),
("docs/qcvv/isolated_xeb.ipynb", QCVV_MAINTAINERS.union(DOCS_MAINTAINERS)),
# aqt
("cirq-aqt/cirq_aqt/__init__.py", AQT_MAINTAINERS),
("cirq-aqt/setup.py", AQT_MAINTAINERS),
("docs/aqt/access.md", AQT_MAINTAINERS.union(DOCS_MAINTAINERS)),
("docs/tutorials/aqt/getting_started.ipynb", AQT_MAINTAINERS.union(DOCS_MAINTAINERS)),
# pasqal
("cirq-pasqal/cirq_pasqal/__init__.py", PASQAL_MAINTAINERS),
("cirq-pasqal/setup.py", PASQAL_MAINTAINERS),
("docs/pasqal/access.md", PASQAL_MAINTAINERS.union(DOCS_MAINTAINERS)),
("docs/tutorials/pasqal/getting_started.ipynb", PASQAL_MAINTAINERS.union(DOCS_MAINTAINERS)),
# ionq
("cirq-ionq/cirq_ionq/__init__.py", IONQ_MAINTAINERS),
("cirq-ionq/setup.py", IONQ_MAINTAINERS),
("docs/ionq/access.md", IONQ_MAINTAINERS.union(DOCS_MAINTAINERS)),
("docs/tutorials/ionq/getting_started.ipynb", IONQ_MAINTAINERS.union(DOCS_MAINTAINERS)),
# google
("cirq-google/cirq_google/__init__.py", GOOGLE_MAINTAINERS),
("cirq-google/setup.py", GOOGLE_MAINTAINERS),
("docs/google/access.md", GOOGLE_MAINTAINERS.union(DOCS_MAINTAINERS)),
("docs/tutorials/google/start.ipynb", GOOGLE_MAINTAINERS.union(DOCS_MAINTAINERS)),
],
)
def test_codeowners(filepath, expected):
# for some reason the codeowners library does not publish all the wheels
# for Mac and Windows. Eventually we could write our own codeowners parser,
# but for now it is good enough. If codeowners is not installed, this test
# will be skipped
codeowners = pytest.importorskip("codeowners")
with open(".github/CODEOWNERS") as f:
owners = codeowners.CodeOwners(f.read())
assert os.path.exists(
filepath
), f"{filepath} should exist to avoid creating/maintaining meaningless codeowners rules."
assert set(owners.of(filepath)) == expected
|
# Copyright 2020 The GPflow Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
from typing import Callable, Iterable, Union
import tensorflow as tf
from ..base import TensorType
class GaussianQuadrature:
"""
Abstract class implementing quadrature methods to compute Gaussian Expectations.
Inheriting classes must provide the method _build_X_W to create points and weights
to be used for quadrature.
"""
@abc.abstractmethod
def _build_X_W(self, mean: TensorType, var: TensorType):
raise NotImplementedError
def __call__(self, fun, mean, var, *args, **kwargs):
r"""
Compute the Gaussian Expectation of a function f:
X ~ N(mean, var)
E[f(X)] = ∫f(x, *args, **kwargs)p(x)dx
Using the formula:
E[f(X)] = sum_{i=1}^{N_quad_points} f(x_i) * w_i
where x_i, w_i must be provided by the inheriting class through self._build_X_W.
The computations broadcast along batch-dimensions, represented by [b1, b2, ..., bX].
:param fun: Callable or Iterable of Callables that operates elementwise, with
signature f(X, *args, **kwargs). Moreover, it must satisfy the shape-mapping:
X shape: [N_quad_points, b1, b2, ..., bX, d],
usually [N_quad_points, N, d]
f(X) shape: [N_quad_points, b1, b2, ...., bX, d'],
usually [N_quad_points, N, 1] or [N_quad_points, N, d]
In most cases, f should only operate over the last dimension of X
:param mean: Array/Tensor with shape [b1, b2, ..., bX, d], usually [N, d],
representing the mean of a d-Variate Gaussian distribution
:param var: Array/Tensor with shape b1, b2, ..., bX, d], usually [N, d],
representing the variance of a d-Variate Gaussian distribution
:param *args: Passed to fun
:param **kargs: Passed to fun
:return: Array/Tensor with shape [b1, b2, ...., bX, d'],
usually [N, d] or [N, 1]
"""
X, W = self._build_X_W(mean, var)
if isinstance(fun, Iterable):
return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=0) for f in fun]
return tf.reduce_sum(fun(X, *args, **kwargs) * W, axis=0)
def logspace(self, fun: Union[Callable, Iterable[Callable]], mean, var, *args, **kwargs):
r"""
Compute the Gaussian log-Expectation of a the exponential of a function f:
X ~ N(mean, var)
log E[exp[f(X)]] = log ∫exp[f(x, *args, **kwargs)]p(x)dx
Using the formula:
log E[exp[f(X)]] = log sum_{i=1}^{N_quad_points} exp[f(x_i) + log w_i]
where x_i, w_i must be provided by the inheriting class through self._build_X_W.
The computations broadcast along batch-dimensions, represented by [b1, b2, ..., bX].
:param fun: Callable or Iterable of Callables that operates elementwise, with
signature f(X, *args, **kwargs). Moreover, it must satisfy the shape-mapping:
X shape: [N_quad_points, b1, b2, ..., bX, d],
usually [N_quad_points, N, d]
f(X) shape: [N_quad_points, b1, b2, ...., bX, d'],
usually [N_quad_points, N, 1] or [N_quad_points, N, d]
In most cases, f should only operate over the last dimension of X
:param mean: Array/Tensor with shape [b1, b2, ..., bX, d], usually [N, d],
representing the mean of a d-Variate Gaussian distribution
:param var: Array/Tensor with shape b1, b2, ..., bX, d], usually [N, d],
representing the variance of a d-Variate Gaussian distribution
:param *args: Passed to fun
:param **kargs: Passed to fun
:return: Array/Tensor with shape [b1, b2, ...., bX, d'],
usually [N, d] or [N, 1]
"""
X, W = self._build_X_W(mean, var)
logW = tf.math.log(W)
if isinstance(fun, Iterable):
return [tf.reduce_logsumexp(f(X, *args, **kwargs) + logW, axis=0) for f in fun]
return tf.reduce_logsumexp(fun(X, *args, **kwargs) + logW, axis=0)
|
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'Lighthouse'
copyright = '2018, the Lighthouse Authors, see the AUTHORS file'
author = 'the Lighthouse Authors, see the AUTHORS file'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = '0.1.0'
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
highlight_language = 'none'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
#html_theme = 'alabaster'
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Lighthousedoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Lighthouse.tex', 'Lighthouse Documentation',
'the Lighthouse Authors, see the AUTHORS.md file', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'lighthouse', 'Lighthouse Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Lighthouse', 'Lighthouse Documentation',
author, 'Lighthouse', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
|
!function(a){function b(a,b,c,d){this.bubbles=!1,this.cancelBubble=!1,this.cancelable=!1,this.data=b||null,this.origin=c||"",this.lastEventId=d||"",this.type=a||"message"}function c(){return window.XDomainRequest&&window.XMLHttpRequest&&void 0===(new XMLHttpRequest).responseType?!0:!1}if(!a.EventSource||a._eventSourceImportPrefix){var d=(a._eventSourceImportPrefix||"")+"EventSource",e=function(a,b){if(!a||"string"!=typeof a)throw new SyntaxError("Not enough arguments");this.URL=a,this.setOptions(b);var c=this;setTimeout(function(){c.poll()},0)};if(e.prototype={CONNECTING:0,OPEN:1,CLOSED:2,defaultOptions:{loggingEnabled:!1,loggingPrefix:"eventsource",interval:500,bufferSizeLimit:262144,silentTimeout:3e5,getArgs:{evs_buffer_size_limit:262144},xhrHeaders:{Accept:"text/event-stream","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"}},setOptions:function(a){var b,c=this.defaultOptions;for(b in c)c.hasOwnProperty(b)&&(this[b]=c[b]);for(b in a)b in c&&a.hasOwnProperty(b)&&(this[b]=a[b]);this.getArgs&&this.bufferSizeLimit&&(this.getArgs.evs_buffer_size_limit=this.bufferSizeLimit),("undefined"==typeof console||"undefined"==typeof console.log)&&(this.loggingEnabled=!1)},log:function(a){this.loggingEnabled&&console.log("["+this.loggingPrefix+"]:"+a)},poll:function(){try{if(this.readyState==this.CLOSED)return;this.cleanup(),this.readyState=this.CONNECTING,this.cursor=0,this.cache="",this._xhr=new this.XHR(this),this.resetNoActivityTimer()}catch(a){this.log("There were errors inside the pool try-catch"),this.dispatchEvent("error",{type:"error",data:a.message})}},pollAgain:function(a){var b=this;b.readyState=b.CONNECTING,b.dispatchEvent("error",{type:"error",data:"Reconnecting "}),this._pollTimer=setTimeout(function(){b.poll()},a||0)},cleanup:function(){this.log("evs cleaning up"),this._pollTimer&&(clearInterval(this._pollTimer),this._pollTimer=null),this._noActivityTimer&&(clearInterval(this._noActivityTimer),this._noActivityTimer=null),this._xhr&&(this._xhr.abort(),this._xhr=null)},resetNoActivityTimer:function(){if(this.silentTimeout){this._noActivityTimer&&clearInterval(this._noActivityTimer);var a=this;this._noActivityTimer=setTimeout(function(){a.log("Timeout! silentTImeout:"+a.silentTimeout),a.pollAgain()},this.silentTimeout)}},close:function(){this.readyState=this.CLOSED,this.log("Closing connection. readyState: "+this.readyState),this.cleanup()},ondata:function(){var a=this._xhr;if(a.isReady()&&!a.hasError()){this.resetNoActivityTimer(),this.readyState==this.CONNECTING&&(this.readyState=this.OPEN,this.dispatchEvent("open",{type:"open"}));var b=a.getBuffer();b.length>this.bufferSizeLimit&&(this.log("buffer.length > this.bufferSizeLimit"),this.pollAgain()),0==this.cursor&&b.length>0&&""==b.substring(0,1)&&(this.cursor=1);var c=this.lastMessageIndex(b);if(c[0]>=this.cursor){var d=c[1],e=b.substring(this.cursor,d);this.parseStream(e),this.cursor=d}a.isDone()&&(this.log("request.isDone(). reopening the connection"),this.pollAgain(this.interval))}else this.readyState!==this.CLOSED&&(this.log("this.readyState !== this.CLOSED"),this.pollAgain(this.interval))},parseStream:function(a){a=this.cache+this.normalizeToLF(a);var c,d,e,f,g,h,i=a.split("\n\n");for(c=0;c<i.length-1;c++){for(e="message",f=[],parts=i[c].split("\n"),d=0;d<parts.length;d++)g=this.trimWhiteSpace(parts[d]),0==g.indexOf("event")?e=g.replace(/event:?\s*/,""):0==g.indexOf("retry")?(h=parseInt(g.replace(/retry:?\s*/,"")),isNaN(h)||(this.interval=h)):0==g.indexOf("data")?f.push(g.replace(/data:?\s*/,"")):0==g.indexOf("id:")?this.lastEventId=g.replace(/id:?\s*/,""):0==g.indexOf("id")&&(this.lastEventId=null);if(f.length){var j=new b(e,f.join("\n"),window.location.origin,this.lastEventId);this.dispatchEvent(e,j)}}this.cache=i[i.length-1]},dispatchEvent:function(a,b){var c=this["_"+a+"Handlers"];if(c)for(var d=0;d<c.length;d++)c[d].call(this,b);this["on"+a]&&this["on"+a].call(this,b)},addEventListener:function(a,b){this["_"+a+"Handlers"]||(this["_"+a+"Handlers"]=[]),this["_"+a+"Handlers"].push(b)},removeEventListener:function(a,b){var c=this["_"+a+"Handlers"];if(c)for(var d=c.length-1;d>=0;--d)if(c[d]===b){c.splice(d,1);break}},_pollTimer:null,_noactivityTimer:null,_xhr:null,lastEventId:null,cache:"",cursor:0,onerror:null,onmessage:null,onopen:null,readyState:0,urlWithParams:function(a,b){var c=[];if(b){var d,e,f=encodeURIComponent;for(d in b)b.hasOwnProperty(d)&&(e=f(d)+"="+f(b[d]),c.push(e))}return c.length>0?-1==a.indexOf("?")?a+"?"+c.join("&"):a+"&"+c.join("&"):a},lastMessageIndex:function(a){var b=a.lastIndexOf("\n\n"),c=a.lastIndexOf("\r\r"),d=a.lastIndexOf("\r\n\r\n");return d>Math.max(b,c)?[d,d+4]:[Math.max(b,c),Math.max(b,c)+2]},trimWhiteSpace:function(a){var b=/^(\s|\u00A0)+|(\s|\u00A0)+$/g;return a.replace(b,"")},normalizeToLF:function(a){return a.replace(/\r\n|\r/g,"\n")}},c()){e.isPolyfill="IE_8-9";var f=e.prototype.defaultOptions;f.xhrHeaders=null,f.getArgs.evs_preamble=2056,e.prototype.XHR=function(a){request=new XDomainRequest,this._request=request,request.onprogress=function(){request._ready=!0,a.ondata()},request.onload=function(){this._loaded=!0,a.ondata()},request.onerror=function(){this._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"XDomainRequest error"})},request.ontimeout=function(){this._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"XDomainRequest timed out"})};var b={};if(a.getArgs){var c=a.getArgs;for(var d in c)c.hasOwnProperty(d)&&(b[d]=c[d]);a.lastEventId&&(b.evs_last_event_id=a.lastEventId)}request.open("GET",a.urlWithParams(a.URL,b)),request.send()},e.prototype.XHR.prototype={useXDomainRequest:!0,_request:null,_ready:!1,_loaded:!1,_failed:!1,isReady:function(){return this._request._ready},isDone:function(){return this._request._loaded},hasError:function(){return this._request._failed},getBuffer:function(){var a="";try{a=this._request.responseText||""}catch(b){}return a},abort:function(){this._request&&this._request.abort()}}}else e.isPolyfill="XHR",e.prototype.XHR=function(a){request=new XMLHttpRequest,this._request=request,a._xhr=this,request.onreadystatechange=function(){request.readyState>1&&a.readyState!=a.CLOSED&&(200==request.status||request.status>=300&&request.status<400?a.ondata():(request._failed=!0,a.readyState=a.CLOSED,a.dispatchEvent("error",{type:"error",data:"The server responded with "+request.status}),a.close()))},request.onprogress=function(){},request.open("GET",a.urlWithParams(a.URL,a.getArgs),!0);var b=a.xhrHeaders;for(var c in b)b.hasOwnProperty(c)&&request.setRequestHeader(c,b[c]);a.lastEventId&&request.setRequestHeader("Last-Event-Id",a.lastEventId),request.send()},e.prototype.XHR.prototype={useXDomainRequest:!1,_request:null,_failed:!1,isReady:function(){return this._request.readyState>=2},isDone:function(){return 4==this._request.readyState},hasError:function(){return this._failed||this._request.status>=400},getBuffer:function(){var a="";try{a=this._request.responseText||""}catch(b){}return a},abort:function(){this._request&&this._request.abort()}};a[d]=e}}(this);
|
// @flow
import React from 'react';
import get from 'lodash/get';
import colours from '../../styles/colours.less';
import Icon from '../Icon';
type Props = {
data?: {
name: string,
icon: string,
details: {
infix_upgrade: {
buff: {
description: Array<string>,
},
},
},
},
};
const Infusion = ({ data }: Props) => {
if (!data) {
return (
<div>
<span>Unused Infusion Slot</span>
</div>
);
}
return (
<div className={colours.blue}>
<div>
<Icon src={data.icon} size="micro" />
<span> {data.name}</span>
</div>
<div>
{get(data.details, 'infix_upgrade.buff.description', [])
.map((text) => <div key={text}>{text}</div>)}
</div>
</div>
);
};
export default Infusion;
|
class MouseActionConverter(TypeConverter):
"""
Converts a System.Windows.Input.MouseAction object to and from other types.
MouseActionConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: MouseActionConverter,context: ITypeDescriptorContext,sourceType: Type) -> bool
Determines whether an object of the specified type can be converted to an
instance of System.Windows.Input.MouseAction,using the specified context.
context: A format context that provides information about the environment from which
this converter is being invoked.
sourceType: The type being evaluated for conversion.
Returns: true if this converter can perform the operation; otherwise,false.
"""
pass
def CanConvertTo(self,*__args):
"""
CanConvertTo(self: MouseActionConverter,context: ITypeDescriptorContext,destinationType: Type) -> bool
Determines whether an instance of System.Windows.Input.MouseAction can be
converted to the specified type,using the specified context.
context: A format context that provides information about the environment from which
this converter is being invoked.
destinationType: The type being evaluated for conversion.
Returns: true if this converter can perform the operation; otherwise,false.
"""
pass
def ConvertFrom(self,*__args):
"""
ConvertFrom(self: MouseActionConverter,context: ITypeDescriptorContext,culture: CultureInfo,source: object) -> object
Attempts to convert the specified object to a System.Windows.Input.MouseAction,
using the specified context.
context: A format context that provides information about the environment from which
this converter is being invoked.
culture: Culture specific information.
source: The object to convert.
Returns: The converted object.
"""
pass
def ConvertTo(self,*__args):
"""
ConvertTo(self: MouseActionConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object
Attempts to convert a System.Windows.Input.MouseAction to the specified type,
using the specified context.
context: A format context that provides information about the environment from which
this converter is being invoked.
culture: Culture specific information.
value: The object to convert.
destinationType: The type to convert the object to.
Returns: The converted object.
"""
pass
|
#!/usr/bin/env python
####################
# Required Modules #
####################
# Generic/Built-in
import asyncio
import json
import os
import shutil
from pathlib import Path
from typing import Dict, List, Any
# Libs
import aiohttp
import mlflow
import torch as th
# Custom
from rest_rpc import app
from rest_rpc.training.core.utils import (
UrlConstructor,
RPCFormatter,
Orchestrator
)
from synarchive.connection import ExperimentRecords, RunRecords
from synarchive.training import ModelRecords
from synarchive.evaluation import MLFRecords
##################
# Configurations #
##################
SOURCE_FILE = os.path.abspath(__file__)
schemas = app.config['SCHEMAS']
db_path = app.config['DB_PATH']
out_dir = app.config['OUT_DIR']
mlflow_dir = app.config['MLFLOW_DIR']
logging = app.config['NODE_LOGGER'].synlog
logging.debug("evaluation/core/utils.py logged", Description="No Changes")
####################
# Helper Functions #
####################
def replicate_combination_key(expt_id, run_id):
return str((expt_id, run_id))
############################################
# Inference Orchestration class - Analyser #
############################################
class Analyser(Orchestrator):
"""
Takes in a list of minibatch IDs and sends them to worker nodes. Workers
will use these IDs to reconstruct their aggregated test datasets with
prediction labels mapped appropriately.
Attributes:
inferences (dict(str, dict(str, dict(str, th.tensor)))
"""
def __init__(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str,
inferences: dict,
metas: list = ['train', 'evaluate', 'predict'],
auto_align: bool = True
):
super().__init__()
self.metas = metas
self.collab_id = collab_id
self.project_id = project_id
self.expt_id = expt_id
self.run_id = run_id
self.inferences = inferences
self.auto_align = auto_align
###########
# Helpers #
###########
async def _poll_for_stats(
self,
node_info: Dict[str, Any],
inferences: Dict[str, Dict[str, th.Tensor]]
):
""" Parses a registration record for participant metadata, before
submitting minibatch IDs of inference objects to corresponding
worker node's REST-RPC service for calculating descriptive
statistics and prediction exports
Args:
reg_record (tinydb.database.Document): Participant-project details
inferences (dict): List of dicts containing inference object IDs
Returns:
Statistics (dict)
"""
_, _, participant_id = self.parse_keys(node_info)
if not inferences:
return {participant_id: {meta:{} for meta in self.metas}}
# Construct destination url for interfacing with worker REST-RPC
rest_connection = self.parse_rest_info(node_info)
destination_constructor = UrlConstructor(**rest_connection)
destination_url = destination_constructor.construct_predict_url(
collab_id=self.collab_id,
project_id=self.project_id,
expt_id=self.expt_id,
run_id=self.run_id
)
ml_action = self.parse_action(node_info)
data_tags = self.parse_tags(node_info)
data_alignments = self.parse_alignments(node_info, self.auto_align)
payload = {
'action': ml_action,
'tags': data_tags,
'alignments': data_alignments,
'inferences': inferences
}
# Trigger remote inference by posting alignments & ID mappings to
# `Predict` route in worker
resp_inference_data, status_code = await self.instruct(
command='post',
url=destination_url,
payload=payload
)
logging.debug(
f"Participant '{participant_id}' >|< Project '{self.project_id}' -> Experiment '{self.expt_id}' -> Run '{self.run_id}': Polled statistics tracked.",
description=f"Polled statistics for participant '{participant_id}' under project '{self.project_id}' using experiment '{self.expt_id}' and run '{self.run_id}' tracked.",
resp_json=resp_inference_data,
ID_path=SOURCE_FILE,
ID_class=Analyser.__name__,
ID_function=Analyser._poll_for_stats.__name__
)
# Extract the relevant expt-run results
expt_run_key = replicate_combination_key(self.expt_id, self.run_id)
metadata = resp_inference_data['results'][expt_run_key]
# Filter by selected meta-datasets
filtered_statistics = {
meta: stats
for meta, stats in metadata.items()
if meta in self.metas
}
return {participant_id: filtered_statistics}
async def _collect_all_stats(self, grid: List[Dict[str, Any]]) -> dict:
""" Asynchronous function to submit inference data to registered
participant servers in return for remote performance statistics
Args:
grid (list(dict))): Registry of participants' node information
Returns:
All participants' statistics (dict)
"""
###########################
# Implementation Footnote #
###########################
# [Causes]
# Node info retrieved is asynmetric as compared to input inferences.
# [Problems]
# Zipping causes misallocation of dataset inferences to the wrong
# servers, resulting in a "ValueError: Found input variables with
# inconsistent numbers of samples: [N1, N2]", since prediction counts
# obtained are not aligned with label counts in the remote servers
# [Solution]
# Pair things up via manual matching
mapped_pairs = [
(record, inferences)
for worker_id, inferences in self.inferences.items()
for record in grid
if self.parse_syft_info(record).get('id') == worker_id
]
logging.debug(f"Mapped pairs: {mapped_pairs}")
all_statistics = {}
for future in asyncio.as_completed(
map(lambda args: self._poll_for_stats(*args), mapped_pairs)
):
result = await future
all_statistics.update(result)
return all_statistics
##################
# Core Functions #
##################
def infer(self, grid: List[Dict[str, Any]]) -> dict:
""" Wrapper function for triggering asychroneous remote inferencing of
participant nodes
Args:
grid (list(dict))): Registry of participants' node information
Returns:
All participants' statistics (dict)
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
all_stats = loop.run_until_complete(
self._collect_all_stats(grid=grid)
)
finally:
loop.close()
return all_stats
####################################
# MLFLow logging class - MLFlogger #
####################################
class MLFlogger:
"""
Wrapper class around MLFlow to faciliate experiment & run registrations in
the REST-RPC setting, where statistical logging is performed during
post-mortem analysis
"""
def __init__(self, db_path: str = db_path, remote_uri: str = None):
# Private attributes
self.__rpc_formatter = RPCFormatter()
self.__expt_records = ExperimentRecords(db_path=db_path)
self.__run_records = RunRecords(db_path=db_path)
self.__model_records = ModelRecords(db_path=db_path)
self.__connector = "_>_"
# Public attributes
self.mlf_records = MLFRecords(db_path=db_path)
self.db_path = db_path
self.remote_uri = remote_uri
###########
# Helpers #
###########
def _generate_expt_name(
self,
collab_id: str,
project_id: str,
expt_id: str
) -> str:
""" Abstracts creation of a unique key to identify an MLFlow experiment.
This collapses the payload hierarchy so that only one MLFlow instance
is required to host all runs registered under collaboration(s)
Args:
collab_id (str): ID of collaboration
project_id (str): ID of project
expt_id (str): ID of experiment
Returns:
Experiment name (str)
"""
return self.__connector.join([collab_id, project_id, expt_id])
def _generate_run_name(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str
) -> str:
""" Abstracts creation of a unique key to identify an MLFlow run.
Args:
collab_id (str): ID of collaboration
project_id (str): ID of project
expt_id (str): ID of experiment
run_id (str): ID of run
Returns:
Run name (str)
"""
return run_id # keeping it simple
def _generate_record_name(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str = "",
mlflow_type: str = "experiment"
):
""" Abstracts creation of a unique key to partition experiments & runs
internally within the context of MLFlow.
Args:
collab_id (str): ID of collaboration
project_id (str): ID of project
expt_id (str): ID of experiment
run_id (str): ID of run
mlflow_type (str): Type of entity to be represented in MLFlow
Returns:
Record name (str)
"""
###########################
# Implementation Footnote #
###########################
# [Causes]
# In MLFlow, only experiments and runs are mappable/usable to the
# Synergos hierarchy. In order to simplify the deployment process,
# collaborations & projects are collapsed in as part of an MLFlow's
# experiment, allowing a single instance of MLFlow to host results &
# analysis of results across the grid.
# [Problems]
# The collapsed hierarchy becomes ambigious due to the inability to
# distinguish between a Synergos experiment and a Synergos run.
# [Solution]
# Use expt_id and run_id to create a unique composite key for use when
# storing mapping details between MLFlow and Synergos.
if mlflow_type == "experiment":
return expt_id
elif mlflow_type == "run":
return self.__connector.join([expt_id, run_id])
else:
raise RuntimeError("Unsupported entity specified!")
def retrieve_mlflow_experiment(
self,
collab_id: str,
project_id: str,
expt_id: str,
) -> Dict[str, str]:
"""
"""
expt_name = self._generate_expt_name(collab_id, project_id, expt_id)
expt_record_name = self._generate_record_name(
collab_id, project_id, expt_id,
mlflow_type="experiment"
)
expt_mlflow_record = self.mlf_records.read(
collaboration=collab_id,
project=project_id,
record=expt_record_name,
name=expt_name
)
return expt_mlflow_record
def retrieve_mlflow_run(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str
) -> Dict[str, str]:
"""
"""
run_name = self._generate_run_name(collab_id, project_id, expt_id, run_id)
run_record_name = self._generate_record_name(
collab_id, project_id, expt_id, run_id,
mlflow_type="run"
)
run_mlflow_record = self.mlf_records.read(
collaboration=collab_id,
project=project_id,
record=run_record_name,
name=run_name
)
return run_mlflow_record
def initialise_mlflow_experiment(
self,
collab_id: str,
project_id: str,
expt_id: str,
tracking_uri: str
) -> Dict[str, str]:
""" Initialises an MLFlow experiment at the specified project URI
Args:
project_id (str): REST-RPC ID of specified project
expt_id (str): REST-RPC ID of specified experiment
Returns:
MLFlow Experiment configuration (dict)
"""
mlflow.set_tracking_uri(tracking_uri)
expt_name = self._generate_expt_name(collab_id, project_id, expt_id)
expt_record_name = self._generate_record_name(
collab_id, project_id, expt_id,
mlflow_type="experiment"
)
expt_mlflow_record = self.mlf_records.read(
collaboration=collab_id,
project=project_id,
record=expt_record_name,
name=expt_name
)
# Check if MLFlow experiment has already been created. Create a
# MLFRecord if:
# 1) No previous records for this combination key was initialized
# 2) Specified tracking URI has changed
if not expt_mlflow_record:
# Initialise MLFlow experiment
mlflow_id = mlflow.create_experiment(name=expt_name)
mlflow_details = {
'collaboration': collab_id,
'project': project_id,
'record': expt_record_name,
'name': expt_name,
'mlflow_type': 'experiment',
'mlflow_id': mlflow_id,
'mlflow_uri': tracking_uri # Overridable with remote > local
}
expt_mlflow_record = self.mlf_records.create(
collaboration=collab_id,
project=project_id,
record=expt_record_name,
name=expt_name,
details=mlflow_details
)
# Update URI if necessary
if expt_mlflow_record.get('mlflow_uri') != tracking_uri:
expt_mlflow_record = self.mlf_records.update(
collaboration=collab_id,
project=project_id,
record=expt_record_name,
name=expt_name,
updates={'mlflow_uri': tracking_uri}
)
stripped_expt_mlflow_details = self.__rpc_formatter.strip_keys(
record=expt_mlflow_record
)
return stripped_expt_mlflow_details
def initialise_mlflow_run(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str
) -> Dict[str, str]:
""" Initialises a MLFLow run under a specified experiment of a project.
Initial run hyperparameters will be logged, and MLFlow run id will
be stored for subsequent analysis.
Args:
project_id (str): REST-RPC ID of specified project
expt_id (str): REST-RPC ID of specified experiment
run_id (str): REST-RPC ID of specified run
"""
# Retrieve parent MLFlow experiment metadata (if available)
expt_mlflow_record = self.retrieve_mlflow_experiment(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id
)
expt_mlflow_id = expt_mlflow_record.get('mlflow_id')
expt_mlflow_uri = expt_mlflow_record.get('mlflow_uri')
if not expt_mlflow_id:
logging.error(
"MLFlow experiment has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.initialise_mlflow_run.__name__
)
raise RuntimeError("MLFlow experiment has not been initialised!")
run_name = self._generate_run_name(collab_id, project_id, expt_id, run_id)
run_record_name = self._generate_record_name(
collab_id, project_id, expt_id, run_id,
mlflow_type="run"
)
run_mlflow_record = self.mlf_records.read(
collaboration=collab_id,
project=project_id,
record=run_record_name,
name=run_name
)
if not run_mlflow_record:
with mlflow.start_run(
experiment_id=expt_mlflow_id,
run_name=run_name
) as mlf_run:
# Retrieve run details from database
run_details = self.__run_records.read(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
stripped_run_details = self.__rpc_formatter.strip_keys(
record=run_details,
concise=True
)
mlflow.log_params(stripped_run_details)
# Save the MLFlow ID mapping
run_mlflow_id = mlf_run.info.run_id
run_mlflow_details = {
'collaboration': collab_id,
'project': project_id,
'record': run_record_name,
'name': run_name,
'mlflow_type': 'run',
'mlflow_id': run_mlflow_id,
'mlflow_uri': expt_mlflow_record['mlflow_uri'] # same as expt
}
run_mlflow_record = self.mlf_records.create(
collaboration=collab_id,
project=project_id,
record=run_record_name,
name=run_name,
details=run_mlflow_details
)
if run_mlflow_record.get('mlflow_uri') != expt_mlflow_uri:
run_mlflow_record = self.mlf_records.update(
collaboration=collab_id,
project=project_id,
record=run_record_name,
name=run_name,
updates={'mlflow_uri': expt_mlflow_record['mlflow_uri']}
)
stripped_run_mlflow_details = self.__rpc_formatter.strip_keys(
record=run_mlflow_record
)
return stripped_run_mlflow_details
def log_losses(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str
):
""" Registers all cached losses, be it global or local, obtained from
federated training into MLFlow.
Args:
project_id (str): REST-RPC ID of specified project
expt_id (str): REST-RPC ID of specified experiment
run_id (str): REST-RPC ID of specified run
Returns:
Stripped metadata (dict)
"""
# Retrieve parent MLFlow experiment metadata (if available)
expt_mlflow_record = self.retrieve_mlflow_experiment(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id
)
expt_mlflow_id = expt_mlflow_record.get('mlflow_id')
if not expt_mlflow_id:
logging.error(
"MLFlow experiment has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow experiment has not been initialised!")
# Search for run session to update entry, not create a new one
run_mlflow_record = self.retrieve_mlflow_run(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
run_mlflow_id = run_mlflow_record.get('mlflow_id')
if not run_mlflow_id:
logging.error(
"MLFlow run has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow run has not been initialised!")
# Retrieve all model metadata from storage
model_metadata = self.__model_records.read(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
stripped_metadata = self.__rpc_formatter.strip_keys(
record=model_metadata,
concise=True
) if model_metadata else model_metadata
if stripped_metadata:
with mlflow.start_run(
experiment_id=expt_mlflow_id,
run_id=run_mlflow_id # continue existing run
) as mlf_run:
# Extract loss histories
for m_type, metadata in stripped_metadata.items():
loss_history_path = metadata['loss_history']
origin = metadata['origin']
with open(loss_history_path, 'r') as lh:
loss_history = json.load(lh)
if m_type == 'global':
for meta, losses in loss_history.items():
for round_idx, loss, in losses.items():
mlflow.log_metric(
key=f"global_{meta}_loss",
value=loss,
step=int(round_idx)
)
else:
for round_idx, loss, in losses.items():
mlflow.log_metric(
key=f"{origin}_local_loss",
value=loss,
step=int(round_idx)
)
return stripped_metadata
def log_model_performance(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str,
statistics: dict
) -> dict:
""" Using all cached model checkpoints, log the performance statistics
of models, be it global or local, to MLFlow at round (for global) or
epoch (for local) level.
Args:
project_id (str): REST-RPC ID of specified project
expt_id (str): REST-RPC ID of specified experiment
run_id (str): REST-RPC ID of specified run
statistics (dict): Inference statistics polled from workers
Returns:
MLFLow run details (dict)
"""
# Retrieve parent MLFlow experiment metadata (if available)
expt_mlflow_record = self.retrieve_mlflow_experiment(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id
)
expt_mlflow_id = expt_mlflow_record.get('mlflow_id')
if not expt_mlflow_id:
logging.error(
"MLFlow experiment has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow experiment has not been initialised!")
# Search for run session to update entry, not create a new one
run_mlflow_record = self.retrieve_mlflow_run(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
run_mlflow_id = run_mlflow_record.get('mlflow_id')
if not run_mlflow_id:
logging.error(
"MLFlow run has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow run has not been initialised!")
with mlflow.start_run(
experiment_id=expt_mlflow_id,
run_id=run_mlflow_id
) as mlf_run:
# Store output metadata into database
for _, inference_stats in statistics.items():
for _, meta_stats in inference_stats.items():
# Log statistics to MLFlow for analysis
stats = meta_stats.get('statistics', {})
for stat_type, stat_value in stats.items():
if isinstance(stat_value, list):
for val_idx, value in enumerate(stat_value):
mlflow.log_metric(
key=f"{stat_type}_class_{val_idx}",
value=value,
step=int(val_idx+1)
)
else:
mlflow.log_metric(key=stat_type, value=stat_value)
stripped_mlflow_run_details = self.__rpc_formatter.strip_keys(
run_mlflow_record,
concise=True
)
return stripped_mlflow_run_details
def log_artifacts(
self,
collab_id: str,
project_id: str,
expt_id: str,
run_id: str
) -> str:
""" Log all artifacts produced (i.e. local & global models, losses etc.)
during the specified federated run.
Args:
project_id (str): REST-RPC ID of specified project
expt_id (str): REST-RPC ID of specified experiment
run_id (str): REST-RPC ID of specified run
statistics (dict): Inference statistics polled from workers
Returns:
MLFLow run details (dict)
"""
# Retrieve parent MLFlow experiment metadata (if available)
expt_mlflow_record = self.retrieve_mlflow_experiment(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id
)
expt_mlflow_id = expt_mlflow_record.get('mlflow_id')
if not expt_mlflow_id:
logging.error(
"MLFlow experiment has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow experiment has not been initialised!")
# Search for run session to update entry, not create a new one
run_mlflow_record = self.retrieve_mlflow_run(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
run_mlflow_id = run_mlflow_record.get('mlflow_id')
if not run_mlflow_id:
logging.error(
"MLFlow run has not been initialised!",
ID_path=SOURCE_FILE,
ID_class=MLFlogger.__name__,
ID_function=MLFlogger.log_losses.__name__
)
raise RuntimeError("MLFlow run has not been initialised!")
with mlflow.start_run(
experiment_id=expt_mlflow_id,
run_id=run_mlflow_id # continue existing run
) as mlf_run:
results_dir = os.path.join(out_dir, collab_id, project_id, expt_id, run_id)
mlflow.log_artifacts(local_dir=results_dir)
return results_dir
##################
# Core Functions #
##################
def log(self, accumulations: dict) -> List[str]:
""" Wrapper function that processes statistics accumulated from
inference.
Args:
accumulations (dict): Accumulated statistics from inferring
different project-expt-run combinations
Returns:
List of MLFlow run IDs from all runs executed (list(str))
"""
###########################
# Implementation Footnote #
###########################
# [Causes]
# Depending on where your MLFlow logs are, the accessibility of the
# resource changes.
# [Problems]
# As Synergos MLOps is an optional component, the orchestrator may or
# may not install it. Also, depending on the location of deployment
# (i.e. local filesystem vs remote tracking server), connection URI
# may vary.
# [Solution]
# By default, ALWAYS generate local MLFlow caches. If a remote tracking
# URI was specified, then attempt to send logs over. That way, clients
# will always have the option of choosing which way they would to serve
# their MLOps information
has_remote_tracking = self.remote_uri is not None
tracking_uris = (
[mlflow_dir, self.remote_uri]
if has_remote_tracking
else [mlflow_dir]
)
jobs_ran = []
for tracking_uri in tracking_uris:
for combination_key, statistics in accumulations.items():
collab_id, project_id, expt_id, run_id = combination_key
self.initialise_mlflow_experiment(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
tracking_uri=tracking_uri
)
run_mlflow_details = self.initialise_mlflow_run(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
self.log_losses(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
self.log_model_performance(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id,
statistics=statistics
)
self.log_artifacts(
collab_id=collab_id,
project_id=project_id,
expt_id=expt_id,
run_id=run_id
)
if run_mlflow_details['mlflow_id'] not in jobs_ran:
jobs_ran.append(run_mlflow_details['mlflow_id'])
return jobs_ran
|
/*
* This source file is part of the EdgeDB open source project.
*
* Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef EDGE_DATATYPES_H
#define EDGE_DATATYPES_H
#include <stdint.h>
#include "Python.h"
#define EDGE_MAX_TUPLE_SIZE (0x4000 - 1)
#define EDGE_POINTER_IS_IMPLICIT (1 << 0)
#define EDGE_POINTER_IS_LINKPROP (1 << 1)
#define EDGE_POINTER_IS_LINK (1 << 2)
/* === edgedb.RecordDesc ==================================== */
extern PyTypeObject EdgeRecordDesc_Type;
#define EdgeRecordDesc_Check(d) (Py_TYPE(d) == &EdgeRecordDesc_Type)
typedef enum {
UNKNOWN = 0,
NO_RESULT,
AT_MOST_ONE,
ONE,
MANY,
AT_LEAST_ONE
} EdgeFieldCardinality;
typedef struct {
uint32_t flags;
EdgeFieldCardinality cardinality;
} EdgeRecordFieldDesc;
typedef struct {
PyObject_HEAD
PyObject *index;
PyObject *names;
EdgeRecordFieldDesc *descs;
Py_ssize_t idpos;
Py_ssize_t size;
} EdgeRecordDescObject;
typedef enum {
L_ERROR,
L_NOT_FOUND,
L_LINKPROP,
L_PROPERTY,
L_LINK
} edge_attr_lookup_t;
PyObject * EdgeRecordDesc_InitType(void);
PyObject * EdgeRecordDesc_New(PyObject *, PyObject *, PyObject *);
PyObject * EdgeRecordDesc_PointerName(PyObject *, Py_ssize_t);
Py_ssize_t EdgeRecordDesc_IDPos(PyObject *ob);
int EdgeRecordDesc_PointerIsLinkProp(PyObject *, Py_ssize_t);
int EdgeRecordDesc_PointerIsLink(PyObject *, Py_ssize_t);
int EdgeRecordDesc_PointerIsImplicit(PyObject *, Py_ssize_t);
EdgeFieldCardinality EdgeRecordDesc_PointerCardinality(PyObject *, Py_ssize_t);
Py_ssize_t EdgeRecordDesc_GetSize(PyObject *);
edge_attr_lookup_t EdgeRecordDesc_Lookup(PyObject *, PyObject *, Py_ssize_t *);
PyObject * EdgeRecordDesc_List(PyObject *, uint8_t, uint8_t);
/* === edgedb.Tuple ========================================= */
#define EDGE_TUPLE_FREELIST_SIZE 500
#define EDGE_TUPLE_FREELIST_MAXSAVE 20
extern PyTypeObject EdgeTuple_Type;
#define EdgeTuple_Check(d) (Py_TYPE(d) == &EdgeTuple_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *weakreflist;
PyObject *ob_item[1];
} EdgeTupleObject;
PyObject * EdgeTuple_InitType(void);
PyObject * EdgeTuple_New(Py_ssize_t size);
int EdgeTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
/* === edgedb.NamedTuple ==================================== */
#define EDGE_NAMEDTUPLE_FREELIST_SIZE 500
#define EDGE_NAMEDTUPLE_FREELIST_MAXSAVE 20
extern PyTypeObject EdgeNamedTuple_Type;
#define EdgeNamedTuple_Check(d) (Py_TYPE(d) == &EdgeNamedTuple_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *desc;
PyObject *weakreflist;
PyObject *ob_item[1];
} EdgeNamedTupleObject;
PyObject * EdgeNamedTuple_InitType(void);
PyObject * EdgeNamedTuple_New(PyObject *);
int EdgeNamedTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
/* === edgedb.Object ======================================== */
#define EDGE_OBJECT_FREELIST_SIZE 2000
#define EDGE_OBJECT_FREELIST_MAXSAVE 20
extern PyTypeObject EdgeObject_Type;
#define EdgeObject_Check(d) (Py_TYPE(d) == &EdgeObject_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *weakreflist;
PyObject *desc;
Py_hash_t cached_hash;
PyObject *ob_item[1];
} EdgeObject;
PyObject * EdgeObject_InitType(void);
PyObject * EdgeObject_New(PyObject *);
PyObject * EdgeObject_GetRecordDesc(PyObject *);
int EdgeObject_SetItem(PyObject *, Py_ssize_t, PyObject *);
PyObject * EdgeObject_GetItem(PyObject *, Py_ssize_t);
PyObject * EdgeObject_GetID(PyObject *ob);
/* === edgedb.Set =========================================== */
extern PyTypeObject EdgeSet_Type;
#define EdgeSet_Check(d) (Py_TYPE(d) == &EdgeSet_Type)
typedef struct {
PyObject_HEAD
Py_hash_t cached_hash;
PyObject *weakreflist;
PyObject *els;
} EdgeSetObject;
PyObject * EdgeSet_InitType(void);
PyObject * EdgeSet_New(Py_ssize_t);
int EdgeSet_SetItem(PyObject *, Py_ssize_t, PyObject *);
PyObject * EdgeSet_GetItem(PyObject *, Py_ssize_t);
int EdgeSet_AppendItem(PyObject *, PyObject *);
Py_ssize_t EdgeSet_Len(PyObject *);
/* === edgedb.Array ========================================= */
#define EDGE_ARRAY_FREELIST_SIZE 500
#define EDGE_ARRAY_FREELIST_MAXSAVE 10
extern PyTypeObject EdgeArray_Type;
#define EdgeArray_Check(d) (Py_TYPE(d) == &EdgeArray_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *weakreflist;
Py_hash_t cached_hash;
PyObject *ob_item[1];
} EdgeArrayObject;
PyObject * EdgeArray_InitType(void);
PyObject * EdgeArray_New(Py_ssize_t size);
int EdgeArray_SetItem(PyObject *, Py_ssize_t, PyObject *);
/* === edgedb.Link ========================================== */
extern PyTypeObject EdgeLink_Type;
#define EdgeLink_Check(d) (Py_TYPE(d) == &EdgeLink_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *weakreflist;
PyObject *name;
PyObject *source;
PyObject *target;
} EdgeLinkObject;
PyObject * EdgeLink_InitType(void);
PyObject * EdgeLink_New(PyObject *, PyObject *, PyObject *);
/* === edgedb.LinkSet ======================================= */
extern PyTypeObject EdgeLinkSet_Type;
#define EdgeLinkSet_Check(d) (Py_TYPE(d) == &EdgeLinkSet_Type)
typedef struct {
PyObject_VAR_HEAD
PyObject *weakreflist;
PyObject *name;
PyObject *source;
PyObject *targets;
} EdgeLinkSetObject;
PyObject * EdgeLinkSet_InitType(void);
PyObject * EdgeLinkSet_New(PyObject *, PyObject *, PyObject *);
#endif
|
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
bl_info = {
"name": "Bsurfaces GPL Edition",
"author": "Eclectiel, Spivak Vladimir(cwolf3d)",
"version": (1, 5, 1),
"blender": (2, 80, 0),
"location": "View3D > EditMode > ToolShelf",
"description": "Modeling and retopology tool",
"wiki_url": "https://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.64/Bsurfaces_1.5",
"category": "Mesh",
}
import bpy
import bmesh
from bpy_extras import object_utils
import operator
from mathutils import Matrix, Vector
from mathutils.geometry import (
intersect_line_line,
intersect_point_line,
)
from math import (
degrees,
pi,
sqrt,
)
from bpy.props import (
BoolProperty,
FloatProperty,
IntProperty,
StringProperty,
PointerProperty,
)
from bpy.types import (
Operator,
Panel,
PropertyGroup,
AddonPreferences,
)
class VIEW3D_PT_tools_SURFSK_mesh(Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Tools'
bl_context = "mesh_edit"
bl_label = "Bsurfaces"
@classmethod
def poll(cls, context):
return context.active_object
def draw(self, context):
layout = self.layout
scn = context.scene.bsurfaces
col = layout.column(align=True)
row = layout.row()
row.separator()
col.operator("gpencil.surfsk_add_surface", text="Add Surface")
col.operator("gpencil.surfsk_add_strokes", text="Add Strokes")
col.operator("gpencil.surfsk_edit_strokes", text="Edit Strokes")
col.prop(scn, "SURFSK_cyclic_cross")
col.prop(scn, "SURFSK_cyclic_follow")
col.prop(scn, "SURFSK_loops_on_strokes")
col.prop(scn, "SURFSK_automatic_join")
col.prop(scn, "SURFSK_keep_strokes")
class VIEW3D_PT_tools_SURFSK_curve(Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_context = "curve_edit"
bl_category = 'Tools'
bl_label = "Bsurfaces"
@classmethod
def poll(cls, context):
return context.active_object
def draw(self, context):
layout = self.layout
col = layout.column(align=True)
row = layout.row()
row.separator()
col.operator("curve.surfsk_first_points", text="Set First Points")
col.operator("curve.switch_direction", text="Switch Direction")
col.operator("curve.surfsk_reorder_splines", text="Reorder Splines")
# Returns the type of strokes used
def get_strokes_type(main_object):
strokes_type = ""
strokes_num = 0
# Check if they are grease pencil
try:
# Get the active grease pencil layer
gpencil = bpy.context.scene.objects['GPencil']
layer = gpencil.data.layers[0]
frame = layer.frames[0]
strokes_num = len(frame.strokes)
if strokes_num > 0:
strokes_type = "GP_STROKES"
except:
pass
# Check if they are curves, if there aren't grease pencil strokes
if strokes_type == "":
if len(bpy.context.selected_objects) == 2:
for ob in bpy.context.selected_objects:
if ob != bpy.context.view_layer.objects.active and ob.type == "CURVE":
strokes_type = "EXTERNAL_CURVE"
strokes_num = len(ob.data.splines)
# Check if there is any non-bezier spline
for i in range(len(ob.data.splines)):
if ob.data.splines[i].type != "BEZIER":
strokes_type = "CURVE_WITH_NON_BEZIER_SPLINES"
break
elif ob != bpy.context.view_layer.objects.active and ob.type != "CURVE":
strokes_type = "EXTERNAL_NO_CURVE"
elif len(bpy.context.selected_objects) > 2:
strokes_type = "MORE_THAN_ONE_EXTERNAL"
# Check if there is a single stroke without any selection in the object
if strokes_num == 1 and main_object.data.total_vert_sel == 0:
if strokes_type == "EXTERNAL_CURVE":
strokes_type = "SINGLE_CURVE_STROKE_NO_SELECTION"
elif strokes_type == "GP_STROKES":
strokes_type = "SINGLE_GP_STROKE_NO_SELECTION"
if strokes_num == 0 and main_object.data.total_vert_sel > 0:
strokes_type = "SELECTION_ALONE"
if strokes_type == "":
strokes_type = "NO_STROKES"
return strokes_type
# Surface generator operator
class GPENCIL_OT_SURFSK_add_surface(Operator):
bl_idname = "gpencil.surfsk_add_surface"
bl_label = "Bsurfaces add surface"
bl_description = "Generates surfaces from grease pencil strokes, bezier curves or loose edges"
bl_options = {'REGISTER', 'UNDO'}
edges_U: IntProperty(
name="Cross",
description="Number of face-loops crossing the strokes",
default=1,
min=1,
max=200
)
edges_V: IntProperty(
name="Follow",
description="Number of face-loops following the strokes",
default=1,
min=1,
max=200
)
cyclic_cross: BoolProperty(
name="Cyclic Cross",
description="Make cyclic the face-loops crossing the strokes",
default=False
)
cyclic_follow: BoolProperty(
name="Cyclic Follow",
description="Make cyclic the face-loops following the strokes",
default=False
)
loops_on_strokes: BoolProperty(
name="Loops on strokes",
description="Make the loops match the paths of the strokes",
default=False
)
automatic_join: BoolProperty(
name="Automatic join",
description="Join automatically vertices of either surfaces generated "
"by crosshatching, or from the borders of closed shapes",
default=False
)
join_stretch_factor: FloatProperty(
name="Stretch",
description="Amount of stretching or shrinking allowed for "
"edges when joining vertices automatically",
default=1,
min=0,
max=3,
subtype='FACTOR'
)
def draw(self, context):
layout = self.layout
col = layout.column(align=True)
row = layout.row()
if not self.is_fill_faces:
row.separator()
if not self.is_crosshatch:
if not self.selection_U_exists:
col.prop(self, "edges_U")
row.separator()
if not self.selection_V_exists:
col.prop(self, "edges_V")
row.separator()
row.separator()
if not self.selection_U_exists:
if not (
(self.selection_V_exists and not self.selection_V_is_closed) or
(self.selection_V2_exists and not self.selection_V2_is_closed)
):
col.prop(self, "cyclic_cross")
if not self.selection_V_exists:
if not (
(self.selection_U_exists and not self.selection_U_is_closed) or
(self.selection_U2_exists and not self.selection_U2_is_closed)
):
col.prop(self, "cyclic_follow")
col.prop(self, "loops_on_strokes")
col.prop(self, "automatic_join")
if self.automatic_join:
row.separator()
col.separator()
row.separator()
col.prop(self, "join_stretch_factor")
# Get an ordered list of a chain of vertices
def get_ordered_verts(self, ob, all_selected_edges_idx, all_selected_verts_idx,
first_vert_idx, middle_vertex_idx, closing_vert_idx):
# Order selected vertices.
verts_ordered = []
if closing_vert_idx is not None:
verts_ordered.append(ob.data.vertices[closing_vert_idx])
verts_ordered.append(ob.data.vertices[first_vert_idx])
prev_v = first_vert_idx
prev_ed = None
finish_while = False
while True:
edges_non_matched = 0
for i in all_selected_edges_idx:
if ob.data.edges[i] != prev_ed and ob.data.edges[i].vertices[0] == prev_v and \
ob.data.edges[i].vertices[1] in all_selected_verts_idx:
verts_ordered.append(ob.data.vertices[ob.data.edges[i].vertices[1]])
prev_v = ob.data.edges[i].vertices[1]
prev_ed = ob.data.edges[i]
elif ob.data.edges[i] != prev_ed and ob.data.edges[i].vertices[1] == prev_v and \
ob.data.edges[i].vertices[0] in all_selected_verts_idx:
verts_ordered.append(ob.data.vertices[ob.data.edges[i].vertices[0]])
prev_v = ob.data.edges[i].vertices[0]
prev_ed = ob.data.edges[i]
else:
edges_non_matched += 1
if edges_non_matched == len(all_selected_edges_idx):
finish_while = True
if finish_while:
break
if closing_vert_idx is not None:
verts_ordered.append(ob.data.vertices[closing_vert_idx])
if middle_vertex_idx is not None:
verts_ordered.append(ob.data.vertices[middle_vertex_idx])
verts_ordered.reverse()
return tuple(verts_ordered)
# Calculates length of a chain of points.
def get_chain_length(self, object, verts_ordered):
matrix = object.matrix_world
edges_lengths = []
edges_lengths_sum = 0
for i in range(0, len(verts_ordered)):
if i == 0:
prev_v_co = matrix @ verts_ordered[i].co
else:
v_co = matrix @ verts_ordered[i].co
v_difs = [prev_v_co[0] - v_co[0], prev_v_co[1] - v_co[1], prev_v_co[2] - v_co[2]]
edge_length = abs(sqrt(v_difs[0] * v_difs[0] + v_difs[1] * v_difs[1] + v_difs[2] * v_difs[2]))
edges_lengths.append(edge_length)
edges_lengths_sum += edge_length
prev_v_co = v_co
return edges_lengths, edges_lengths_sum
# Calculates the proportion of the edges of a chain of edges, relative to the full chain length.
def get_edges_proportions(self, edges_lengths, edges_lengths_sum, use_boundaries, fixed_edges_num):
edges_proportions = []
if use_boundaries:
verts_count = 1
for l in edges_lengths:
edges_proportions.append(l / edges_lengths_sum)
verts_count += 1
else:
verts_count = 1
for n in range(0, fixed_edges_num):
edges_proportions.append(1 / fixed_edges_num)
verts_count += 1
return edges_proportions
# Calculates the angle between two pairs of points in space
def orientation_difference(self, points_A_co, points_B_co):
# each parameter should be a list with two elements,
# and each element should be a x,y,z coordinate
vec_A = points_A_co[0] - points_A_co[1]
vec_B = points_B_co[0] - points_B_co[1]
angle = vec_A.angle(vec_B)
if angle > 0.5 * pi:
angle = abs(angle - pi)
return angle
# Calculate the which vert of verts_idx list is the nearest one
# to the point_co coordinates, and the distance
def shortest_distance(self, object, point_co, verts_idx):
matrix = object.matrix_world
for i in range(0, len(verts_idx)):
dist = (point_co - matrix @ object.data.vertices[verts_idx[i]].co).length
if i == 0:
prev_dist = dist
nearest_vert_idx = verts_idx[i]
shortest_dist = dist
if dist < prev_dist:
prev_dist = dist
nearest_vert_idx = verts_idx[i]
shortest_dist = dist
return nearest_vert_idx, shortest_dist
# Returns the index of the opposite vert tip in a chain, given a vert tip index
# as parameter, and a multidimentional list with all pairs of tips
def opposite_tip(self, vert_tip_idx, all_chains_tips_idx):
opposite_vert_tip_idx = None
for i in range(0, len(all_chains_tips_idx)):
if vert_tip_idx == all_chains_tips_idx[i][0]:
opposite_vert_tip_idx = all_chains_tips_idx[i][1]
if vert_tip_idx == all_chains_tips_idx[i][1]:
opposite_vert_tip_idx = all_chains_tips_idx[i][0]
return opposite_vert_tip_idx
# Simplifies a spline and returns the new points coordinates
def simplify_spline(self, spline_coords, segments_num):
simplified_spline = []
points_between_segments = round(len(spline_coords) / segments_num)
simplified_spline.append(spline_coords[0])
for i in range(1, segments_num):
simplified_spline.append(spline_coords[i * points_between_segments])
simplified_spline.append(spline_coords[len(spline_coords) - 1])
return simplified_spline
# Cleans up the scene and gets it the same it was at the beginning,
# in case the script is interrupted in the middle of the execution
def cleanup_on_interruption(self):
# If the original strokes curve comes from conversion
# from grease pencil and wasn't made by hand, delete it
if not self.using_external_curves:
try:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.original_curve.select_set(True)
bpy.context.view_layer.objects.active = self.original_curve
bpy.ops.object.delete()
except:
pass
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
else:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.original_curve.select_set(True)
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Returns a list with the coords of the points distributed over the splines
# passed to this method according to the proportions parameter
def distribute_pts(self, surface_splines, proportions):
# Calculate the length of each final surface spline
surface_splines_lengths = []
surface_splines_parsed = []
for sp_idx in range(0, len(surface_splines)):
# Calculate spline length
surface_splines_lengths.append(0)
for i in range(0, len(surface_splines[sp_idx].bezier_points)):
if i == 0:
prev_p = surface_splines[sp_idx].bezier_points[i]
else:
p = surface_splines[sp_idx].bezier_points[i]
edge_length = (prev_p.co - p.co).length
surface_splines_lengths[sp_idx] += edge_length
prev_p = p
# Calculate vertex positions with appropriate edge proportions, and ordered, for each spline
for sp_idx in range(0, len(surface_splines)):
surface_splines_parsed.append([])
surface_splines_parsed[sp_idx].append(surface_splines[sp_idx].bezier_points[0].co)
prev_p_co = surface_splines[sp_idx].bezier_points[0].co
p_idx = 0
for prop_idx in range(len(proportions) - 1):
target_length = surface_splines_lengths[sp_idx] * proportions[prop_idx]
partial_segment_length = 0
finish_while = False
while True:
# if not it'll pass the p_idx as an index below and crash
if p_idx < len(surface_splines[sp_idx].bezier_points):
p_co = surface_splines[sp_idx].bezier_points[p_idx].co
new_dist = (prev_p_co - p_co).length
# The new distance that could have the partial segment if
# it is still shorter than the target length
potential_segment_length = partial_segment_length + new_dist
# If the potential is still shorter, keep adding
if potential_segment_length < target_length:
partial_segment_length = potential_segment_length
p_idx += 1
prev_p_co = p_co
# If the potential is longer than the target, calculate the target
# (a point between the last two points), and assign
elif potential_segment_length > target_length:
remaining_dist = target_length - partial_segment_length
vec = p_co - prev_p_co
vec.normalize()
intermediate_co = prev_p_co + (vec * remaining_dist)
surface_splines_parsed[sp_idx].append(intermediate_co)
partial_segment_length += remaining_dist
prev_p_co = intermediate_co
finish_while = True
# If the potential is equal to the target, assign
elif potential_segment_length == target_length:
surface_splines_parsed[sp_idx].append(p_co)
prev_p_co = p_co
finish_while = True
if finish_while:
break
# last point of the spline
surface_splines_parsed[sp_idx].append(
surface_splines[sp_idx].bezier_points[len(surface_splines[sp_idx].bezier_points) - 1].co
)
return surface_splines_parsed
# Counts the number of faces that belong to each edge
def edge_face_count(self, ob):
ed_keys_count_dict = {}
for face in ob.data.polygons:
for ed_keys in face.edge_keys:
if ed_keys not in ed_keys_count_dict:
ed_keys_count_dict[ed_keys] = 1
else:
ed_keys_count_dict[ed_keys] += 1
edge_face_count = []
for i in range(len(ob.data.edges)):
edge_face_count.append(0)
for i in range(len(ob.data.edges)):
ed = ob.data.edges[i]
v1 = ed.vertices[0]
v2 = ed.vertices[1]
if (v1, v2) in ed_keys_count_dict:
edge_face_count[i] = ed_keys_count_dict[(v1, v2)]
elif (v2, v1) in ed_keys_count_dict:
edge_face_count[i] = ed_keys_count_dict[(v2, v1)]
return edge_face_count
# Fills with faces all the selected vertices which form empty triangles or quads
def fill_with_faces(self, object):
all_selected_verts_count = self.main_object_selected_verts_count
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
# Calculate average length of selected edges
all_selected_verts = []
original_sel_edges_count = 0
for ed in object.data.edges:
if object.data.vertices[ed.vertices[0]].select and object.data.vertices[ed.vertices[1]].select:
coords = []
coords.append(object.data.vertices[ed.vertices[0]].co)
coords.append(object.data.vertices[ed.vertices[1]].co)
original_sel_edges_count += 1
if not ed.vertices[0] in all_selected_verts:
all_selected_verts.append(ed.vertices[0])
if not ed.vertices[1] in all_selected_verts:
all_selected_verts.append(ed.vertices[1])
tuple(all_selected_verts)
# Check if there is any edge selected. If not, interrupt the script
if original_sel_edges_count == 0 and all_selected_verts_count > 0:
return 0
# Get all edges connected to selected verts
all_edges_around_sel_verts = []
edges_connected_to_sel_verts = {}
verts_connected_to_every_vert = {}
for ed_idx in range(len(object.data.edges)):
ed = object.data.edges[ed_idx]
include_edge = False
if ed.vertices[0] in all_selected_verts:
if not ed.vertices[0] in edges_connected_to_sel_verts:
edges_connected_to_sel_verts[ed.vertices[0]] = []
edges_connected_to_sel_verts[ed.vertices[0]].append(ed_idx)
include_edge = True
if ed.vertices[1] in all_selected_verts:
if not ed.vertices[1] in edges_connected_to_sel_verts:
edges_connected_to_sel_verts[ed.vertices[1]] = []
edges_connected_to_sel_verts[ed.vertices[1]].append(ed_idx)
include_edge = True
if include_edge is True:
all_edges_around_sel_verts.append(ed_idx)
# Get all connected verts to each vert
if not ed.vertices[0] in verts_connected_to_every_vert:
verts_connected_to_every_vert[ed.vertices[0]] = []
if not ed.vertices[1] in verts_connected_to_every_vert:
verts_connected_to_every_vert[ed.vertices[1]] = []
verts_connected_to_every_vert[ed.vertices[0]].append(ed.vertices[1])
verts_connected_to_every_vert[ed.vertices[1]].append(ed.vertices[0])
# Get all verts connected to faces
all_verts_part_of_faces = []
all_edges_faces_count = []
all_edges_faces_count += self.edge_face_count(object)
# Get only the selected edges that have faces attached.
count_faces_of_edges_around_sel_verts = {}
selected_verts_with_faces = []
for ed_idx in all_edges_around_sel_verts:
count_faces_of_edges_around_sel_verts[ed_idx] = all_edges_faces_count[ed_idx]
if all_edges_faces_count[ed_idx] > 0:
ed = object.data.edges[ed_idx]
if not ed.vertices[0] in selected_verts_with_faces:
selected_verts_with_faces.append(ed.vertices[0])
if not ed.vertices[1] in selected_verts_with_faces:
selected_verts_with_faces.append(ed.vertices[1])
all_verts_part_of_faces.append(ed.vertices[0])
all_verts_part_of_faces.append(ed.vertices[1])
tuple(selected_verts_with_faces)
# Discard unneeded verts from calculations
participating_verts = []
movable_verts = []
for v_idx in all_selected_verts:
vert_has_edges_with_one_face = False
# Check if the actual vert has at least one edge connected to only one face
for ed_idx in edges_connected_to_sel_verts[v_idx]:
if count_faces_of_edges_around_sel_verts[ed_idx] == 1:
vert_has_edges_with_one_face = True
# If the vert has two or less edges connected and the vert is not part of any face.
# Or the vert is part of any face and at least one of
# the connected edges has only one face attached to it.
if (len(edges_connected_to_sel_verts[v_idx]) == 2 and
v_idx not in all_verts_part_of_faces) or \
len(edges_connected_to_sel_verts[v_idx]) == 1 or \
(v_idx in all_verts_part_of_faces and
vert_has_edges_with_one_face):
participating_verts.append(v_idx)
if v_idx not in all_verts_part_of_faces:
movable_verts.append(v_idx)
# Remove from movable verts list those that are part of closed geometry (ie: triangles, quads)
for mv_idx in movable_verts:
freeze_vert = False
mv_connected_verts = verts_connected_to_every_vert[mv_idx]
for actual_v_idx in all_selected_verts:
count_shared_neighbors = 0
checked_verts = []
for mv_conn_v_idx in mv_connected_verts:
if mv_idx != actual_v_idx:
if mv_conn_v_idx in verts_connected_to_every_vert[actual_v_idx] and \
mv_conn_v_idx not in checked_verts:
count_shared_neighbors += 1
checked_verts.append(mv_conn_v_idx)
if actual_v_idx in mv_connected_verts:
freeze_vert = True
break
if count_shared_neighbors == 2:
freeze_vert = True
break
if freeze_vert:
break
if freeze_vert:
movable_verts.remove(mv_idx)
# Calculate merge distance for participating verts
shortest_edge_length = None
for ed in object.data.edges:
if ed.vertices[0] in movable_verts and ed.vertices[1] in movable_verts:
v1 = object.data.vertices[ed.vertices[0]]
v2 = object.data.vertices[ed.vertices[1]]
length = (v1.co - v2.co).length
if shortest_edge_length is None:
shortest_edge_length = length
else:
if length < shortest_edge_length:
shortest_edge_length = length
if shortest_edge_length is not None:
edges_merge_distance = shortest_edge_length * 0.5
else:
edges_merge_distance = 0
# Get together the verts near enough. They will be merged later
remaining_verts = []
remaining_verts += participating_verts
for v1_idx in participating_verts:
if v1_idx in remaining_verts and v1_idx in movable_verts:
verts_to_merge = []
coords_verts_to_merge = {}
verts_to_merge.append(v1_idx)
v1_co = object.data.vertices[v1_idx].co
coords_verts_to_merge[v1_idx] = (v1_co[0], v1_co[1], v1_co[2])
for v2_idx in remaining_verts:
if v1_idx != v2_idx:
v2_co = object.data.vertices[v2_idx].co
dist = (v1_co - v2_co).length
if dist <= edges_merge_distance: # Add the verts which are near enough
verts_to_merge.append(v2_idx)
coords_verts_to_merge[v2_idx] = (v2_co[0], v2_co[1], v2_co[2])
for vm_idx in verts_to_merge:
remaining_verts.remove(vm_idx)
if len(verts_to_merge) > 1:
# Calculate middle point of the verts to merge.
sum_x_co = 0
sum_y_co = 0
sum_z_co = 0
movable_verts_to_merge_count = 0
for i in range(len(verts_to_merge)):
if verts_to_merge[i] in movable_verts:
v_co = object.data.vertices[verts_to_merge[i]].co
sum_x_co += v_co[0]
sum_y_co += v_co[1]
sum_z_co += v_co[2]
movable_verts_to_merge_count += 1
middle_point_co = [
sum_x_co / movable_verts_to_merge_count,
sum_y_co / movable_verts_to_merge_count,
sum_z_co / movable_verts_to_merge_count
]
# Check if any vert to be merged is not movable
shortest_dist = None
are_verts_not_movable = False
verts_not_movable = []
for v_merge_idx in verts_to_merge:
if v_merge_idx in participating_verts and v_merge_idx not in movable_verts:
are_verts_not_movable = True
verts_not_movable.append(v_merge_idx)
if are_verts_not_movable:
# Get the vert connected to faces, that is nearest to
# the middle point of the movable verts
shortest_dist = None
for vcf_idx in verts_not_movable:
dist = abs((object.data.vertices[vcf_idx].co -
Vector(middle_point_co)).length)
if shortest_dist is None:
shortest_dist = dist
nearest_vert_idx = vcf_idx
else:
if dist < shortest_dist:
shortest_dist = dist
nearest_vert_idx = vcf_idx
coords = object.data.vertices[nearest_vert_idx].co
target_point_co = [coords[0], coords[1], coords[2]]
else:
target_point_co = middle_point_co
# Move verts to merge to the middle position
for v_merge_idx in verts_to_merge:
if v_merge_idx in movable_verts: # Only move the verts that are not part of faces
object.data.vertices[v_merge_idx].co[0] = target_point_co[0]
object.data.vertices[v_merge_idx].co[1] = target_point_co[1]
object.data.vertices[v_merge_idx].co[2] = target_point_co[2]
# Perform "Remove Doubles" to weld all the disconnected verts
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
bpy.ops.mesh.remove_doubles(threshold=0.0001)
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
# Get all the definitive selected edges, after weldding
selected_edges = []
edges_per_vert = {} # Number of faces of each selected edge
for ed in object.data.edges:
if object.data.vertices[ed.vertices[0]].select and object.data.vertices[ed.vertices[1]].select:
selected_edges.append(ed.index)
# Save all the edges that belong to each vertex.
if not ed.vertices[0] in edges_per_vert:
edges_per_vert[ed.vertices[0]] = []
if not ed.vertices[1] in edges_per_vert:
edges_per_vert[ed.vertices[1]] = []
edges_per_vert[ed.vertices[0]].append(ed.index)
edges_per_vert[ed.vertices[1]].append(ed.index)
# Check if all the edges connected to each vert have two faces attached to them.
# To discard them later and make calculations faster
a = []
a += self.edge_face_count(object)
tuple(a)
verts_surrounded_by_faces = {}
for v_idx in edges_per_vert:
edges = edges_per_vert[v_idx]
edges_with_two_faces_count = 0
for ed_idx in edges_per_vert[v_idx]:
if a[ed_idx] == 2:
edges_with_two_faces_count += 1
if edges_with_two_faces_count == len(edges_per_vert[v_idx]):
verts_surrounded_by_faces[v_idx] = True
else:
verts_surrounded_by_faces[v_idx] = False
# Get all the selected vertices
selected_verts_idx = []
for v in object.data.vertices:
if v.select:
selected_verts_idx.append(v.index)
# Get all the faces of the object
all_object_faces_verts_idx = []
for face in object.data.polygons:
face_verts = []
face_verts.append(face.vertices[0])
face_verts.append(face.vertices[1])
face_verts.append(face.vertices[2])
if len(face.vertices) == 4:
face_verts.append(face.vertices[3])
all_object_faces_verts_idx.append(face_verts)
# Deselect all vertices
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
# Make a dictionary with the verts related to each vert
related_key_verts = {}
for ed_idx in selected_edges:
ed = object.data.edges[ed_idx]
if not verts_surrounded_by_faces[ed.vertices[0]]:
if not ed.vertices[0] in related_key_verts:
related_key_verts[ed.vertices[0]] = []
if not ed.vertices[1] in related_key_verts[ed.vertices[0]]:
related_key_verts[ed.vertices[0]].append(ed.vertices[1])
if not verts_surrounded_by_faces[ed.vertices[1]]:
if not ed.vertices[1] in related_key_verts:
related_key_verts[ed.vertices[1]] = []
if not ed.vertices[0] in related_key_verts[ed.vertices[1]]:
related_key_verts[ed.vertices[1]].append(ed.vertices[0])
# Get groups of verts forming each face
faces_verts_idx = []
for v1 in related_key_verts: # verts-1 ....
for v2 in related_key_verts: # verts-2
if v1 != v2:
related_verts_in_common = []
v2_in_rel_v1 = False
v1_in_rel_v2 = False
for rel_v1 in related_key_verts[v1]:
# Check if related verts of verts-1 are related verts of verts-2
if rel_v1 in related_key_verts[v2]:
related_verts_in_common.append(rel_v1)
if v2 in related_key_verts[v1]:
v2_in_rel_v1 = True
if v1 in related_key_verts[v2]:
v1_in_rel_v2 = True
repeated_face = False
# If two verts have two related verts in common, they form a quad
if len(related_verts_in_common) == 2:
# Check if the face is already saved
all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
for f_verts in all_faces_to_check_idx:
repeated_verts = 0
if len(f_verts) == 4:
if v1 in f_verts:
repeated_verts += 1
if v2 in f_verts:
repeated_verts += 1
if related_verts_in_common[0] in f_verts:
repeated_verts += 1
if related_verts_in_common[1] in f_verts:
repeated_verts += 1
if repeated_verts == len(f_verts):
repeated_face = True
break
if not repeated_face:
faces_verts_idx.append(
[v1, related_verts_in_common[0], v2, related_verts_in_common[1]]
)
# If Two verts have one related vert in common and
# they are related to each other, they form a triangle
elif v2_in_rel_v1 and v1_in_rel_v2 and len(related_verts_in_common) == 1:
# Check if the face is already saved.
all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
for f_verts in all_faces_to_check_idx:
repeated_verts = 0
if len(f_verts) == 3:
if v1 in f_verts:
repeated_verts += 1
if v2 in f_verts:
repeated_verts += 1
if related_verts_in_common[0] in f_verts:
repeated_verts += 1
if repeated_verts == len(f_verts):
repeated_face = True
break
if not repeated_face:
faces_verts_idx.append([v1, related_verts_in_common[0], v2])
# Keep only the faces that don't overlap by ignoring quads
# that overlap with two adjacent triangles
faces_to_not_include_idx = [] # Indices of faces_verts_idx to eliminate
all_faces_to_check_idx = faces_verts_idx + all_object_faces_verts_idx
for i in range(len(faces_verts_idx)):
for t in range(len(all_faces_to_check_idx)):
if i != t:
verts_in_common = 0
if len(faces_verts_idx[i]) == 4 and len(all_faces_to_check_idx[t]) == 3:
for v_idx in all_faces_to_check_idx[t]:
if v_idx in faces_verts_idx[i]:
verts_in_common += 1
# If it doesn't have all it's vertices repeated in the other face
if verts_in_common == 3:
if i not in faces_to_not_include_idx:
faces_to_not_include_idx.append(i)
# Build faces discarding the ones in faces_to_not_include
me = object.data
bm = bmesh.new()
bm.from_mesh(me)
num_faces_created = 0
for i in range(len(faces_verts_idx)):
if i not in faces_to_not_include_idx:
bm.faces.new([bm.verts[v] for v in faces_verts_idx[i]])
num_faces_created += 1
bm.to_mesh(me)
bm.free()
for v_idx in selected_verts_idx:
self.main_object.data.vertices[v_idx].select = True
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='EDIT')
bpy.ops.mesh.normals_make_consistent(inside=False)
bpy.ops.object.mode_set('INVOKE_REGION_WIN', mode='OBJECT')
return num_faces_created
# Crosshatch skinning
def crosshatch_surface_invoke(self, ob_original_splines):
self.is_crosshatch = False
self.crosshatch_merge_distance = 0
objects_to_delete = [] # duplicated strokes to be deleted.
# If the main object uses modifiers deactivate them temporarily until the surface is joined
# (without this the surface verts merging with the main object doesn't work well)
self.modifiers_prev_viewport_state = []
if len(self.main_object.modifiers) > 0:
for m_idx in range(len(self.main_object.modifiers)):
self.modifiers_prev_viewport_state.append(
self.main_object.modifiers[m_idx].show_viewport
)
self.main_object.modifiers[m_idx].show_viewport = False
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_original_splines.select_set(True)
bpy.context.view_layer.objects.active = ob_original_splines
if len(ob_original_splines.data.splines) >= 2:
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
ob_splines = bpy.context.object
ob_splines.name = "SURFSKIO_NE_STR"
# Get estimative merge distance (sum up the distances from the first point to
# all other points, then average them and then divide them)
first_point_dist_sum = 0
first_dist = 0
second_dist = 0
coords_first_pt = ob_splines.data.splines[0].bezier_points[0].co
for i in range(len(ob_splines.data.splines)):
sp = ob_splines.data.splines[i]
if coords_first_pt != sp.bezier_points[0].co:
first_dist = (coords_first_pt - sp.bezier_points[0].co).length
if coords_first_pt != sp.bezier_points[len(sp.bezier_points) - 1].co:
second_dist = (coords_first_pt - sp.bezier_points[len(sp.bezier_points) - 1].co).length
first_point_dist_sum += first_dist + second_dist
if i == 0:
if first_dist != 0:
shortest_dist = first_dist
elif second_dist != 0:
shortest_dist = second_dist
if shortest_dist > first_dist and first_dist != 0:
shortest_dist = first_dist
if shortest_dist > second_dist and second_dist != 0:
shortest_dist = second_dist
self.crosshatch_merge_distance = shortest_dist / 20
# Recalculation of merge distance
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
ob_calc_merge_dist = bpy.context.object
ob_calc_merge_dist.name = "SURFSKIO_CALC_TMP"
objects_to_delete.append(ob_calc_merge_dist)
# Smooth out strokes a little to improve crosshatch detection
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='SELECT')
for i in range(4):
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Convert curves into mesh
ob_calc_merge_dist.data.resolution_u = 12
bpy.ops.object.convert(target='MESH', keep_original=False)
# Find "intersection-nodes"
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN',
threshold=self.crosshatch_merge_distance)
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Remove verts with less than three edges
verts_edges_count = {}
for ed in ob_calc_merge_dist.data.edges:
v = ed.vertices
if v[0] not in verts_edges_count:
verts_edges_count[v[0]] = 0
if v[1] not in verts_edges_count:
verts_edges_count[v[1]] = 0
verts_edges_count[v[0]] += 1
verts_edges_count[v[1]] += 1
nodes_verts_coords = []
for v_idx in verts_edges_count:
v = ob_calc_merge_dist.data.vertices[v_idx]
if verts_edges_count[v_idx] < 3:
v.select = True
# Remove them
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.delete('INVOKE_REGION_WIN', type='VERT')
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
# Remove doubles to discard very near verts from calculations of distance
bpy.ops.mesh.remove_doubles(
'INVOKE_REGION_WIN',
threshold=self.crosshatch_merge_distance * 4.0
)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Get all coords of the resulting nodes
nodes_verts_coords = [(v.co[0], v.co[1], v.co[2]) for
v in ob_calc_merge_dist.data.vertices]
# Check if the strokes are a crosshatch
if len(nodes_verts_coords) >= 3:
self.is_crosshatch = True
shortest_dist = None
for co_1 in nodes_verts_coords:
for co_2 in nodes_verts_coords:
if co_1 != co_2:
dist = (Vector(co_1) - Vector(co_2)).length
if shortest_dist is not None:
if dist < shortest_dist:
shortest_dist = dist
else:
shortest_dist = dist
self.crosshatch_merge_distance = shortest_dist / 3
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_splines.select_set(True)
bpy.context.view_layer.objects.active = ob_splines
# Deselect all points
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Smooth splines in a localized way, to eliminate "saw-teeth"
# like shapes when there are many points
for sp in ob_splines.data.splines:
angle_sum = 0
angle_limit = 2 # Degrees
for t in range(len(sp.bezier_points)):
# Because on each iteration it checks the "next two points"
# of the actual. This way it doesn't go out of range
if t <= len(sp.bezier_points) - 3:
p1 = sp.bezier_points[t]
p2 = sp.bezier_points[t + 1]
p3 = sp.bezier_points[t + 2]
vec_1 = p1.co - p2.co
vec_2 = p2.co - p3.co
if p2.co != p1.co and p2.co != p3.co:
angle = vec_1.angle(vec_2)
angle_sum += degrees(angle)
if angle_sum >= angle_limit: # If sum of angles is grater than the limit
if (p1.co - p2.co).length <= self.crosshatch_merge_distance:
p1.select_control_point = True
p1.select_left_handle = True
p1.select_right_handle = True
p2.select_control_point = True
p2.select_left_handle = True
p2.select_right_handle = True
if (p1.co - p2.co).length <= self.crosshatch_merge_distance:
p3.select_control_point = True
p3.select_left_handle = True
p3.select_right_handle = True
angle_sum = 0
sp.bezier_points[0].select_control_point = False
sp.bezier_points[0].select_left_handle = False
sp.bezier_points[0].select_right_handle = False
sp.bezier_points[len(sp.bezier_points) - 1].select_control_point = False
sp.bezier_points[len(sp.bezier_points) - 1].select_left_handle = False
sp.bezier_points[len(sp.bezier_points) - 1].select_right_handle = False
# Smooth out strokes a little to improve crosshatch detection
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
for i in range(15):
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Simplify the splines
for sp in ob_splines.data.splines:
angle_sum = 0
sp.bezier_points[0].select_control_point = True
sp.bezier_points[0].select_left_handle = True
sp.bezier_points[0].select_right_handle = True
sp.bezier_points[len(sp.bezier_points) - 1].select_control_point = True
sp.bezier_points[len(sp.bezier_points) - 1].select_left_handle = True
sp.bezier_points[len(sp.bezier_points) - 1].select_right_handle = True
angle_limit = 15 # Degrees
for t in range(len(sp.bezier_points)):
# Because on each iteration it checks the "next two points"
# of the actual. This way it doesn't go out of range
if t <= len(sp.bezier_points) - 3:
p1 = sp.bezier_points[t]
p2 = sp.bezier_points[t + 1]
p3 = sp.bezier_points[t + 2]
vec_1 = p1.co - p2.co
vec_2 = p2.co - p3.co
if p2.co != p1.co and p2.co != p3.co:
angle = vec_1.angle(vec_2)
angle_sum += degrees(angle)
# If sum of angles is grater than the limit
if angle_sum >= angle_limit:
p1.select_control_point = True
p1.select_left_handle = True
p1.select_right_handle = True
p2.select_control_point = True
p2.select_left_handle = True
p2.select_right_handle = True
p3.select_control_point = True
p3.select_left_handle = True
p3.select_right_handle = True
angle_sum = 0
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all(action='INVERT')
bpy.ops.curve.delete(type='VERT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
objects_to_delete.append(ob_splines)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Check if the strokes are a crosshatch
if self.is_crosshatch:
all_points_coords = []
for i in range(len(ob_splines.data.splines)):
all_points_coords.append([])
all_points_coords[i] = [Vector((x, y, z)) for
x, y, z in [bp.co for
bp in ob_splines.data.splines[i].bezier_points]]
all_intersections = []
checked_splines = []
for i in range(len(all_points_coords)):
for t in range(len(all_points_coords[i]) - 1):
bp1_co = all_points_coords[i][t]
bp2_co = all_points_coords[i][t + 1]
for i2 in range(len(all_points_coords)):
if i != i2 and i2 not in checked_splines:
for t2 in range(len(all_points_coords[i2]) - 1):
bp3_co = all_points_coords[i2][t2]
bp4_co = all_points_coords[i2][t2 + 1]
intersec_coords = intersect_line_line(
bp1_co, bp2_co, bp3_co, bp4_co
)
if intersec_coords is not None:
dist = (intersec_coords[0] - intersec_coords[1]).length
if dist <= self.crosshatch_merge_distance * 1.5:
temp_co, percent1 = intersect_point_line(
intersec_coords[0], bp1_co, bp2_co
)
if (percent1 >= -0.02 and percent1 <= 1.02):
temp_co, percent2 = intersect_point_line(
intersec_coords[1], bp3_co, bp4_co
)
if (percent2 >= -0.02 and percent2 <= 1.02):
# Format: spline index, first point index from
# corresponding segment, percentage from first point of
# actual segment, coords of intersection point
all_intersections.append(
(i, t, percent1,
ob_splines.matrix_world @ intersec_coords[0])
)
all_intersections.append(
(i2, t2, percent2,
ob_splines.matrix_world @ intersec_coords[1])
)
checked_splines.append(i)
# Sort list by spline, then by corresponding first point index of segment,
# and then by percentage from first point of segment: elements 0 and 1 respectively
all_intersections.sort(key=operator.itemgetter(0, 1, 2))
self.crosshatch_strokes_coords = {}
for i in range(len(all_intersections)):
if not all_intersections[i][0] in self.crosshatch_strokes_coords:
self.crosshatch_strokes_coords[all_intersections[i][0]] = []
self.crosshatch_strokes_coords[all_intersections[i][0]].append(
all_intersections[i][3]
) # Save intersection coords
else:
self.is_crosshatch = False
# Delete all duplicates
for o in objects_to_delete:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
o.select_set(True)
bpy.context.view_layer.objects.active = o
bpy.ops.object.delete()
# If the main object has modifiers, turn their "viewport view status" to
# what it was before the forced deactivation above
if len(self.main_object.modifiers) > 0:
for m_idx in range(len(self.main_object.modifiers)):
self.main_object.modifiers[m_idx].show_viewport = self.modifiers_prev_viewport_state[m_idx]
return
# Part of the Crosshatch process that is repeated when the operator is tweaked
def crosshatch_surface_execute(self):
# If the main object uses modifiers deactivate them temporarily until the surface is joined
# (without this the surface verts merging with the main object doesn't work well)
self.modifiers_prev_viewport_state = []
if len(self.main_object.modifiers) > 0:
for m_idx in range(len(self.main_object.modifiers)):
self.modifiers_prev_viewport_state.append(self.main_object.modifiers[m_idx].show_viewport)
self.main_object.modifiers[m_idx].show_viewport = False
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
me_name = "SURFSKIO_STK_TMP"
me = bpy.data.meshes.new(me_name)
all_verts_coords = []
all_edges = []
for st_idx in self.crosshatch_strokes_coords:
for co_idx in range(len(self.crosshatch_strokes_coords[st_idx])):
coords = self.crosshatch_strokes_coords[st_idx][co_idx]
all_verts_coords.append(coords)
if co_idx > 0:
all_edges.append((len(all_verts_coords) - 2, len(all_verts_coords) - 1))
me.from_pydata(all_verts_coords, all_edges, [])
me.update()
ob = bpy.data.objects.new(me_name, me)
ob.data = me
bpy.context.collection.objects.link(ob)
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob.select_set(True)
bpy.context.view_layer.objects.active = ob
# Get together each vert and its nearest, to the middle position
verts = ob.data.vertices
checked_verts = []
for i in range(len(verts)):
shortest_dist = None
if i not in checked_verts:
for t in range(len(verts)):
if i != t and t not in checked_verts:
dist = (verts[i].co - verts[t].co).length
if shortest_dist is not None:
if dist < shortest_dist:
shortest_dist = dist
nearest_vert = t
else:
shortest_dist = dist
nearest_vert = t
middle_location = (verts[i].co + verts[nearest_vert].co) / 2
verts[i].co = middle_location
verts[nearest_vert].co = middle_location
checked_verts.append(i)
checked_verts.append(nearest_vert)
# Calculate average length between all the generated edges
ob = bpy.context.object
lengths_sum = 0
for ed in ob.data.edges:
v1 = ob.data.vertices[ed.vertices[0]]
v2 = ob.data.vertices[ed.vertices[1]]
lengths_sum += (v1.co - v2.co).length
edges_count = len(ob.data.edges)
# possible division by zero here
average_edge_length = lengths_sum / edges_count if edges_count != 0 else 0.0001
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='SELECT')
bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN',
threshold=average_edge_length / 15.0)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
final_points_ob = bpy.context.view_layer.objects.active
# Make a dictionary with the verts related to each vert
related_key_verts = {}
for ed in final_points_ob.data.edges:
if not ed.vertices[0] in related_key_verts:
related_key_verts[ed.vertices[0]] = []
if not ed.vertices[1] in related_key_verts:
related_key_verts[ed.vertices[1]] = []
if not ed.vertices[1] in related_key_verts[ed.vertices[0]]:
related_key_verts[ed.vertices[0]].append(ed.vertices[1])
if not ed.vertices[0] in related_key_verts[ed.vertices[1]]:
related_key_verts[ed.vertices[1]].append(ed.vertices[0])
# Get groups of verts forming each face
faces_verts_idx = []
for v1 in related_key_verts: # verts-1 ....
for v2 in related_key_verts: # verts-2
if v1 != v2:
related_verts_in_common = []
v2_in_rel_v1 = False
v1_in_rel_v2 = False
for rel_v1 in related_key_verts[v1]:
# Check if related verts of verts-1 are related verts of verts-2
if rel_v1 in related_key_verts[v2]:
related_verts_in_common.append(rel_v1)
if v2 in related_key_verts[v1]:
v2_in_rel_v1 = True
if v1 in related_key_verts[v2]:
v1_in_rel_v2 = True
repeated_face = False
# If two verts have two related verts in common, they form a quad
if len(related_verts_in_common) == 2:
# Check if the face is already saved
for f_verts in faces_verts_idx:
repeated_verts = 0
if len(f_verts) == 4:
if v1 in f_verts:
repeated_verts += 1
if v2 in f_verts:
repeated_verts += 1
if related_verts_in_common[0] in f_verts:
repeated_verts += 1
if related_verts_in_common[1] in f_verts:
repeated_verts += 1
if repeated_verts == len(f_verts):
repeated_face = True
break
if not repeated_face:
faces_verts_idx.append([v1, related_verts_in_common[0],
v2, related_verts_in_common[1]])
# If Two verts have one related vert in common and they are
# related to each other, they form a triangle
elif v2_in_rel_v1 and v1_in_rel_v2 and len(related_verts_in_common) == 1:
# Check if the face is already saved.
for f_verts in faces_verts_idx:
repeated_verts = 0
if len(f_verts) == 3:
if v1 in f_verts:
repeated_verts += 1
if v2 in f_verts:
repeated_verts += 1
if related_verts_in_common[0] in f_verts:
repeated_verts += 1
if repeated_verts == len(f_verts):
repeated_face = True
break
if not repeated_face:
faces_verts_idx.append([v1, related_verts_in_common[0], v2])
# Keep only the faces that don't overlap by ignoring
# quads that overlap with two adjacent triangles
faces_to_not_include_idx = [] # Indices of faces_verts_idx to eliminate
for i in range(len(faces_verts_idx)):
for t in range(len(faces_verts_idx)):
if i != t:
verts_in_common = 0
if len(faces_verts_idx[i]) == 4 and len(faces_verts_idx[t]) == 3:
for v_idx in faces_verts_idx[t]:
if v_idx in faces_verts_idx[i]:
verts_in_common += 1
# If it doesn't have all it's vertices repeated in the other face
if verts_in_common == 3:
if i not in faces_to_not_include_idx:
faces_to_not_include_idx.append(i)
# Build surface
all_surface_verts_co = []
verts_idx_translation = {}
for i in range(len(final_points_ob.data.vertices)):
coords = final_points_ob.data.vertices[i].co
all_surface_verts_co.append([coords[0], coords[1], coords[2]])
# Verts of each face.
all_surface_faces = []
for i in range(len(faces_verts_idx)):
if i not in faces_to_not_include_idx:
face = []
for v_idx in faces_verts_idx[i]:
face.append(v_idx)
all_surface_faces.append(face)
# Build the mesh
surf_me_name = "SURFSKIO_surface"
me_surf = bpy.data.meshes.new(surf_me_name)
me_surf.from_pydata(all_surface_verts_co, [], all_surface_faces)
me_surf.update()
ob_surface = bpy.data.objects.new(surf_me_name, me_surf)
bpy.context.collection.objects.link(ob_surface)
# Delete final points temporal object
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
final_points_ob.select_set(True)
bpy.context.view_layer.objects.active = final_points_ob
bpy.ops.object.delete()
# Delete isolated verts if there are any
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_surface.select_set(True)
bpy.context.view_layer.objects.active = ob_surface
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_face_by_sides(type='NOTEQUAL')
bpy.ops.mesh.delete()
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Join crosshatch results with original mesh
# Calculate a distance to merge the verts of the crosshatch surface to the main object
edges_length_sum = 0
for ed in ob_surface.data.edges:
edges_length_sum += (
ob_surface.data.vertices[ed.vertices[0]].co -
ob_surface.data.vertices[ed.vertices[1]].co
).length
if len(ob_surface.data.edges) > 0:
average_surface_edges_length = edges_length_sum / len(ob_surface.data.edges)
else:
average_surface_edges_length = 0.0001
# Make dictionary with all the verts connected to each vert, on the new surface object.
surface_connected_verts = {}
for ed in ob_surface.data.edges:
if not ed.vertices[0] in surface_connected_verts:
surface_connected_verts[ed.vertices[0]] = []
surface_connected_verts[ed.vertices[0]].append(ed.vertices[1])
if ed.vertices[1] not in surface_connected_verts:
surface_connected_verts[ed.vertices[1]] = []
surface_connected_verts[ed.vertices[1]].append(ed.vertices[0])
# Duplicate the new surface object, and use shrinkwrap to
# calculate later the nearest verts to the main object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
final_ob_duplicate = bpy.context.view_layer.objects.active
bpy.ops.object.modifier_add('INVOKE_REGION_WIN', type='SHRINKWRAP')
shrinkwrap_modifier = final_ob_duplicate.modifiers[-1]
shrinkwrap_modifier.wrap_method = "NEAREST_VERTEX"
shrinkwrap_modifier.target = self.main_object
bpy.ops.object.modifier_apply('INVOKE_REGION_WIN', apply_as='DATA', modifier=shrinkwrap_modifier.name)
# Make list with verts of original mesh as index and coords as value
main_object_verts_coords = []
for v in self.main_object.data.vertices:
coords = self.main_object.matrix_world @ v.co
# To avoid problems when taking "-0.00" as a different value as "0.00"
for c in range(len(coords)):
if "%.3f" % coords[c] == "-0.00":
coords[c] = 0
main_object_verts_coords.append(["%.3f" % coords[0], "%.3f" % coords[1], "%.3f" % coords[2]])
tuple(main_object_verts_coords)
# Determine which verts will be merged, snap them to the nearest verts
# on the original verts, and get them selected
crosshatch_verts_to_merge = []
if self.automatic_join:
for i in range(len(ob_surface.data.vertices)):
# Calculate the distance from each of the connected verts to the actual vert,
# and compare it with the distance they would have if joined.
# If they don't change much, that vert can be joined
merge_actual_vert = True
if len(surface_connected_verts[i]) < 4:
for c_v_idx in surface_connected_verts[i]:
points_original = []
points_original.append(ob_surface.data.vertices[c_v_idx].co)
points_original.append(ob_surface.data.vertices[i].co)
points_target = []
points_target.append(ob_surface.data.vertices[c_v_idx].co)
points_target.append(final_ob_duplicate.data.vertices[i].co)
vec_A = points_original[0] - points_original[1]
vec_B = points_target[0] - points_target[1]
dist_A = (points_original[0] - points_original[1]).length
dist_B = (points_target[0] - points_target[1]).length
if not (
points_original[0] == points_original[1] or
points_target[0] == points_target[1]
): # If any vector's length is zero
angle = vec_A.angle(vec_B) / pi
else:
angle = 0
# Set a range of acceptable variation in the connected edges
if dist_B > dist_A * 1.7 * self.join_stretch_factor or \
dist_B < dist_A / 2 / self.join_stretch_factor or \
angle >= 0.15 * self.join_stretch_factor:
merge_actual_vert = False
break
else:
merge_actual_vert = False
if merge_actual_vert:
coords = final_ob_duplicate.data.vertices[i].co
# To avoid problems when taking "-0.000" as a different value as "0.00"
for c in range(len(coords)):
if "%.3f" % coords[c] == "-0.00":
coords[c] = 0
comparison_coords = ["%.3f" % coords[0], "%.3f" % coords[1], "%.3f" % coords[2]]
if comparison_coords in main_object_verts_coords:
# Get the index of the vert with those coords in the main object
main_object_related_vert_idx = main_object_verts_coords.index(comparison_coords)
if self.main_object.data.vertices[main_object_related_vert_idx].select is True or \
self.main_object_selected_verts_count == 0:
ob_surface.data.vertices[i].co = final_ob_duplicate.data.vertices[i].co
ob_surface.data.vertices[i].select_set(True)
crosshatch_verts_to_merge.append(i)
# Make sure the vert in the main object is selected,
# in case it wasn't selected and the "join crosshatch" option is active
self.main_object.data.vertices[main_object_related_vert_idx].select_set(True)
# Delete duplicated object
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
final_ob_duplicate.select_set(True)
bpy.context.view_layer.objects.active = final_ob_duplicate
bpy.ops.object.delete()
# Join crosshatched surface and main object
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_surface.select_set(True)
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.join('INVOKE_REGION_WIN')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Perform Remove doubles to merge verts
if not (self.automatic_join is False and self.main_object_selected_verts_count == 0):
bpy.ops.mesh.remove_doubles(threshold=0.0001)
bpy.ops.mesh.select_all(action='DESELECT')
# If the main object has modifiers, turn their "viewport view status"
# to what it was before the forced deactivation above
if len(self.main_object.modifiers) > 0:
for m_idx in range(len(self.main_object.modifiers)):
self.main_object.modifiers[m_idx].show_viewport = self.modifiers_prev_viewport_state[m_idx]
return {'FINISHED'}
def rectangular_surface(self):
# Selected edges
all_selected_edges_idx = []
all_selected_verts = []
all_verts_idx = []
for ed in self.main_object.data.edges:
if ed.select:
all_selected_edges_idx.append(ed.index)
# Selected vertices
if not ed.vertices[0] in all_selected_verts:
all_selected_verts.append(self.main_object.data.vertices[ed.vertices[0]])
if not ed.vertices[1] in all_selected_verts:
all_selected_verts.append(self.main_object.data.vertices[ed.vertices[1]])
# All verts (both from each edge) to determine later
# which are at the tips (those not repeated twice)
all_verts_idx.append(ed.vertices[0])
all_verts_idx.append(ed.vertices[1])
# Identify the tips and "middle-vertex" that separates U from V, if there is one
all_chains_tips_idx = []
for v_idx in all_verts_idx:
if all_verts_idx.count(v_idx) < 2:
all_chains_tips_idx.append(v_idx)
edges_connected_to_tips = []
for ed in self.main_object.data.edges:
if (ed.vertices[0] in all_chains_tips_idx or ed.vertices[1] in all_chains_tips_idx) and \
not (ed.vertices[0] in all_verts_idx and ed.vertices[1] in all_verts_idx):
edges_connected_to_tips.append(ed)
# Check closed selections
# List with groups of three verts, where the first element of the pair is
# the unselected vert of a closed selection and the other two elements are the
# selected neighbor verts (it will be useful to determine which selection chain
# the unselected vert belongs to, and determine the "middle-vertex")
single_unselected_verts_and_neighbors = []
# To identify a "closed" selection (a selection that is a closed chain except
# for one vertex) find the vertex in common that have the edges connected to tips.
# If there is a vertex in common, that one is the unselected vert that closes
# the selection or is a "middle-vertex"
single_unselected_verts = []
for ed in edges_connected_to_tips:
for ed_b in edges_connected_to_tips:
if ed != ed_b:
if ed.vertices[0] == ed_b.vertices[0] and \
not self.main_object.data.vertices[ed.vertices[0]].select and \
ed.vertices[0] not in single_unselected_verts:
# The second element is one of the tips of the selected
# vertices of the closed selection
single_unselected_verts_and_neighbors.append(
[ed.vertices[0], ed.vertices[1], ed_b.vertices[1]]
)
single_unselected_verts.append(ed.vertices[0])
break
elif ed.vertices[0] == ed_b.vertices[1] and \
not self.main_object.data.vertices[ed.vertices[0]].select and \
ed.vertices[0] not in single_unselected_verts:
single_unselected_verts_and_neighbors.append(
[ed.vertices[0], ed.vertices[1], ed_b.vertices[0]]
)
single_unselected_verts.append(ed.vertices[0])
break
elif ed.vertices[1] == ed_b.vertices[0] and \
not self.main_object.data.vertices[ed.vertices[1]].select and \
ed.vertices[1] not in single_unselected_verts:
single_unselected_verts_and_neighbors.append(
[ed.vertices[1], ed.vertices[0], ed_b.vertices[1]]
)
single_unselected_verts.append(ed.vertices[1])
break
elif ed.vertices[1] == ed_b.vertices[1] and \
not self.main_object.data.vertices[ed.vertices[1]].select and \
ed.vertices[1] not in single_unselected_verts:
single_unselected_verts_and_neighbors.append(
[ed.vertices[1], ed.vertices[0], ed_b.vertices[0]]
)
single_unselected_verts.append(ed.vertices[1])
break
middle_vertex_idx = None
tips_to_discard_idx = []
# Check if there is a "middle-vertex", and get its index
for i in range(0, len(single_unselected_verts_and_neighbors)):
actual_chain_verts = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, single_unselected_verts_and_neighbors[i][1],
None, None
)
if single_unselected_verts_and_neighbors[i][2] != \
actual_chain_verts[len(actual_chain_verts) - 1].index:
middle_vertex_idx = single_unselected_verts_and_neighbors[i][0]
tips_to_discard_idx.append(single_unselected_verts_and_neighbors[i][1])
tips_to_discard_idx.append(single_unselected_verts_and_neighbors[i][2])
# List with pairs of verts that belong to the tips of each selection chain (row)
verts_tips_same_chain_idx = []
if len(all_chains_tips_idx) >= 2:
checked_v = []
for i in range(0, len(all_chains_tips_idx)):
if all_chains_tips_idx[i] not in checked_v:
v_chain = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, all_chains_tips_idx[i],
middle_vertex_idx, None
)
verts_tips_same_chain_idx.append([v_chain[0].index, v_chain[len(v_chain) - 1].index])
checked_v.append(v_chain[0].index)
checked_v.append(v_chain[len(v_chain) - 1].index)
# Selection tips (vertices).
verts_tips_parsed_idx = []
if len(all_chains_tips_idx) >= 2:
for spec_v_idx in all_chains_tips_idx:
if (spec_v_idx not in tips_to_discard_idx):
verts_tips_parsed_idx.append(spec_v_idx)
# Identify the type of selection made by the user
if middle_vertex_idx is not None:
# If there are 4 tips (two selection chains), and
# there is only one single unselected vert (the middle vert)
if len(all_chains_tips_idx) == 4 and len(single_unselected_verts_and_neighbors) == 1:
selection_type = "TWO_CONNECTED"
else:
# The type of the selection was not identified, the script stops.
self.report({'WARNING'}, "The selection isn't valid.")
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.cleanup_on_interruption()
self.stopping_errors = True
return{'CANCELLED'}
else:
if len(all_chains_tips_idx) == 2: # If there are 2 tips
selection_type = "SINGLE"
elif len(all_chains_tips_idx) == 4: # If there are 4 tips
selection_type = "TWO_NOT_CONNECTED"
elif len(all_chains_tips_idx) == 0:
if len(self.main_splines.data.splines) > 1:
selection_type = "NO_SELECTION"
else:
# If the selection was not identified and there is only one stroke,
# there's no possibility to build a surface, so the script is interrupted
self.report({'WARNING'}, "The selection isn't valid.")
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.cleanup_on_interruption()
self.stopping_errors = True
return{'CANCELLED'}
else:
# The type of the selection was not identified, the script stops
self.report({'WARNING'}, "The selection isn't valid.")
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.cleanup_on_interruption()
self.stopping_errors = True
return{'CANCELLED'}
# If the selection type is TWO_NOT_CONNECTED and there is only one stroke, stop the script
if selection_type == "TWO_NOT_CONNECTED" and len(self.main_splines.data.splines) == 1:
self.report({'WARNING'},
"At least two strokes are needed when there are two not connected selections")
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.cleanup_on_interruption()
self.stopping_errors = True
return{'CANCELLED'}
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_splines.select_set(True)
bpy.context.view_layer.objects.active = self.main_splines
# Enter editmode for the new curve (converted from grease pencil strokes), to smooth it out
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.curve.smooth('INVOKE_REGION_WIN')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.selection_U_exists = False
self.selection_U2_exists = False
self.selection_V_exists = False
self.selection_V2_exists = False
self.selection_U_is_closed = False
self.selection_U2_is_closed = False
self.selection_V_is_closed = False
self.selection_V2_is_closed = False
# Define what vertices are at the tips of each selection and are not the middle-vertex
if selection_type == "TWO_CONNECTED":
self.selection_U_exists = True
self.selection_V_exists = True
closing_vert_U_idx = None
closing_vert_V_idx = None
closing_vert_U2_idx = None
closing_vert_V2_idx = None
# Determine which selection is Selection-U and which is Selection-V
points_A = []
points_B = []
points_first_stroke_tips = []
points_A.append(
self.main_object.matrix_world @ self.main_object.data.vertices[verts_tips_parsed_idx[0]].co
)
points_A.append(
self.main_object.matrix_world @ self.main_object.data.vertices[middle_vertex_idx].co
)
points_B.append(
self.main_object.matrix_world @ self.main_object.data.vertices[verts_tips_parsed_idx[1]].co
)
points_B.append(
self.main_object.matrix_world @ self.main_object.data.vertices[middle_vertex_idx].co
)
points_first_stroke_tips.append(
self.main_splines.data.splines[0].bezier_points[0].co
)
points_first_stroke_tips.append(
self.main_splines.data.splines[0].bezier_points[
len(self.main_splines.data.splines[0].bezier_points) - 1
].co
)
angle_A = self.orientation_difference(points_A, points_first_stroke_tips)
angle_B = self.orientation_difference(points_B, points_first_stroke_tips)
if angle_A < angle_B:
first_vert_U_idx = verts_tips_parsed_idx[0]
first_vert_V_idx = verts_tips_parsed_idx[1]
else:
first_vert_U_idx = verts_tips_parsed_idx[1]
first_vert_V_idx = verts_tips_parsed_idx[0]
elif selection_type == "SINGLE" or selection_type == "TWO_NOT_CONNECTED":
first_sketched_point_first_stroke_co = self.main_splines.data.splines[0].bezier_points[0].co
last_sketched_point_first_stroke_co = \
self.main_splines.data.splines[0].bezier_points[
len(self.main_splines.data.splines[0].bezier_points) - 1
].co
first_sketched_point_last_stroke_co = \
self.main_splines.data.splines[
len(self.main_splines.data.splines) - 1
].bezier_points[0].co
if len(self.main_splines.data.splines) > 1:
first_sketched_point_second_stroke_co = self.main_splines.data.splines[1].bezier_points[0].co
last_sketched_point_second_stroke_co = \
self.main_splines.data.splines[1].bezier_points[
len(self.main_splines.data.splines[1].bezier_points) - 1
].co
single_unselected_neighbors = [] # Only the neighbors of the single unselected verts
for verts_neig_idx in single_unselected_verts_and_neighbors:
single_unselected_neighbors.append(verts_neig_idx[1])
single_unselected_neighbors.append(verts_neig_idx[2])
all_chains_tips_and_middle_vert = []
for v_idx in all_chains_tips_idx:
if v_idx not in single_unselected_neighbors:
all_chains_tips_and_middle_vert.append(v_idx)
all_chains_tips_and_middle_vert += single_unselected_verts
all_participating_verts = all_chains_tips_and_middle_vert + all_verts_idx
# The tip of the selected vertices nearest to the first point of the first sketched stroke
nearest_tip_to_first_st_first_pt_idx, shortest_distance_to_first_stroke = \
self.shortest_distance(
self.main_object,
first_sketched_point_first_stroke_co,
all_chains_tips_and_middle_vert
)
# If the nearest tip is not from a closed selection, get the opposite tip vertex index
if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or \
nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx:
nearest_tip_to_first_st_first_pt_opposite_idx = \
self.opposite_tip(
nearest_tip_to_first_st_first_pt_idx,
verts_tips_same_chain_idx
)
# The tip of the selected vertices nearest to the last point of the first sketched stroke
nearest_tip_to_first_st_last_pt_idx, temp_dist = \
self.shortest_distance(
self.main_object,
last_sketched_point_first_stroke_co,
all_chains_tips_and_middle_vert
)
# The tip of the selected vertices nearest to the first point of the last sketched stroke
nearest_tip_to_last_st_first_pt_idx, shortest_distance_to_last_stroke = \
self.shortest_distance(
self.main_object,
first_sketched_point_last_stroke_co,
all_chains_tips_and_middle_vert
)
if len(self.main_splines.data.splines) > 1:
# The selected vertex nearest to the first point of the second sketched stroke
# (This will be useful to determine the direction of the closed
# selection V when extruding along strokes)
nearest_vert_to_second_st_first_pt_idx, temp_dist = \
self.shortest_distance(
self.main_object,
first_sketched_point_second_stroke_co,
all_verts_idx
)
# The selected vertex nearest to the first point of the second sketched stroke
# (This will be useful to determine the direction of the closed
# selection V2 when extruding along strokes)
nearest_vert_to_second_st_last_pt_idx, temp_dist = \
self.shortest_distance(
self.main_object,
last_sketched_point_second_stroke_co,
all_verts_idx
)
# Determine if the single selection will be treated as U or as V
edges_sum = 0
for i in all_selected_edges_idx:
edges_sum += (
(self.main_object.matrix_world @
self.main_object.data.vertices[self.main_object.data.edges[i].vertices[0]].co) -
(self.main_object.matrix_world @
self.main_object.data.vertices[self.main_object.data.edges[i].vertices[1]].co)
).length
average_edge_length = edges_sum / len(all_selected_edges_idx)
# Get shortest distance from the first point of the last stroke to any participating vertex
temp_idx, shortest_distance_to_last_stroke = \
self.shortest_distance(
self.main_object,
first_sketched_point_last_stroke_co,
all_participating_verts
)
# If the beginning of the first stroke is near enough, and its orientation
# difference with the first edge of the nearest selection chain is not too high,
# interpret things as an "extrude along strokes" instead of "extrude through strokes"
if shortest_distance_to_first_stroke < average_edge_length / 4 and \
shortest_distance_to_last_stroke < average_edge_length and \
len(self.main_splines.data.splines) > 1:
self.selection_U_exists = False
self.selection_V_exists = True
# If the first selection is not closed
if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or \
nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx:
self.selection_V_is_closed = False
first_neighbor_V_idx = None
closing_vert_U_idx = None
closing_vert_U2_idx = None
closing_vert_V_idx = None
closing_vert_V2_idx = None
first_vert_V_idx = nearest_tip_to_first_st_first_pt_idx
if selection_type == "TWO_NOT_CONNECTED":
self.selection_V2_exists = True
first_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
else:
self.selection_V_is_closed = True
closing_vert_V_idx = nearest_tip_to_first_st_first_pt_idx
# Get the neighbors of the first (unselected) vert of the closed selection U.
vert_neighbors = []
for verts in single_unselected_verts_and_neighbors:
if verts[0] == nearest_tip_to_first_st_first_pt_idx:
vert_neighbors.append(verts[1])
vert_neighbors.append(verts[2])
break
verts_V = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, vert_neighbors[0], middle_vertex_idx, None
)
for i in range(0, len(verts_V)):
if verts_V[i].index == nearest_vert_to_second_st_first_pt_idx:
# If the vertex nearest to the first point of the second stroke
# is in the first half of the selected verts
if i >= len(verts_V) / 2:
first_vert_V_idx = vert_neighbors[1]
break
else:
first_vert_V_idx = vert_neighbors[0]
break
if selection_type == "TWO_NOT_CONNECTED":
self.selection_V2_exists = True
# If the second selection is not closed
if nearest_tip_to_first_st_last_pt_idx not in single_unselected_verts or \
nearest_tip_to_first_st_last_pt_idx == middle_vertex_idx:
self.selection_V2_is_closed = False
first_neighbor_V2_idx = None
closing_vert_V2_idx = None
first_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
else:
self.selection_V2_is_closed = True
closing_vert_V2_idx = nearest_tip_to_first_st_last_pt_idx
# Get the neighbors of the first (unselected) vert of the closed selection U
vert_neighbors = []
for verts in single_unselected_verts_and_neighbors:
if verts[0] == nearest_tip_to_first_st_last_pt_idx:
vert_neighbors.append(verts[1])
vert_neighbors.append(verts[2])
break
verts_V2 = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, vert_neighbors[0], middle_vertex_idx, None
)
for i in range(0, len(verts_V2)):
if verts_V2[i].index == nearest_vert_to_second_st_last_pt_idx:
# If the vertex nearest to the first point of the second stroke
# is in the first half of the selected verts
if i >= len(verts_V2) / 2:
first_vert_V2_idx = vert_neighbors[1]
break
else:
first_vert_V2_idx = vert_neighbors[0]
break
else:
self.selection_V2_exists = False
else:
self.selection_U_exists = True
self.selection_V_exists = False
# If the first selection is not closed
if nearest_tip_to_first_st_first_pt_idx not in single_unselected_verts or \
nearest_tip_to_first_st_first_pt_idx == middle_vertex_idx:
self.selection_U_is_closed = False
first_neighbor_U_idx = None
closing_vert_U_idx = None
points_tips = []
points_tips.append(
self.main_object.matrix_world @
self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_idx].co
)
points_tips.append(
self.main_object.matrix_world @
self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_opposite_idx].co
)
points_first_stroke_tips = []
points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[0].co)
points_first_stroke_tips.append(
self.main_splines.data.splines[0].bezier_points[
len(self.main_splines.data.splines[0].bezier_points) - 1
].co
)
vec_A = points_tips[0] - points_tips[1]
vec_B = points_first_stroke_tips[0] - points_first_stroke_tips[1]
# Compare the direction of the selection and the first
# grease pencil stroke to determine which is the "first" vertex of the selection
if vec_A.dot(vec_B) < 0:
first_vert_U_idx = nearest_tip_to_first_st_first_pt_opposite_idx
else:
first_vert_U_idx = nearest_tip_to_first_st_first_pt_idx
else:
self.selection_U_is_closed = True
closing_vert_U_idx = nearest_tip_to_first_st_first_pt_idx
# Get the neighbors of the first (unselected) vert of the closed selection U
vert_neighbors = []
for verts in single_unselected_verts_and_neighbors:
if verts[0] == nearest_tip_to_first_st_first_pt_idx:
vert_neighbors.append(verts[1])
vert_neighbors.append(verts[2])
break
points_first_and_neighbor = []
points_first_and_neighbor.append(
self.main_object.matrix_world @
self.main_object.data.vertices[nearest_tip_to_first_st_first_pt_idx].co
)
points_first_and_neighbor.append(
self.main_object.matrix_world @
self.main_object.data.vertices[vert_neighbors[0]].co
)
points_first_stroke_tips = []
points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[0].co)
points_first_stroke_tips.append(self.main_splines.data.splines[0].bezier_points[1].co)
vec_A = points_first_and_neighbor[0] - points_first_and_neighbor[1]
vec_B = points_first_stroke_tips[0] - points_first_stroke_tips[1]
# Compare the direction of the selection and the first grease pencil stroke to
# determine which is the vertex neighbor to the first vertex (unselected) of
# the closed selection. This will determine the direction of the closed selection
if vec_A.dot(vec_B) < 0:
first_vert_U_idx = vert_neighbors[1]
else:
first_vert_U_idx = vert_neighbors[0]
if selection_type == "TWO_NOT_CONNECTED":
self.selection_U2_exists = True
# If the second selection is not closed
if nearest_tip_to_last_st_first_pt_idx not in single_unselected_verts or \
nearest_tip_to_last_st_first_pt_idx == middle_vertex_idx:
self.selection_U2_is_closed = False
first_neighbor_U2_idx = None
closing_vert_U2_idx = None
first_vert_U2_idx = nearest_tip_to_last_st_first_pt_idx
else:
self.selection_U2_is_closed = True
closing_vert_U2_idx = nearest_tip_to_last_st_first_pt_idx
# Get the neighbors of the first (unselected) vert of the closed selection U
vert_neighbors = []
for verts in single_unselected_verts_and_neighbors:
if verts[0] == nearest_tip_to_last_st_first_pt_idx:
vert_neighbors.append(verts[1])
vert_neighbors.append(verts[2])
break
points_first_and_neighbor = []
points_first_and_neighbor.append(
self.main_object.matrix_world @
self.main_object.data.vertices[nearest_tip_to_last_st_first_pt_idx].co
)
points_first_and_neighbor.append(
self.main_object.matrix_world @
self.main_object.data.vertices[vert_neighbors[0]].co
)
points_last_stroke_tips = []
points_last_stroke_tips.append(
self.main_splines.data.splines[
len(self.main_splines.data.splines) - 1
].bezier_points[0].co
)
points_last_stroke_tips.append(
self.main_splines.data.splines[
len(self.main_splines.data.splines) - 1
].bezier_points[1].co
)
vec_A = points_first_and_neighbor[0] - points_first_and_neighbor[1]
vec_B = points_last_stroke_tips[0] - points_last_stroke_tips[1]
# Compare the direction of the selection and the last grease pencil stroke to
# determine which is the vertex neighbor to the first vertex (unselected) of
# the closed selection. This will determine the direction of the closed selection
if vec_A.dot(vec_B) < 0:
first_vert_U2_idx = vert_neighbors[1]
else:
first_vert_U2_idx = vert_neighbors[0]
else:
self.selection_U2_exists = False
elif selection_type == "NO_SELECTION":
self.selection_U_exists = False
self.selection_V_exists = False
# Get an ordered list of the vertices of Selection-U
verts_ordered_U = []
if self.selection_U_exists:
verts_ordered_U = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, first_vert_U_idx,
middle_vertex_idx, closing_vert_U_idx
)
verts_ordered_U_indices = [x.index for x in verts_ordered_U]
# Get an ordered list of the vertices of Selection-U2
verts_ordered_U2 = []
if self.selection_U2_exists:
verts_ordered_U2 = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, first_vert_U2_idx,
middle_vertex_idx, closing_vert_U2_idx
)
verts_ordered_U2_indices = [x.index for x in verts_ordered_U2]
# Get an ordered list of the vertices of Selection-V
verts_ordered_V = []
if self.selection_V_exists:
verts_ordered_V = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, first_vert_V_idx,
middle_vertex_idx, closing_vert_V_idx
)
verts_ordered_V_indices = [x.index for x in verts_ordered_V]
# Get an ordered list of the vertices of Selection-V2
verts_ordered_V2 = []
if self.selection_V2_exists:
verts_ordered_V2 = self.get_ordered_verts(
self.main_object, all_selected_edges_idx,
all_verts_idx, first_vert_V2_idx,
middle_vertex_idx, closing_vert_V2_idx
)
verts_ordered_V2_indices = [x.index for x in verts_ordered_V2]
# Check if when there are two-not-connected selections both have the same
# number of verts. If not terminate the script
if ((self.selection_U2_exists and len(verts_ordered_U) != len(verts_ordered_U2)) or
(self.selection_V2_exists and len(verts_ordered_V) != len(verts_ordered_V2))):
# Display a warning
self.report({'WARNING'}, "Both selections must have the same number of edges")
self.cleanup_on_interruption()
self.stopping_errors = True
return{'CANCELLED'}
# Calculate edges U proportions
# Sum selected edges U lengths
edges_lengths_U = []
edges_lengths_sum_U = 0
if self.selection_U_exists:
edges_lengths_U, edges_lengths_sum_U = self.get_chain_length(
self.main_object,
verts_ordered_U
)
if self.selection_U2_exists:
edges_lengths_U2, edges_lengths_sum_U2 = self.get_chain_length(
self.main_object,
verts_ordered_U2
)
# Sum selected edges V lengths
edges_lengths_V = []
edges_lengths_sum_V = 0
if self.selection_V_exists:
edges_lengths_V, edges_lengths_sum_V = self.get_chain_length(
self.main_object,
verts_ordered_V
)
if self.selection_V2_exists:
edges_lengths_V2, edges_lengths_sum_V2 = self.get_chain_length(
self.main_object,
verts_ordered_V2
)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.subdivide('INVOKE_REGION_WIN',
number_cuts=bpy.context.scene.bsurfaces.SURFSK_precision)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Proportions U
edges_proportions_U = []
edges_proportions_U = self.get_edges_proportions(
edges_lengths_U, edges_lengths_sum_U,
self.selection_U_exists, self.edges_U
)
verts_count_U = len(edges_proportions_U) + 1
if self.selection_U2_exists:
edges_proportions_U2 = []
edges_proportions_U2 = self.get_edges_proportions(
edges_lengths_U2, edges_lengths_sum_U2,
self.selection_U2_exists, self.edges_V
)
verts_count_U2 = len(edges_proportions_U2) + 1
# Proportions V
edges_proportions_V = []
edges_proportions_V = self.get_edges_proportions(
edges_lengths_V, edges_lengths_sum_V,
self.selection_V_exists, self.edges_V
)
verts_count_V = len(edges_proportions_V) + 1
if self.selection_V2_exists:
edges_proportions_V2 = []
edges_proportions_V2 = self.get_edges_proportions(
edges_lengths_V2, edges_lengths_sum_V2,
self.selection_V2_exists, self.edges_V
)
verts_count_V2 = len(edges_proportions_V2) + 1
# Cyclic Follow: simplify sketched curves, make them Cyclic, and complete
# the actual sketched curves with a "closing segment"
if self.cyclic_follow and not self.selection_V_exists and not \
((self.selection_U_exists and not self.selection_U_is_closed) or
(self.selection_U2_exists and not self.selection_U2_is_closed)):
simplified_spline_coords = []
simplified_curve = []
ob_simplified_curve = []
splines_first_v_co = []
for i in range(len(self.main_splines.data.splines)):
# Create a curve object for the actual spline "cyclic extension"
simplified_curve.append(bpy.data.curves.new('SURFSKIO_simpl_crv', 'CURVE'))
ob_simplified_curve.append(bpy.data.objects.new('SURFSKIO_simpl_crv', simplified_curve[i]))
bpy.context.collection.objects.link(ob_simplified_curve[i])
simplified_curve[i].dimensions = "3D"
spline_coords = []
for bp in self.main_splines.data.splines[i].bezier_points:
spline_coords.append(bp.co)
# Simplification
simplified_spline_coords.append(self.simplify_spline(spline_coords, 5))
# Get the coordinates of the first vert of the actual spline
splines_first_v_co.append(simplified_spline_coords[i][0])
# Generate the spline
spline = simplified_curve[i].splines.new('BEZIER')
# less one because one point is added when the spline is created
spline.bezier_points.add(len(simplified_spline_coords[i]) - 1)
for p in range(0, len(simplified_spline_coords[i])):
spline.bezier_points[p].co = simplified_spline_coords[i][p]
spline.use_cyclic_u = True
spline_bp_count = len(spline.bezier_points)
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_simplified_curve[i].select_set(True)
bpy.context.view_layer.objects.active = ob_simplified_curve[i]
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='SELECT')
bpy.ops.curve.handle_type_set('INVOKE_REGION_WIN', type='AUTOMATIC')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Select the "closing segment", and subdivide it
ob_simplified_curve[i].data.splines[0].bezier_points[0].select_control_point = True
ob_simplified_curve[i].data.splines[0].bezier_points[0].select_left_handle = True
ob_simplified_curve[i].data.splines[0].bezier_points[0].select_right_handle = True
ob_simplified_curve[i].data.splines[0].bezier_points[spline_bp_count - 1].select_control_point = True
ob_simplified_curve[i].data.splines[0].bezier_points[spline_bp_count - 1].select_left_handle = True
ob_simplified_curve[i].data.splines[0].bezier_points[spline_bp_count - 1].select_right_handle = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
segments = sqrt(
(ob_simplified_curve[i].data.splines[0].bezier_points[0].co -
ob_simplified_curve[i].data.splines[0].bezier_points[spline_bp_count - 1].co).length /
self.average_gp_segment_length
)
for t in range(2):
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=segments)
# Delete the other vertices and make it non-cyclic to
# keep only the needed verts of the "closing segment"
bpy.ops.curve.select_all(action='INVERT')
bpy.ops.curve.delete(type='VERT')
ob_simplified_curve[i].data.splines[0].use_cyclic_u = False
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Add the points of the "closing segment" to the original curve from grease pencil stroke
first_new_index = len(self.main_splines.data.splines[i].bezier_points)
self.main_splines.data.splines[i].bezier_points.add(
len(ob_simplified_curve[i].data.splines[0].bezier_points) - 1
)
for t in range(1, len(ob_simplified_curve[i].data.splines[0].bezier_points)):
self.main_splines.data.splines[i].bezier_points[t - 1 + first_new_index].co = \
ob_simplified_curve[i].data.splines[0].bezier_points[t].co
# Delete the temporal curve
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_simplified_curve[i].select_set(True)
bpy.context.view_layer.objects.active = ob_simplified_curve[i]
bpy.ops.object.delete()
# Get the coords of the points distributed along the sketched strokes,
# with proportions-U of the first selection
pts_on_strokes_with_proportions_U = self.distribute_pts(
self.main_splines.data.splines,
edges_proportions_U
)
sketched_splines_parsed = []
if self.selection_U2_exists:
# Initialize the multidimensional list with the proportions of all the segments
proportions_loops_crossing_strokes = []
for i in range(len(pts_on_strokes_with_proportions_U)):
proportions_loops_crossing_strokes.append([])
for t in range(len(pts_on_strokes_with_proportions_U[0])):
proportions_loops_crossing_strokes[i].append(None)
# Calculate the proportions of each segment of the loops-U from pts_on_strokes_with_proportions_U
for lp in range(len(pts_on_strokes_with_proportions_U[0])):
loop_segments_lengths = []
for st in range(len(pts_on_strokes_with_proportions_U)):
# When on the first stroke, add the segment from the selection to the dirst stroke
if st == 0:
loop_segments_lengths.append(
((self.main_object.matrix_world @ verts_ordered_U[lp].co) -
pts_on_strokes_with_proportions_U[0][lp]).length
)
# For all strokes except for the last, calculate the distance
# from the actual stroke to the next
if st != len(pts_on_strokes_with_proportions_U) - 1:
loop_segments_lengths.append(
(pts_on_strokes_with_proportions_U[st][lp] -
pts_on_strokes_with_proportions_U[st + 1][lp]).length
)
# When on the last stroke, add the segments
# from the last stroke to the second selection
if st == len(pts_on_strokes_with_proportions_U) - 1:
loop_segments_lengths.append(
(pts_on_strokes_with_proportions_U[st][lp] -
(self.main_object.matrix_world @ verts_ordered_U2[lp].co)).length
)
# Calculate full loop length
loop_seg_lengths_sum = 0
for i in range(len(loop_segments_lengths)):
loop_seg_lengths_sum += loop_segments_lengths[i]
# Fill the multidimensional list with the proportions of all the segments
for st in range(len(pts_on_strokes_with_proportions_U)):
proportions_loops_crossing_strokes[st][lp] = \
loop_segments_lengths[st] / loop_seg_lengths_sum
# Calculate proportions for each stroke
for st in range(len(pts_on_strokes_with_proportions_U)):
actual_stroke_spline = []
# Needs to be a list for the "distribute_pts" method
actual_stroke_spline.append(self.main_splines.data.splines[st])
# Calculate the proportions for the actual stroke.
actual_edges_proportions_U = []
for i in range(len(edges_proportions_U)):
proportions_sum = 0
# Sum the proportions of this loop up to the actual.
for t in range(0, st + 1):
proportions_sum += proportions_loops_crossing_strokes[t][i]
# i + 1, because proportions_loops_crossing_strokes refers to loops,
# and the proportions refer to edges, so we start at the element 1
# of proportions_loops_crossing_strokes instead of element 0
actual_edges_proportions_U.append(
edges_proportions_U[i] -
((edges_proportions_U[i] - edges_proportions_U2[i]) * proportions_sum)
)
points_actual_spline = self.distribute_pts(actual_stroke_spline, actual_edges_proportions_U)
sketched_splines_parsed.append(points_actual_spline[0])
else:
sketched_splines_parsed = pts_on_strokes_with_proportions_U
# If the selection type is "TWO_NOT_CONNECTED" replace the
# points of the last spline with the points in the "target" selection
if selection_type == "TWO_NOT_CONNECTED":
if self.selection_U2_exists:
for i in range(0, len(sketched_splines_parsed[len(sketched_splines_parsed) - 1])):
sketched_splines_parsed[len(sketched_splines_parsed) - 1][i] = \
self.main_object.matrix_world @ verts_ordered_U2[i].co
# Create temporary curves along the "control-points" found
# on the sketched curves and the mesh selection
mesh_ctrl_pts_name = "SURFSKIO_ctrl_pts"
me = bpy.data.meshes.new(mesh_ctrl_pts_name)
ob_ctrl_pts = bpy.data.objects.new(mesh_ctrl_pts_name, me)
ob_ctrl_pts.data = me
bpy.context.collection.objects.link(ob_ctrl_pts)
cyclic_loops_U = []
first_verts = []
second_verts = []
last_verts = []
for i in range(0, verts_count_U):
vert_num_in_spline = 1
if self.selection_U_exists:
ob_ctrl_pts.data.vertices.add(1)
last_v = ob_ctrl_pts.data.vertices[len(ob_ctrl_pts.data.vertices) - 1]
last_v.co = self.main_object.matrix_world @ verts_ordered_U[i].co
vert_num_in_spline += 1
for t in range(0, len(sketched_splines_parsed)):
ob_ctrl_pts.data.vertices.add(1)
v = ob_ctrl_pts.data.vertices[len(ob_ctrl_pts.data.vertices) - 1]
v.co = sketched_splines_parsed[t][i]
if vert_num_in_spline > 1:
ob_ctrl_pts.data.edges.add(1)
ob_ctrl_pts.data.edges[len(ob_ctrl_pts.data.edges) - 1].vertices[0] = \
len(ob_ctrl_pts.data.vertices) - 2
ob_ctrl_pts.data.edges[len(ob_ctrl_pts.data.edges) - 1].vertices[1] = \
len(ob_ctrl_pts.data.vertices) - 1
if t == 0:
first_verts.append(v.index)
if t == 1:
second_verts.append(v.index)
if t == len(sketched_splines_parsed) - 1:
last_verts.append(v.index)
last_v = v
vert_num_in_spline += 1
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_ctrl_pts.select_set(True)
bpy.context.view_layer.objects.active = ob_ctrl_pts
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Determine which loops-U will be "Cyclic"
for i in range(0, len(first_verts)):
# When there is Cyclic Cross there is no need of
# Automatic Join, (and there are at least three strokes)
if self.automatic_join and not self.cyclic_cross and \
selection_type != "TWO_CONNECTED" and len(self.main_splines.data.splines) >= 3:
v = ob_ctrl_pts.data.vertices
first_point_co = v[first_verts[i]].co
second_point_co = v[second_verts[i]].co
last_point_co = v[last_verts[i]].co
# Coordinates of the point in the center of both the first and last verts.
verts_center_co = [
(first_point_co[0] + last_point_co[0]) / 2,
(first_point_co[1] + last_point_co[1]) / 2,
(first_point_co[2] + last_point_co[2]) / 2
]
vec_A = second_point_co - first_point_co
vec_B = second_point_co - Vector(verts_center_co)
# Calculate the length of the first segment of the loop,
# and the length it would have after moving the first vert
# to the middle position between first and last
length_original = (second_point_co - first_point_co).length
length_target = (second_point_co - Vector(verts_center_co)).length
angle = vec_A.angle(vec_B) / pi
# If the target length doesn't stretch too much, and the
# its angle doesn't change to much either
if length_target <= length_original * 1.03 * self.join_stretch_factor and \
angle <= 0.008 * self.join_stretch_factor and not self.selection_U_exists:
cyclic_loops_U.append(True)
# Move the first vert to the center coordinates
ob_ctrl_pts.data.vertices[first_verts[i]].co = verts_center_co
# Select the last verts from Cyclic loops, for later deletion all at once
v[last_verts[i]].select_set(True)
else:
cyclic_loops_U.append(False)
else:
# If "Cyclic Cross" is active then "all" crossing curves become cyclic
if self.cyclic_cross and not self.selection_U_exists and not \
((self.selection_V_exists and not self.selection_V_is_closed) or
(self.selection_V2_exists and not self.selection_V2_is_closed)):
cyclic_loops_U.append(True)
else:
cyclic_loops_U.append(False)
# The cyclic_loops_U list needs to be reversed.
cyclic_loops_U.reverse()
# Delete the previously selected (last_)verts.
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.delete('INVOKE_REGION_WIN', type='VERT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Create curves from control points.
bpy.ops.object.convert('INVOKE_REGION_WIN', target='CURVE', keep_original=False)
ob_curves_surf = bpy.context.view_layer.objects.active
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.spline_type_set('INVOKE_REGION_WIN', type='BEZIER')
bpy.ops.curve.handle_type_set('INVOKE_REGION_WIN', type='AUTOMATIC')
# Make Cyclic the splines designated as Cyclic.
for i in range(0, len(cyclic_loops_U)):
ob_curves_surf.data.splines[i].use_cyclic_u = cyclic_loops_U[i]
# Get the coords of all points on first loop-U, for later comparison with its
# subdivided version, to know which points of the loops-U are crossed by the
# original strokes. The indices will be the same for the other loops-U
if self.loops_on_strokes:
coords_loops_U_control_points = []
for p in ob_ctrl_pts.data.splines[0].bezier_points:
coords_loops_U_control_points.append(["%.4f" % p.co[0], "%.4f" % p.co[1], "%.4f" % p.co[2]])
tuple(coords_loops_U_control_points)
# Calculate number of edges-V in case option "Loops on strokes" is active or inactive
if self.loops_on_strokes and not self.selection_V_exists:
edges_V_count = len(self.main_splines.data.splines) * self.edges_V
else:
edges_V_count = len(edges_proportions_V)
# The Follow precision will vary depending on the number of Follow face-loops
precision_multiplier = round(2 + (edges_V_count / 15))
curve_cuts = bpy.context.scene.bsurfaces.SURFSK_precision * precision_multiplier
# Subdivide the curves
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=curve_cuts)
# The verts position shifting that happens with splines subdivision.
# For later reorder splines points
verts_position_shift = curve_cuts + 1
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Reorder coordinates of the points of each spline to put the first point of
# the spline starting at the position it was the first point before sudividing
# the curve. And make a new curve object per spline (to handle memory better later)
splines_U_objects = []
for i in range(len(ob_curves_surf.data.splines)):
spline_U_curve = bpy.data.curves.new('SURFSKIO_spline_U_' + str(i), 'CURVE')
ob_spline_U = bpy.data.objects.new('SURFSKIO_spline_U_' + str(i), spline_U_curve)
bpy.context.collection.objects.link(ob_spline_U)
spline_U_curve.dimensions = "3D"
# Add points to the spline in the new curve object
ob_spline_U.data.splines.new('BEZIER')
for t in range(len(ob_curves_surf.data.splines[i].bezier_points)):
if cyclic_loops_U[i] is True and not self.selection_U_exists: # If the loop is cyclic
if t + verts_position_shift <= len(ob_curves_surf.data.splines[i].bezier_points) - 1:
point_index = t + verts_position_shift
else:
point_index = t + verts_position_shift - len(ob_curves_surf.data.splines[i].bezier_points)
else:
point_index = t
# to avoid adding the first point since it's added when the spline is created
if t > 0:
ob_spline_U.data.splines[0].bezier_points.add(1)
ob_spline_U.data.splines[0].bezier_points[t].co = \
ob_curves_surf.data.splines[i].bezier_points[point_index].co
if cyclic_loops_U[i] is True and not self.selection_U_exists: # If the loop is cyclic
# Add a last point at the same location as the first one
ob_spline_U.data.splines[0].bezier_points.add(1)
ob_spline_U.data.splines[0].bezier_points[len(ob_spline_U.data.splines[0].bezier_points) - 1].co = \
ob_spline_U.data.splines[0].bezier_points[0].co
else:
ob_spline_U.data.splines[0].use_cyclic_u = False
splines_U_objects.append(ob_spline_U)
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_spline_U.select_set(True)
bpy.context.view_layer.objects.active = ob_spline_U
# When option "Loops on strokes" is active each "Cross" loop will have
# its own proportions according to where the original strokes "touch" them
if self.loops_on_strokes:
# Get the indices of points where the original strokes "touch" loops-U
points_U_crossed_by_strokes = []
for i in range(len(splines_U_objects[0].data.splines[0].bezier_points)):
bp = splines_U_objects[0].data.splines[0].bezier_points[i]
if ["%.4f" % bp.co[0], "%.4f" % bp.co[1], "%.4f" % bp.co[2]] in coords_loops_U_control_points:
points_U_crossed_by_strokes.append(i)
# Make a dictionary with the number of the edge, in the selected chain V, corresponding to each stroke
edge_order_number_for_splines = {}
if self.selection_V_exists:
# For two-connected selections add a first hypothetic stroke at the beginning.
if selection_type == "TWO_CONNECTED":
edge_order_number_for_splines[0] = 0
for i in range(len(self.main_splines.data.splines)):
sp = self.main_splines.data.splines[i]
v_idx, dist_temp = self.shortest_distance(
self.main_object,
sp.bezier_points[0].co,
verts_ordered_V_indices
)
# Get the position (edges count) of the vert v_idx in the selected chain V
edge_idx_in_chain = verts_ordered_V_indices.index(v_idx)
# For two-connected selections the strokes go after the
# hypothetic stroke added before, so the index adds one per spline
if selection_type == "TWO_CONNECTED":
spline_number = i + 1
else:
spline_number = i
edge_order_number_for_splines[spline_number] = edge_idx_in_chain
# Get the first and last verts indices for later comparison
if i == 0:
first_v_idx = v_idx
elif i == len(self.main_splines.data.splines) - 1:
last_v_idx = v_idx
if self.selection_V_is_closed:
# If there is no last stroke on the last vertex (same as first vertex),
# add a hypothetic spline at last vert order
if first_v_idx != last_v_idx:
edge_order_number_for_splines[(len(self.main_splines.data.splines) - 1) + 1] = \
len(verts_ordered_V_indices) - 1
else:
if self.cyclic_cross:
edge_order_number_for_splines[len(self.main_splines.data.splines) - 1] = \
len(verts_ordered_V_indices) - 2
edge_order_number_for_splines[(len(self.main_splines.data.splines) - 1) + 1] = \
len(verts_ordered_V_indices) - 1
else:
edge_order_number_for_splines[len(self.main_splines.data.splines) - 1] = \
len(verts_ordered_V_indices) - 1
# Get the coords of the points distributed along the
# "crossing curves", with appropriate proportions-V
surface_splines_parsed = []
for i in range(len(splines_U_objects)):
sp_ob = splines_U_objects[i]
# If "Loops on strokes" option is active, calculate the proportions for each loop-U
if self.loops_on_strokes:
# Segments distances from stroke to stroke
dist = 0
full_dist = 0
segments_distances = []
for t in range(len(sp_ob.data.splines[0].bezier_points)):
bp = sp_ob.data.splines[0].bezier_points[t]
if t == 0:
last_p = bp.co
else:
actual_p = bp.co
dist += (last_p - actual_p).length
if t in points_U_crossed_by_strokes:
segments_distances.append(dist)
full_dist += dist
dist = 0
last_p = actual_p
# Calculate Proportions.
used_edges_proportions_V = []
for t in range(len(segments_distances)):
if self.selection_V_exists:
if t == 0:
order_number_last_stroke = 0
segment_edges_length_V = 0
segment_edges_length_V2 = 0
for order in range(order_number_last_stroke, edge_order_number_for_splines[t + 1]):
segment_edges_length_V += edges_lengths_V[order]
if self.selection_V2_exists:
segment_edges_length_V2 += edges_lengths_V2[order]
for order in range(order_number_last_stroke, edge_order_number_for_splines[t + 1]):
# Calculate each "sub-segment" (the ones between each stroke) length
if self.selection_V2_exists:
proportion_sub_seg = (edges_lengths_V2[order] -
((edges_lengths_V2[order] - edges_lengths_V[order]) /
len(splines_U_objects) * i)) / (segment_edges_length_V2 -
(segment_edges_length_V2 - segment_edges_length_V) /
len(splines_U_objects) * i)
sub_seg_dist = segments_distances[t] * proportion_sub_seg
else:
proportion_sub_seg = edges_lengths_V[order] / segment_edges_length_V
sub_seg_dist = segments_distances[t] * proportion_sub_seg
used_edges_proportions_V.append(sub_seg_dist / full_dist)
order_number_last_stroke = edge_order_number_for_splines[t + 1]
else:
for c in range(self.edges_V):
# Calculate each "sub-segment" (the ones between each stroke) length
sub_seg_dist = segments_distances[t] / self.edges_V
used_edges_proportions_V.append(sub_seg_dist / full_dist)
actual_spline = self.distribute_pts(sp_ob.data.splines, used_edges_proportions_V)
surface_splines_parsed.append(actual_spline[0])
else:
if self.selection_V2_exists:
used_edges_proportions_V = []
for p in range(len(edges_proportions_V)):
used_edges_proportions_V.append(
edges_proportions_V2[p] -
((edges_proportions_V2[p] -
edges_proportions_V[p]) / len(splines_U_objects) * i)
)
else:
used_edges_proportions_V = edges_proportions_V
actual_spline = self.distribute_pts(sp_ob.data.splines, used_edges_proportions_V)
surface_splines_parsed.append(actual_spline[0])
# Set the verts of the first and last splines to the locations
# of the respective verts in the selections
if self.selection_V_exists:
for i in range(0, len(surface_splines_parsed[0])):
surface_splines_parsed[len(surface_splines_parsed) - 1][i] = \
self.main_object.matrix_world @ verts_ordered_V[i].co
if selection_type == "TWO_NOT_CONNECTED":
if self.selection_V2_exists:
for i in range(0, len(surface_splines_parsed[0])):
surface_splines_parsed[0][i] = self.main_object.matrix_world @ verts_ordered_V2[i].co
# When "Automatic join" option is active (and the selection type != "TWO_CONNECTED"),
# merge the verts of the tips of the loops when they are "near enough"
if self.automatic_join and selection_type != "TWO_CONNECTED":
# Join the tips of "Follow" loops that are near enough and must be "closed"
if not self.selection_V_exists and len(edges_proportions_U) >= 3:
for i in range(len(surface_splines_parsed[0])):
sp = surface_splines_parsed
loop_segment_dist = (sp[0][i] - sp[1][i]).length
full_loop_dist = loop_segment_dist * self.edges_U
verts_middle_position_co = [
(sp[0][i][0] + sp[len(sp) - 1][i][0]) / 2,
(sp[0][i][1] + sp[len(sp) - 1][i][1]) / 2,
(sp[0][i][2] + sp[len(sp) - 1][i][2]) / 2
]
points_original = []
points_original.append(sp[1][i])
points_original.append(sp[0][i])
points_target = []
points_target.append(sp[1][i])
points_target.append(Vector(verts_middle_position_co))
vec_A = points_original[0] - points_original[1]
vec_B = points_target[0] - points_target[1]
# check for zero angles, not sure if it is a great fix
if vec_A.length != 0 and vec_B.length != 0:
angle = vec_A.angle(vec_B) / pi
edge_new_length = (Vector(verts_middle_position_co) - sp[1][i]).length
else:
angle = 0
edge_new_length = 0
# If after moving the verts to the middle point, the segment doesn't stretch too much
if edge_new_length <= loop_segment_dist * 1.5 * \
self.join_stretch_factor and angle < 0.25 * self.join_stretch_factor:
# Avoid joining when the actual loop must be merged with the original mesh
if not (self.selection_U_exists and i == 0) and \
not (self.selection_U2_exists and i == len(surface_splines_parsed[0]) - 1):
# Change the coords of both verts to the middle position
surface_splines_parsed[0][i] = verts_middle_position_co
surface_splines_parsed[len(surface_splines_parsed) - 1][i] = verts_middle_position_co
# Delete object with control points and object from grease pencil conversion
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_ctrl_pts.select_set(True)
bpy.context.view_layer.objects.active = ob_ctrl_pts
bpy.ops.object.delete()
for sp_ob in splines_U_objects:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
sp_ob.select_set(True)
bpy.context.view_layer.objects.active = sp_ob
bpy.ops.object.delete()
# Generate surface
# Get all verts coords
all_surface_verts_co = []
for i in range(0, len(surface_splines_parsed)):
# Get coords of all verts and make a list with them
for pt_co in surface_splines_parsed[i]:
all_surface_verts_co.append(pt_co)
# Define verts for each face
all_surface_faces = []
for i in range(0, len(all_surface_verts_co) - len(surface_splines_parsed[0])):
if ((i + 1) / len(surface_splines_parsed[0]) != int((i + 1) / len(surface_splines_parsed[0]))):
all_surface_faces.append(
[i + 1, i, i + len(surface_splines_parsed[0]),
i + len(surface_splines_parsed[0]) + 1]
)
# Build the mesh
surf_me_name = "SURFSKIO_surface"
me_surf = bpy.data.meshes.new(surf_me_name)
me_surf.from_pydata(all_surface_verts_co, [], all_surface_faces)
me_surf.update()
ob_surface = bpy.data.objects.new(surf_me_name, me_surf)
bpy.context.collection.objects.link(ob_surface)
# Select all the "unselected but participating" verts, from closed selection
# or double selections with middle-vertex, for later join with remove doubles
for v_idx in single_unselected_verts:
self.main_object.data.vertices[v_idx].select_set(True)
# Join the new mesh to the main object
ob_surface.select_set(True)
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.join('INVOKE_REGION_WIN')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.mesh.remove_doubles('INVOKE_REGION_WIN', threshold=0.0001)
bpy.ops.mesh.normals_make_consistent('INVOKE_REGION_WIN', inside=False)
bpy.ops.mesh.select_all('INVOKE_REGION_WIN', action='DESELECT')
return{'FINISHED'}
def execute(self, context):
self.main_object = bpy.context.view_layer.objects.active
bpy.context.preferences.edit.use_global_undo = False
if not self.is_fill_faces:
bpy.ops.wm.context_set_value(data_path='tool_settings.mesh_select_mode',
value='True, False, False')
# Build splines from the "last saved splines".
last_saved_curve = bpy.data.curves.new('SURFSKIO_last_crv', 'CURVE')
self.main_splines = bpy.data.objects.new('SURFSKIO_last_crv', last_saved_curve)
bpy.context.collection.objects.link(self.main_splines)
last_saved_curve.dimensions = "3D"
for sp in self.last_strokes_splines_coords:
spline = self.main_splines.data.splines.new('BEZIER')
# less one because one point is added when the spline is created
spline.bezier_points.add(len(sp) - 1)
for p in range(0, len(sp)):
spline.bezier_points[p].co = [sp[p][0], sp[p][1], sp[p][2]]
#bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_splines.select_set(True)
bpy.context.view_layer.objects.active = self.main_splines
#bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='SELECT')
# Important to make it vector first and then automatic, otherwise the
# tips handles get too big and distort the shrinkwrap results later
bpy.ops.curve.handle_type_set(type='VECTOR')
bpy.ops.curve.handle_type_set('INVOKE_REGION_WIN', type='AUTOMATIC')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.main_splines.name = "SURFSKIO_temp_strokes"
if self.is_crosshatch:
strokes_for_crosshatch = True
strokes_for_rectangular_surface = False
else:
strokes_for_rectangular_surface = True
strokes_for_crosshatch = False
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
if strokes_for_rectangular_surface:
self.rectangular_surface()
elif strokes_for_crosshatch:
self.crosshatch_surface_execute()
# Delete main splines
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_splines.select_set(True)
bpy.context.view_layer.objects.active = self.main_splines
bpy.ops.object.delete()
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.context.preferences.edit.use_global_undo = self.initial_global_undo_state
return{'FINISHED'}
def invoke(self, context, event):
self.initial_global_undo_state = bpy.context.preferences.edit.use_global_undo
self.main_object = bpy.context.view_layer.objects.active
self.main_object_selected_verts_count = int(self.main_object.data.total_vert_sel)
bpy.context.preferences.edit.use_global_undo = False
bpy.ops.wm.context_set_value(data_path='tool_settings.mesh_select_mode',
value='True, False, False')
# Out Edit mode and In again to make sure the actual mesh selections are being taken
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bsurfaces_props = bpy.context.scene.bsurfaces
self.cyclic_cross = bsurfaces_props.SURFSK_cyclic_cross
self.cyclic_follow = bsurfaces_props.SURFSK_cyclic_follow
self.automatic_join = bsurfaces_props.SURFSK_automatic_join
self.loops_on_strokes = bsurfaces_props.SURFSK_loops_on_strokes
self.keep_strokes = bsurfaces_props.SURFSK_keep_strokes
self.edges_U = 5
if self.loops_on_strokes:
self.edges_V = 1
else:
self.edges_V = 5
self.is_fill_faces = False
self.stopping_errors = False
self.last_strokes_splines_coords = []
# Determine the type of the strokes
self.strokes_type = get_strokes_type(self.main_object)
# Check if it will be used grease pencil strokes or curves
# If there are strokes to be used
if self.strokes_type == "GP_STROKES" or self.strokes_type == "EXTERNAL_CURVE":
if self.strokes_type == "GP_STROKES":
# Convert grease pencil strokes to curve
gp = bpy.context.scene.objects['GPencil']
#bpy.ops.gpencil.convert(type='CURVE', use_link_strokes=False)
self.original_curve = conver_gpencil_to_curve(context, gp)
# XXX gpencil.convert now keep org object as active/selected, *not* newly created curve!
# XXX This is far from perfect, but should work in most cases...
# self.original_curve = bpy.context.object
gplayer_prefix_translated = bpy.app.translations.pgettext_data('GP_Layer')
for ob in bpy.context.selected_objects:
if ob != bpy.context.view_layer.objects.active and \
ob.name.startswith((gplayer_prefix_translated, 'GP_Layer')):
self.original_curve = ob
self.using_external_curves = False
elif self.strokes_type == "EXTERNAL_CURVE":
for ob in bpy.context.selected_objects:
if ob != bpy.context.view_layer.objects.active:
self.original_curve = ob
self.using_external_curves = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Make sure there are no objects left from erroneous
# executions of this operator, with the reserved names used here
for o in bpy.data.objects:
if o.name.find("SURFSKIO_") != -1:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
o.select_set(True)
bpy.context.view_layer.objects.active = o
bpy.ops.object.delete()
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.original_curve.select_set(True)
bpy.context.view_layer.objects.active = self.original_curve
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
self.temporary_curve = bpy.context.view_layer.objects.active
# Deselect all points of the curve
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Delete splines with only a single isolated point
for i in range(len(self.temporary_curve.data.splines)):
sp = self.temporary_curve.data.splines[i]
if len(sp.bezier_points) == 1:
sp.bezier_points[0].select_control_point = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.delete(type='VERT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.temporary_curve.select_set(True)
bpy.context.view_layer.objects.active = self.temporary_curve
# Set a minimum number of points for crosshatch
minimum_points_num = 15
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Check if the number of points of each curve has at least the number of points
# of minimum_points_num, which is a bit more than the face-loops limit.
# If not, subdivide to reach at least that number of points
for i in range(len(self.temporary_curve.data.splines)):
sp = self.temporary_curve.data.splines[i]
if len(sp.bezier_points) < minimum_points_num:
for bp in sp.bezier_points:
bp.select_control_point = True
if (len(sp.bezier_points) - 1) != 0:
# Formula to get the number of cuts that will make a curve
# of N number of points have near to "minimum_points_num"
# points, when subdividing with this number of cuts
subdivide_cuts = int(
(minimum_points_num - len(sp.bezier_points)) /
(len(sp.bezier_points) - 1)
) + 1
else:
subdivide_cuts = 0
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=subdivide_cuts)
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Detect if the strokes are a crosshatch and do it if it is
self.crosshatch_surface_invoke(self.temporary_curve)
if not self.is_crosshatch:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.temporary_curve.select_set(True)
bpy.context.view_layer.objects.active = self.temporary_curve
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Set a minimum number of points for rectangular surfaces
minimum_points_num = 60
# Check if the number of points of each curve has at least the number of points
# of minimum_points_num, which is a bit more than the face-loops limit.
# If not, subdivide to reach at least that number of points
for i in range(len(self.temporary_curve.data.splines)):
sp = self.temporary_curve.data.splines[i]
if len(sp.bezier_points) < minimum_points_num:
for bp in sp.bezier_points:
bp.select_control_point = True
if (len(sp.bezier_points) - 1) != 0:
# Formula to get the number of cuts that will make a curve of
# N number of points have near to "minimum_points_num" points,
# when subdividing with this number of cuts
subdivide_cuts = int(
(minimum_points_num - len(sp.bezier_points)) /
(len(sp.bezier_points) - 1)
) + 1
else:
subdivide_cuts = 0
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=subdivide_cuts)
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Save coordinates of the actual strokes (as the "last saved splines")
for sp_idx in range(len(self.temporary_curve.data.splines)):
self.last_strokes_splines_coords.append([])
for bp_idx in range(len(self.temporary_curve.data.splines[sp_idx].bezier_points)):
coords = self.temporary_curve.matrix_world @ \
self.temporary_curve.data.splines[sp_idx].bezier_points[bp_idx].co
self.last_strokes_splines_coords[sp_idx].append([coords[0], coords[1], coords[2]])
# Check for cyclic splines, put the first and last points in the middle of their actual positions
for sp_idx in range(len(self.temporary_curve.data.splines)):
if self.temporary_curve.data.splines[sp_idx].use_cyclic_u is True:
first_p_co = self.last_strokes_splines_coords[sp_idx][0]
last_p_co = self.last_strokes_splines_coords[sp_idx][
len(self.last_strokes_splines_coords[sp_idx]) - 1
]
target_co = [
(first_p_co[0] + last_p_co[0]) / 2,
(first_p_co[1] + last_p_co[1]) / 2,
(first_p_co[2] + last_p_co[2]) / 2
]
self.last_strokes_splines_coords[sp_idx][0] = target_co
self.last_strokes_splines_coords[sp_idx][
len(self.last_strokes_splines_coords[sp_idx]) - 1
] = target_co
tuple(self.last_strokes_splines_coords)
# Estimation of the average length of the segments between
# each point of the grease pencil strokes.
# Will be useful to determine whether a curve should be made "Cyclic"
segments_lengths_sum = 0
segments_count = 0
random_spline = self.temporary_curve.data.splines[0].bezier_points
for i in range(0, len(random_spline)):
if i != 0 and len(random_spline) - 1 >= i:
segments_lengths_sum += (random_spline[i - 1].co - random_spline[i].co).length
segments_count += 1
self.average_gp_segment_length = segments_lengths_sum / segments_count
# Delete temporary strokes curve object
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.temporary_curve.select_set(True)
bpy.context.view_layer.objects.active = self.temporary_curve
bpy.ops.object.delete()
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.execute(context)
# Set again since "execute()" will turn it again to its initial value
bpy.context.preferences.edit.use_global_undo = False
# If "Keep strokes" option is not active, delete original strokes curve object
if (not self.stopping_errors and not self.keep_strokes) or self.is_crosshatch:
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.original_curve.select_set(True)
bpy.context.view_layer.objects.active = self.original_curve
bpy.ops.object.delete()
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_object.select_set(True)
bpy.context.view_layer.objects.active = self.main_object
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Delete grease pencil strokes
if self.strokes_type == "GP_STROKES" and not self.stopping_errors:
bpy.context.scene.objects['GPencil'].select_set(True)
bpy.context.view_layer.objects.active = bpy.context.scene.objects['GPencil']
bpy.ops.object.mode_set(mode='PAINT_GPENCIL')
bpy.ops.gpencil.active_frame_delete('INVOKE_REGION_WIN')
bpy.ops.object.mode_set(mode='OBJECT')
bpy.context.preferences.edit.use_global_undo = self.initial_global_undo_state
if not self.stopping_errors:
return {"FINISHED"}
else:
return{"CANCELLED"}
elif self.strokes_type == "SELECTION_ALONE":
self.is_fill_faces = True
created_faces_count = self.fill_with_faces(self.main_object)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.context.preferences.edit.use_global_undo = self.initial_global_undo_state
if created_faces_count == 0:
self.report({'WARNING'}, "There aren't any strokes attached to the object")
return {"CANCELLED"}
else:
return {"FINISHED"}
bpy.context.preferences.edit.use_global_undo = self.initial_global_undo_state
if self.strokes_type == "EXTERNAL_NO_CURVE":
self.report({'WARNING'}, "The secondary object is not a Curve.")
return{"CANCELLED"}
elif self.strokes_type == "MORE_THAN_ONE_EXTERNAL":
self.report({'WARNING'}, "There shouldn't be more than one secondary object selected.")
return{"CANCELLED"}
elif self.strokes_type == "SINGLE_GP_STROKE_NO_SELECTION" or \
self.strokes_type == "SINGLE_CURVE_STROKE_NO_SELECTION":
self.report({'WARNING'}, "It's needed at least one stroke and one selection, or two strokes.")
return{"CANCELLED"}
elif self.strokes_type == "NO_STROKES":
self.report({'WARNING'}, "There aren't any strokes attached to the object")
return{"CANCELLED"}
elif self.strokes_type == "CURVE_WITH_NON_BEZIER_SPLINES":
self.report({'WARNING'}, "All splines must be Bezier.")
return{"CANCELLED"}
else:
return{"CANCELLED"}
# Edit strokes operator
class GPENCIL_OT_SURFSK_add_strokes(Operator):
bl_idname = "gpencil.surfsk_add_strokes"
bl_label = "Bsurfaces add strokes"
bl_description = "Add the grease pencil strokes"
def execute(self, context):
# Determine the type of the strokes
self.strokes_type = get_strokes_type(self.main_object)
# Check if strokes are grease pencil strokes or a curves object
selected_objs = bpy.context.selected_objects
if self.strokes_type == "EXTERNAL_CURVE" or self.strokes_type == "SINGLE_CURVE_STROKE_NO_SELECTION":
for ob in selected_objs:
if ob != bpy.context.view_layer.objects.active:
curve_ob = ob
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
curve_ob.select_set(True)
bpy.context.view_layer.objects.active = curve_ob
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
else:
bpy.context.scene.objects['GPencil'].select_set(True)
bpy.context.view_layer.objects.active = bpy.context.scene.objects['GPencil']
bpy.ops.object.mode_set(mode='PAINT_GPENCIL')
return{"FINISHED"}
def invoke(self, context, event):
self.main_object = bpy.context.object
self.execute(context)
return {"FINISHED"}
# Edit strokes operator
class GPENCIL_OT_SURFSK_edit_strokes(Operator):
bl_idname = "gpencil.surfsk_edit_strokes"
bl_label = "Bsurfaces edit strokes"
bl_description = "Edit the grease pencil strokes or curves used"
def execute(self, context):
# Determine the type of the strokes
self.strokes_type = get_strokes_type(self.main_object)
# Check if strokes are grease pencil strokes or a curves object
selected_objs = bpy.context.selected_objects
if self.strokes_type == "EXTERNAL_CURVE" or self.strokes_type == "SINGLE_CURVE_STROKE_NO_SELECTION":
for ob in selected_objs:
if ob != bpy.context.view_layer.objects.active:
curve_ob = ob
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
curve_ob.select_set(True)
bpy.context.view_layer.objects.active = curve_ob
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
elif self.strokes_type == "GP_STROKES" or self.strokes_type == "SINGLE_GP_STROKE_NO_SELECTION":
# Convert grease pencil strokes to curve
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
#bpy.ops.gpencil.convert('INVOKE_REGION_WIN', type='CURVE', use_link_strokes=False)
gp = bpy.context.scene.objects['GPencil']
conver_gpencil_to_curve(context, gp)
for ob in bpy.context.selected_objects:
if ob != bpy.context.view_layer.objects.active and ob.name.startswith("GP_Layer"):
ob_gp_strokes = ob
ob_gp_strokes = bpy.context.object
# Delete grease pencil strokes
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.context.scene.objects['GPencil'].select_set(True)
bpy.context.view_layer.objects.active = bpy.context.scene.objects['GPencil']
bpy.ops.object.mode_set(mode='PAINT_GPENCIL')
bpy.ops.gpencil.active_frame_delete('INVOKE_REGION_WIN')
bpy.ops.object.mode_set(mode='OBJECT')
# Clean up curves
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
ob_gp_strokes.select_set(True)
bpy.context.view_layer.objects.active = ob_gp_strokes
curve_crv = ob_gp_strokes.data
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.spline_type_set('INVOKE_REGION_WIN', type="BEZIER")
bpy.ops.curve.handle_type_set('INVOKE_REGION_WIN', type="AUTOMATIC")
#curve_crv.show_handles = False
#curve_crv.show_normal_face = False
elif self.strokes_type == "EXTERNAL_NO_CURVE":
self.report({'WARNING'}, "The secondary object is not a Curve.")
return{"CANCELLED"}
elif self.strokes_type == "MORE_THAN_ONE_EXTERNAL":
self.report({'WARNING'}, "There shouldn't be more than one secondary object selected.")
return{"CANCELLED"}
elif self.strokes_type == "NO_STROKES" or self.strokes_type == "SELECTION_ALONE":
self.report({'WARNING'}, "There aren't any strokes attached to the object")
return{"CANCELLED"}
else:
return{"CANCELLED"}
def invoke(self, context, event):
self.main_object = bpy.context.object
self.execute(context)
return {"FINISHED"}
class CURVE_OT_SURFSK_reorder_splines(Operator):
bl_idname = "curve.surfsk_reorder_splines"
bl_label = "Bsurfaces reorder splines"
bl_description = "Defines the order of the splines by using grease pencil strokes"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
objects_to_delete = []
# Convert grease pencil strokes to curve.
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.gpencil.convert('INVOKE_REGION_WIN', type='CURVE', use_link_strokes=False)
for ob in bpy.context.selected_objects:
if ob != bpy.context.view_layer.objects.active and ob.name.startswith("GP_Layer"):
GP_strokes_curve = ob
# GP_strokes_curve = bpy.context.object
objects_to_delete.append(GP_strokes_curve)
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
GP_strokes_curve.select_set(True)
bpy.context.view_layer.objects.active = GP_strokes_curve
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='SELECT')
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=100)
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
GP_strokes_mesh = bpy.context.object
objects_to_delete.append(GP_strokes_mesh)
GP_strokes_mesh.data.resolution_u = 1
bpy.ops.object.convert(target='MESH', keep_original=False)
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_curve.select_set(True)
bpy.context.view_layer.objects.active = self.main_curve
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
curves_duplicate_1 = bpy.context.object
objects_to_delete.append(curves_duplicate_1)
minimum_points_num = 500
# Some iterations since the subdivision operator
# has a limit of 100 subdivisions per iteration
for x in range(round(minimum_points_num / 100)):
# Check if the number of points of each curve has at least the number of points
# of minimum_points_num. If not, subdivide to reach at least that number of points
for i in range(len(curves_duplicate_1.data.splines)):
sp = curves_duplicate_1.data.splines[i]
if len(sp.bezier_points) < minimum_points_num:
for bp in sp.bezier_points:
bp.select_control_point = True
if (len(sp.bezier_points) - 1) != 0:
# Formula to get the number of cuts that will make a curve of N
# number of points have near to "minimum_points_num" points,
# when subdividing with this number of cuts
subdivide_cuts = int(
(minimum_points_num - len(sp.bezier_points)) /
(len(sp.bezier_points) - 1)
) + 1
else:
subdivide_cuts = 0
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.subdivide('INVOKE_REGION_WIN', number_cuts=subdivide_cuts)
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.object.duplicate('INVOKE_REGION_WIN')
curves_duplicate_2 = bpy.context.object
objects_to_delete.append(curves_duplicate_2)
# Duplicate the duplicate and add Shrinkwrap to it, with the grease pencil strokes curve as target
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
curves_duplicate_2.select_set(True)
bpy.context.view_layer.objects.active = curves_duplicate_2
bpy.ops.object.modifier_add('INVOKE_REGION_WIN', type='SHRINKWRAP')
curves_duplicate_2.modifiers["Shrinkwrap"].wrap_method = "NEAREST_VERTEX"
curves_duplicate_2.modifiers["Shrinkwrap"].target = GP_strokes_mesh
bpy.ops.object.modifier_apply('INVOKE_REGION_WIN', apply_as='DATA', modifier='Shrinkwrap')
# Get the distance of each vert from its original position to its position with Shrinkwrap
nearest_points_coords = {}
for st_idx in range(len(curves_duplicate_1.data.splines)):
for bp_idx in range(len(curves_duplicate_1.data.splines[st_idx].bezier_points)):
bp_1_co = curves_duplicate_1.matrix_world @ \
curves_duplicate_1.data.splines[st_idx].bezier_points[bp_idx].co
bp_2_co = curves_duplicate_2.matrix_world @ \
curves_duplicate_2.data.splines[st_idx].bezier_points[bp_idx].co
if bp_idx == 0:
shortest_dist = (bp_1_co - bp_2_co).length
nearest_points_coords[st_idx] = ("%.4f" % bp_2_co[0],
"%.4f" % bp_2_co[1],
"%.4f" % bp_2_co[2])
dist = (bp_1_co - bp_2_co).length
if dist < shortest_dist:
nearest_points_coords[st_idx] = ("%.4f" % bp_2_co[0],
"%.4f" % bp_2_co[1],
"%.4f" % bp_2_co[2])
shortest_dist = dist
# Get all coords of GP strokes points, for comparison
GP_strokes_coords = []
for st_idx in range(len(GP_strokes_curve.data.splines)):
GP_strokes_coords.append(
[("%.4f" % x if "%.4f" % x != "-0.00" else "0.00",
"%.4f" % y if "%.4f" % y != "-0.00" else "0.00",
"%.4f" % z if "%.4f" % z != "-0.00" else "0.00") for
x, y, z in [bp.co for bp in GP_strokes_curve.data.splines[st_idx].bezier_points]]
)
# Check the point of the GP strokes with the same coords as
# the nearest points of the curves (with shrinkwrap)
# Dictionary with GP stroke index as index, and a list as value.
# The list has as index the point index of the GP stroke
# nearest to the spline, and as value the spline index
GP_connection_points = {}
for gp_st_idx in range(len(GP_strokes_coords)):
GPvert_spline_relationship = {}
for splines_st_idx in range(len(nearest_points_coords)):
if nearest_points_coords[splines_st_idx] in GP_strokes_coords[gp_st_idx]:
GPvert_spline_relationship[
GP_strokes_coords[gp_st_idx].index(nearest_points_coords[splines_st_idx])
] = splines_st_idx
GP_connection_points[gp_st_idx] = GPvert_spline_relationship
# Get the splines new order
splines_new_order = []
for i in GP_connection_points:
dict_keys = sorted(GP_connection_points[i].keys()) # Sort dictionaries by key
for k in dict_keys:
splines_new_order.append(GP_connection_points[i][k])
# Reorder
curve_original_name = self.main_curve.name
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
self.main_curve.select_set(True)
bpy.context.view_layer.objects.active = self.main_curve
self.main_curve.name = "SURFSKIO_CRV_ORD"
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
for sp_idx in range(len(self.main_curve.data.splines)):
self.main_curve.data.splines[0].bezier_points[0].select_control_point = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.separate('EXEC_REGION_WIN')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
# Get the names of the separated splines objects in the original order
splines_unordered = {}
for o in bpy.data.objects:
if o.name.find("SURFSKIO_CRV_ORD") != -1:
spline_order_string = o.name.partition(".")[2]
if spline_order_string != "" and int(spline_order_string) > 0:
spline_order_index = int(spline_order_string) - 1
splines_unordered[spline_order_index] = o.name
# Join all splines objects in final order
for order_idx in splines_new_order:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.data.objects[splines_unordered[order_idx]].select_set(True)
bpy.data.objects["SURFSKIO_CRV_ORD"].select_set(True)
bpy.context.view_layer.objects.active = bpy.data.objects["SURFSKIO_CRV_ORD"]
bpy.ops.object.join('INVOKE_REGION_WIN')
# Go back to the original name of the curves object.
bpy.context.object.name = curve_original_name
# Delete all unused objects
for o in objects_to_delete:
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
o.select_set(True)
bpy.context.view_layer.objects.active = o
bpy.ops.object.delete()
bpy.ops.object.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.data.objects[curve_original_name].select_set(True)
bpy.context.view_layer.objects.active = bpy.data.objects[curve_original_name]
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.context.scene.objects['GPencil'].select_set(True)
bpy.context.view_layer.objects.active = bpy.context.scene.objects['GPencil']
bpy.ops.object.mode_set(mode='PAINT_GPENCIL')
bpy.ops.gpencil.active_frame_delete('INVOKE_REGION_WIN')
bpy.ops.object.mode_set(mode='OBJECT')
return {"FINISHED"}
def invoke(self, context, event):
self.main_curve = bpy.context.object
there_are_GP_strokes = False
try:
# Get the active grease pencil layer
strokes_num = len(self.main_curve.grease_pencil.layers.active.active_frame.strokes)
if strokes_num > 0:
there_are_GP_strokes = True
except:
pass
if there_are_GP_strokes:
self.execute(context)
self.report({'INFO'}, "Splines have been reordered")
else:
self.report({'WARNING'}, "Draw grease pencil strokes to connect splines")
return {"FINISHED"}
class CURVE_OT_SURFSK_first_points(Operator):
bl_idname = "curve.surfsk_first_points"
bl_label = "Bsurfaces set first points"
bl_description = "Set the selected points as the first point of each spline"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
splines_to_invert = []
# Check non-cyclic splines to invert
for i in range(len(self.main_curve.data.splines)):
b_points = self.main_curve.data.splines[i].bezier_points
if i not in self.cyclic_splines: # Only for non-cyclic splines
if b_points[len(b_points) - 1].select_control_point:
splines_to_invert.append(i)
# Reorder points of cyclic splines, and set all handles to "Automatic"
# Check first selected point
cyclic_splines_new_first_pt = {}
for i in self.cyclic_splines:
sp = self.main_curve.data.splines[i]
for t in range(len(sp.bezier_points)):
bp = sp.bezier_points[t]
if bp.select_control_point or bp.select_right_handle or bp.select_left_handle:
cyclic_splines_new_first_pt[i] = t
break # To take only one if there are more
# Reorder
for spline_idx in cyclic_splines_new_first_pt:
sp = self.main_curve.data.splines[spline_idx]
spline_old_coords = []
for bp_old in sp.bezier_points:
coords = (bp_old.co[0], bp_old.co[1], bp_old.co[2])
left_handle_type = str(bp_old.handle_left_type)
left_handle_length = float(bp_old.handle_left.length)
left_handle_xyz = (
float(bp_old.handle_left.x),
float(bp_old.handle_left.y),
float(bp_old.handle_left.z)
)
right_handle_type = str(bp_old.handle_right_type)
right_handle_length = float(bp_old.handle_right.length)
right_handle_xyz = (
float(bp_old.handle_right.x),
float(bp_old.handle_right.y),
float(bp_old.handle_right.z)
)
spline_old_coords.append(
[coords, left_handle_type,
right_handle_type, left_handle_length,
right_handle_length, left_handle_xyz,
right_handle_xyz]
)
for t in range(len(sp.bezier_points)):
bp = sp.bezier_points
if t + cyclic_splines_new_first_pt[spline_idx] + 1 <= len(bp) - 1:
new_index = t + cyclic_splines_new_first_pt[spline_idx] + 1
else:
new_index = t + cyclic_splines_new_first_pt[spline_idx] + 1 - len(bp)
bp[t].co = Vector(spline_old_coords[new_index][0])
bp[t].handle_left.length = spline_old_coords[new_index][3]
bp[t].handle_right.length = spline_old_coords[new_index][4]
bp[t].handle_left_type = "FREE"
bp[t].handle_right_type = "FREE"
bp[t].handle_left.x = spline_old_coords[new_index][5][0]
bp[t].handle_left.y = spline_old_coords[new_index][5][1]
bp[t].handle_left.z = spline_old_coords[new_index][5][2]
bp[t].handle_right.x = spline_old_coords[new_index][6][0]
bp[t].handle_right.y = spline_old_coords[new_index][6][1]
bp[t].handle_right.z = spline_old_coords[new_index][6][2]
bp[t].handle_left_type = spline_old_coords[new_index][1]
bp[t].handle_right_type = spline_old_coords[new_index][2]
# Invert the non-cyclic splines designated above
for i in range(len(splines_to_invert)):
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
self.main_curve.data.splines[splines_to_invert[i]].bezier_points[0].select_control_point = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
bpy.ops.curve.switch_direction()
bpy.ops.curve.select_all('INVOKE_REGION_WIN', action='DESELECT')
# Keep selected the first vert of each spline
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
for i in range(len(self.main_curve.data.splines)):
if not self.main_curve.data.splines[i].use_cyclic_u:
bp = self.main_curve.data.splines[i].bezier_points[0]
else:
bp = self.main_curve.data.splines[i].bezier_points[
len(self.main_curve.data.splines[i].bezier_points) - 1
]
bp.select_control_point = True
bp.select_right_handle = True
bp.select_left_handle = True
bpy.ops.object.editmode_toggle('INVOKE_REGION_WIN')
return {'FINISHED'}
def invoke(self, context, event):
self.main_curve = bpy.context.object
# Check if all curves are Bezier, and detect which ones are cyclic
self.cyclic_splines = []
for i in range(len(self.main_curve.data.splines)):
if self.main_curve.data.splines[i].type != "BEZIER":
self.report({'WARNING'}, "All splines must be Bezier type")
return {'CANCELLED'}
else:
if self.main_curve.data.splines[i].use_cyclic_u:
self.cyclic_splines.append(i)
self.execute(context)
self.report({'INFO'}, "First points have been set")
return {'FINISHED'}
# Add-ons Preferences Update Panel
# Define Panel classes for updating
panels = (
VIEW3D_PT_tools_SURFSK_mesh,
VIEW3D_PT_tools_SURFSK_curve,
)
def update_panel(self, context):
message = "Bsurfaces GPL Edition: Updating Panel locations has failed"
try:
for panel in panels:
if "bl_rna" in panel.__dict__:
bpy.utils.unregister_class(panel)
for panel in panels:
panel.bl_category = context.preferences.addons[__name__].preferences.category
bpy.utils.register_class(panel)
except Exception as e:
print("\n[{}]\n{}\n\nError:\n{}".format(__name__, message, e))
pass
def conver_gpencil_to_curve(context, pencil):
newCurve = bpy.data.curves.new('gpencil_curve', type='CURVE') # curvedatablock
newCurve.dimensions = '3D'
CurveObject = object_utils.object_data_add(context, newCurve) # place in active scene
for i, stroke in enumerate(pencil.data.layers[0].active_frame.strokes):
stroke_points = pencil.data.layers[0].active_frame.strokes[i].points
data_list = [ (point.co.x, point.co.y, point.co.z)
for point in stroke_points ]
points_to_add = len(data_list)-1
flat_list = []
for point in data_list:
flat_list.extend(point)
spline = newCurve.splines.new(type='BEZIER') # spline
spline.bezier_points.add(points_to_add)
spline.bezier_points.foreach_set("co", flat_list)
for point in spline.bezier_points:
point.handle_left_type="AUTO"
point.handle_right_type="AUTO"
return CurveObject
class BsurfPreferences(AddonPreferences):
# this must match the addon name, use '__package__'
# when defining this in a submodule of a python package.
bl_idname = __name__
category: StringProperty(
name="Tab Category",
description="Choose a name for the category of the panel",
default="Tools",
update=update_panel
)
def draw(self, context):
layout = self.layout
row = layout.row()
col = row.column()
col.label(text="Tab Category:")
col.prop(self, "category", text="")
# Properties
class BsurfacesProps(PropertyGroup):
SURFSK_cyclic_cross: BoolProperty(
name="Cyclic Cross",
description="Make cyclic the face-loops crossing the strokes",
default=False
)
SURFSK_cyclic_follow: BoolProperty(
name="Cyclic Follow",
description="Make cyclic the face-loops following the strokes",
default=False
)
SURFSK_keep_strokes: BoolProperty(
name="Keep strokes",
description="Keeps the sketched strokes or curves after adding the surface",
default=False
)
SURFSK_automatic_join: BoolProperty(
name="Automatic join",
description="Join automatically vertices of either surfaces "
"generated by crosshatching, or from the borders of closed shapes",
default=True
)
SURFSK_loops_on_strokes: BoolProperty(
name="Loops on strokes",
description="Make the loops match the paths of the strokes",
default=True
)
SURFSK_precision: IntProperty(
name="Precision",
description="Precision level of the surface calculation",
default=2,
min=1,
max=100
)
classes = (
VIEW3D_PT_tools_SURFSK_mesh,
VIEW3D_PT_tools_SURFSK_curve,
GPENCIL_OT_SURFSK_add_surface,
GPENCIL_OT_SURFSK_add_strokes,
GPENCIL_OT_SURFSK_edit_strokes,
CURVE_OT_SURFSK_reorder_splines,
CURVE_OT_SURFSK_first_points,
BsurfPreferences,
BsurfacesProps,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.bsurfaces = PointerProperty(type=BsurfacesProps)
update_panel(None, bpy.context)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
del bpy.types.Scene.bsurfaces
if __name__ == "__main__":
register()
|
import JSONLevelScene from './JSONLevelScene';
import Prefab from '../prefabs/Prefab';
import TextPrefab from '../prefabs/TextPrefab';
import Player from '../prefabs/world/Player';
import Map from '../prefabs/world/Map';
// import Door from '../prefabs/world/Door';
class WorldScene extends JSONLevelScene {
constructor() {
super('WorldScene');
this.prefab_classes = {
players: Player.prototype.constructor,
map: Map.prototype.constructor,
// door: Door.prototype.constructor,
};
}
create() {
super.create();
this.light = this.lights.addLight(600, 0, 1200).setIntensity(2); //setColor() 1000);
this.lights.enable().setAmbientColor(0xf3c260);
this.cameras.main.startFollow(this.players[0]);
this.cameras.main.setZoom(1.5);
// try adding tiles to this.matter.add.gameObject(tile);
// this way not quite working
// const colliderGroup = this.matter.add.gameObject(
// this.mapLayers['grass-fence(640x352)'].setCollisionByProperty({
// collides: true,
// })
// );
// this.colliderGroup.map
// this.matter.add.gameObject(cg)
// this.matterCollision.addOnCollideStart({
// objectA: this.players[0],
// objectB: this.layers['grass-fence(640x352)'],
// });
// debugger;
}
// update() {
// if (this.groups && this.groups.players)
// this.groups.players.children.entries[0].update();
// }
create_object(object) {
let position = {
x: object.x + object.width / 2,
y: object.y + object.height / 2,
};
// debugger;
if (this.prefab_classes.hasOwnProperty(object.type)) {
let prefab = new this.prefab_classes[object.type](
this,
object.name,
position,
object.properties
);
}
}
}
export default WorldScene;
|
/**
* 统计专题图封装层封装,传入数据即可显示统计专题图内容
*/
import GraphThemeLayer from './GraphThemeLayer'
export default GraphThemeLayer
|
from django.urls import path
from linuxmachinebeta.contact.views import email_list_view
app_name = "contact"
urlpatterns = [
path("", email_list_view, name="email-list"),
]
|
# -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,wcshen1994@163.com
Reference:
[1] Guo H, Tang R, Ye Y, et al. Deepfm: a factorization-machine based neural network for ctr prediction[J]. arXiv preprint arXiv:1703.04247, 2017.(https://arxiv.org/abs/1703.04247)
"""
from itertools import chain
import tensorflow as tf
from ..inputs import input_from_feature_columns, get_linear_logit, build_input_features, combined_dnn_input, DEFAULT_GROUP_NAME
from ..layers.core import PredictionLayer, DNN
from ..layers.interaction import FM
from ..layers.utils import concat_func, add_func
def DeepFM(linear_feature_columns, dnn_feature_columns, fm_group=[DEFAULT_GROUP_NAME], dnn_hidden_units=(128, 128),
l2_reg_linear=0.00001, l2_reg_embedding=0.00001, l2_reg_dnn=0, init_std=0.0001, seed=1024, dnn_dropout=0,
dnn_activation='relu', dnn_use_bn=False, task='binary'):
"""Instantiates the DeepFM Network architecture.
:param linear_feature_columns: An iterable containing all the features used by linear part of the model.
:param dnn_feature_columns: An iterable containing all the features used by deep part of the model.
:param fm_group: list, group_name of features that will be used to do feature interactions.
:param dnn_hidden_units: list,list of positive integer or empty list, the layer number and units in each layer of DNN
:param l2_reg_linear: float. L2 regularizer strength applied to linear part
:param l2_reg_embedding: float. L2 regularizer strength applied to embedding vector
:param l2_reg_dnn: float. L2 regularizer strength applied to DNN
:param init_std: float,to use as the initialize std of embedding vector
:param seed: integer ,to use as random seed.
:param dnn_dropout: float in [0,1), the probability we will drop out a given DNN coordinate.
:param dnn_activation: Activation function to use in DNN
:param dnn_use_bn: bool. Whether use BatchNormalization before activation or not in DNN
:param task: str, ``"binary"`` for binary logloss or ``"regression"`` for regression loss
:return: A Keras model instance.
"""
features = build_input_features(
linear_feature_columns + dnn_feature_columns)
inputs_list = list(features.values())
group_embedding_dict, dense_value_list = input_from_feature_columns(features, dnn_feature_columns, l2_reg_embedding,
init_std, seed, support_group=True)
linear_logit = get_linear_logit(features, linear_feature_columns, init_std=init_std, seed=seed, prefix='linear',
l2_reg=l2_reg_linear)
fm_logit = add_func([FM()(concat_func(v, axis=1))
for k, v in group_embedding_dict.items() if k in fm_group])
dnn_input = combined_dnn_input(list(chain.from_iterable(
group_embedding_dict.values())), dense_value_list)
dnn_output = DNN(dnn_hidden_units, dnn_activation, l2_reg_dnn, dnn_dropout,
dnn_use_bn, seed)(dnn_input)
dnn_logit = tf.keras.layers.Dense(
1, use_bias=False, activation=None)(dnn_output)
final_logit = add_func([linear_logit, fm_logit, dnn_logit])
output = PredictionLayer(task)(final_logit)
model = tf.keras.models.Model(inputs=inputs_list, outputs=output)
return model
|
import {authenticatedMethod, RpcMethod} from './../../../../jsonRpc';
import MnemonicWords from 'mnemonic.js';
/**
* Encrypt an account from the wallet
*/
class DeleteAccount extends RpcMethod
{
constructor(name, oWallet) {
super(name);
this._oWallet = oWallet;
}
async getHandler(args) {
let sAddress = args[0] || null;
let oAddress = this._oWallet.getAddress(sAddress);
if (oAddress === null)
{
throw new Error('Account not found.');
}
if (await this._oWallet.isAddressEncrypted(oAddress))
{
throw new Error('Account is already encrypted.');
}
const sPassword = (new MnemonicWords(4 * 32)).toWords(4 * 32).join(' ');
const bEncryptedSuccessfully = await this._oWallet.encryptAddress(oAddress, sPassword);
// Only check against "true" because the way encryptAddress() method returns the results
if (bEncryptedSuccessfully === true)
{
return sPassword;
}
else
{
throw new Error('Unable to encrypt account.');
}
}
}
export default authenticatedMethod(DeleteAccount);
|
import React from 'react'
import { Link, graphql } from 'gatsby'
import { Box } from '@chakra-ui/react'
import Seo from '../components/seo'
import kebabCase from 'lodash/kebabCase'
class TagsPage extends React.Component {
render() {
const { data } = this.props
const pageTitle = 'Tags'
const tags = data.tagsGroup.group
return (
<>
<Seo title={pageTitle} />
<Box minH="80vh">
<h3>{pageTitle}</h3>
<ul style={{ listStyle: `none` }}>
{tags.map(tag => (
<li key={tag.fieldValue}>
<Link to={`/tags/${kebabCase(tag.fieldValue)}/`}>
{tag.fieldValue} ({tag.totalCount})
</Link>
</li>
))}
</ul>
</Box>
</>
)
}
}
export default TagsPage
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
tagsGroup: allMarkdownRemark(limit: 2000) {
group(field: frontmatter___tags) {
fieldValue
totalCount
}
}
}
`
|
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import Login from '../components/login/Login';
import { signInUser } from '../redux/token/tokenOperation';
import Progress from '../components/loader/Progress';
const callFakeAPI = delay =>
new Promise(resolve => {
setTimeout(resolve, delay);
});
const initialState = {
nickname: '',
};
const LoginPage = () => {
const [isLoading, setIsLoading] = useState(true);
const [state, setstate] = useState(initialState);
const dispatch = useDispatch();
useEffect(() => {
(async () => {
await callFakeAPI(500);
setIsLoading(false);
})();
}, []);
const handleSubmit = evt => {
evt.preventDefault();
dispatch(signInUser(state));
};
const handleChange = ({ target: { name, value } }) => {
setstate(prev => ({ ...prev, [name]: value }));
};
return (
<>
<Progress isAnimating={isLoading} />
<Login
handleSubmit={handleSubmit}
handleChange={handleChange}
state={state}
/>
</>
);
};
export default LoginPage;
|
# encoding: utf-8
# ExternalIntegration, ExternalIntegrationLink, ConfigurationSetting
import inspect
import json
import logging
from abc import abstractmethod, ABCMeta
from contextlib import contextmanager
from enum import Enum
from flask_babel import lazy_gettext as _
from sqlalchemy import (
Column,
ForeignKey,
Integer,
Unicode,
UniqueConstraint,
)
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.orm.session import Session
from constants import DataSourceConstants
from hasfulltablecache import HasFullTableCache
from library import Library
from . import (
Base,
get_one,
get_one_or_create,
)
from ..config import (
CannotLoadConfiguration,
Configuration,
)
from ..mirror import MirrorUploader
from ..util.string_helpers import random_string
class ExternalIntegrationLink(Base, HasFullTableCache):
__tablename__ = 'externalintegrationslinks'
NO_MIRROR_INTEGRATION = u"NO_MIRROR"
# Possible purposes that a storage external integration can be used for.
# These string literals may be stored in the database, so changes to them
# may need to be accompanied by a DB migration.
COVERS = 'covers_mirror'
COVERS_KEY = '{0}_integration_id'.format(COVERS)
OPEN_ACCESS_BOOKS = 'books_mirror'
OPEN_ACCESS_BOOKS_KEY = '{0}_integration_id'.format(OPEN_ACCESS_BOOKS)
PROTECTED_ACCESS_BOOKS = 'protected_access_books_mirror'
PROTECTED_ACCESS_BOOKS_KEY = '{0}_integration_id'.format(PROTECTED_ACCESS_BOOKS)
MARC = "MARC_mirror"
id = Column(Integer, primary_key=True)
external_integration_id = Column(
Integer, ForeignKey('externalintegrations.id'), index=True
)
library_id = Column(
Integer, ForeignKey('libraries.id'), index=True
)
other_integration_id = Column(
Integer, ForeignKey('externalintegrations.id'), index=True
)
purpose = Column(Unicode, index=True)
mirror_settings = [
{
'key': COVERS_KEY,
'type': COVERS,
'description_type': 'cover images',
'label': 'Covers Mirror'
},
{
'key': OPEN_ACCESS_BOOKS_KEY,
'type': OPEN_ACCESS_BOOKS,
'description_type': 'free books',
'label': 'Open Access Books Mirror'
},
{
'key': PROTECTED_ACCESS_BOOKS_KEY,
'type': PROTECTED_ACCESS_BOOKS,
'description_type': 'self-hosted, commercially licensed books',
'label': 'Protected Access Books Mirror'
}
]
settings = []
for mirror_setting in mirror_settings:
mirror_type = mirror_setting['type']
mirror_description_type = mirror_setting['description_type']
mirror_label = mirror_setting['label']
settings.append({
'key': '{0}_integration_id'.format(mirror_type.lower()),
'label': _(mirror_label),
"description": _('Any {0} encountered while importing content from this collection '
'can be mirrored to a server you control.'.format(mirror_description_type)),
'type': 'select',
'options': [
{
'key': NO_MIRROR_INTEGRATION,
'label': _('None - Do not mirror {0}'.format(mirror_description_type))
}
]
})
COLLECTION_MIRROR_SETTINGS = settings
class ExternalIntegration(Base, HasFullTableCache):
"""An external integration contains configuration for connecting
to a third-party API.
"""
# Possible goals of ExternalIntegrations.
#
# These integrations are associated with external services such as
# Google Enterprise which authenticate library administrators.
ADMIN_AUTH_GOAL = u'admin_auth'
# These integrations are associated with external services such as
# SIP2 which authenticate library patrons. Other constants related
# to this are defined in the circulation manager.
PATRON_AUTH_GOAL = u'patron_auth'
# These integrations are associated with external services such
# as Overdrive which provide access to books.
LICENSE_GOAL = u'licenses'
# These integrations are associated with external services such as
# the metadata wrangler, which provide information about books,
# but not the books themselves.
METADATA_GOAL = u'metadata'
# These integrations are associated with external services such as
# S3 that provide access to book covers.
STORAGE_GOAL = MirrorUploader.STORAGE_GOAL
# These integrations are associated with external services like
# Cloudfront or other CDNs that mirror and/or cache certain domains.
CDN_GOAL = u'CDN'
# These integrations are associated with external services such as
# Elasticsearch that provide indexed search.
SEARCH_GOAL = u'search'
# These integrations are associated with external services such as
# Google Analytics, which receive analytics events.
ANALYTICS_GOAL = u'analytics'
# These integrations are associated with external services such as
# Adobe Vendor ID, which manage access to DRM-dependent content.
DRM_GOAL = u'drm'
# These integrations are associated with external services that
# help patrons find libraries.
DISCOVERY_GOAL = u'discovery'
# These integrations are associated with external services that
# collect logs of server-side events.
LOGGING_GOAL = u'logging'
# These integrations are associated with external services that
# a library uses to manage its catalog.
CATALOG_GOAL = u'ils_catalog'
# Supported protocols for ExternalIntegrations with LICENSE_GOAL.
OPDS_IMPORT = u'OPDS Import'
OPDS2_IMPORT = u'OPDS 2.0 Import'
OVERDRIVE = DataSourceConstants.OVERDRIVE
ODILO = DataSourceConstants.ODILO
BIBLIOTHECA = DataSourceConstants.BIBLIOTHECA
AXIS_360 = DataSourceConstants.AXIS_360
RB_DIGITAL = DataSourceConstants.RB_DIGITAL
ONE_CLICK = RB_DIGITAL
OPDS_FOR_DISTRIBUTORS = u'OPDS for Distributors'
ENKI = DataSourceConstants.ENKI
FEEDBOOKS = DataSourceConstants.FEEDBOOKS
LCP = DataSourceConstants.LCP
MANUAL = DataSourceConstants.MANUAL
PROQUEST = DataSourceConstants.PROQUEST
# These protocols were used on the Content Server when mirroring
# content from a given directory or directly from Project
# Gutenberg, respectively. DIRECTORY_IMPORT was replaced by
# MANUAL. GUTENBERG has yet to be replaced, but will eventually
# be moved into LICENSE_PROTOCOLS.
DIRECTORY_IMPORT = "Directory Import"
GUTENBERG = DataSourceConstants.GUTENBERG
LICENSE_PROTOCOLS = [
OPDS_IMPORT, OVERDRIVE, ODILO, BIBLIOTHECA, AXIS_360, RB_DIGITAL,
GUTENBERG, ENKI, MANUAL
]
# Some integrations with LICENSE_GOAL imply that the data and
# licenses come from a specific data source.
DATA_SOURCE_FOR_LICENSE_PROTOCOL = {
OVERDRIVE : DataSourceConstants.OVERDRIVE,
ODILO : DataSourceConstants.ODILO,
BIBLIOTHECA : DataSourceConstants.BIBLIOTHECA,
AXIS_360 : DataSourceConstants.AXIS_360,
RB_DIGITAL : DataSourceConstants.RB_DIGITAL,
ENKI : DataSourceConstants.ENKI,
FEEDBOOKS : DataSourceConstants.FEEDBOOKS,
}
# Integrations with METADATA_GOAL
BIBBLIO = u'Bibblio'
CONTENT_CAFE = u'Content Cafe'
NOVELIST = u'NoveList Select'
NYPL_SHADOWCAT = u'Shadowcat'
NYT = u'New York Times'
METADATA_WRANGLER = u'Metadata Wrangler'
CONTENT_SERVER = u'Content Server'
# Integrations with STORAGE_GOAL
S3 = u'Amazon S3'
MINIO = u'MinIO'
LCP = u'LCP'
# Integrations with CDN_GOAL
CDN = u'CDN'
# Integrations with SEARCH_GOAL
ELASTICSEARCH = u'Elasticsearch'
# Integrations with DRM_GOAL
ADOBE_VENDOR_ID = u'Adobe Vendor ID'
# Integrations with DISCOVERY_GOAL
OPDS_REGISTRATION = u'OPDS Registration'
# Integrations with ANALYTICS_GOAL
GOOGLE_ANALYTICS = u'Google Analytics'
# Integrations with ADMIN_AUTH_GOAL
GOOGLE_OAUTH = u'Google OAuth'
# List of such ADMIN_AUTH_GOAL integrations
ADMIN_AUTH_PROTOCOLS = [GOOGLE_OAUTH]
# Integrations with LOGGING_GOAL
INTERNAL_LOGGING = u'Internal logging'
LOGGLY = u"Loggly"
CLOUDWATCH = u"AWS Cloudwatch Logs"
# Integrations with CATALOG_GOAL
MARC_EXPORT = u"MARC Export"
# Keys for common configuration settings
# If there is a special URL to use for access to this API,
# put it here.
URL = u"url"
# If access requires authentication, these settings represent the
# username/password or key/secret combination necessary to
# authenticate. If there's a secret but no key, it's stored in
# 'password'.
USERNAME = u"username"
PASSWORD = u"password"
# If the request should use a custom headers, put it here.
CUSTOM_ACCEPT_HEADER = u"custom_accept_header"
# If want to use an identifier different from <id>, use this config.
PRIMARY_IDENTIFIER_SOURCE = u"primary_identifier_source"
DCTERMS_IDENTIFIER = u"first_dcterms_identifier"
_cache = HasFullTableCache.RESET
_id_cache = HasFullTableCache.RESET
__tablename__ = 'externalintegrations'
id = Column(Integer, primary_key=True)
# Each integration should have a protocol (explaining what type of
# code or network traffic we need to run to get things done) and a
# goal (explaining the real-world goal of the integration).
#
# Basically, the protocol is the 'how' and the goal is the 'why'.
protocol = Column(Unicode, nullable=False)
goal = Column(Unicode, nullable=True)
# A unique name for this ExternalIntegration. This is primarily
# used to identify ExternalIntegrations from command-line scripts.
name = Column(Unicode, nullable=True, unique=True)
# Any additional configuration information goes into
# ConfigurationSettings.
settings = relationship(
"ConfigurationSetting", backref="external_integration",
lazy="joined", cascade="all, delete-orphan",
)
# Any number of Collections may designate an ExternalIntegration
# as the source of their configuration
collections = relationship(
"Collection", backref="_external_integration",
foreign_keys='Collection.external_integration_id',
)
links = relationship(
"ExternalIntegrationLink",
backref="other_integration",
foreign_keys="ExternalIntegrationLink.other_integration_id",
cascade="all, delete-orphan"
)
def __repr__(self):
return u"<ExternalIntegration: protocol=%s goal='%s' settings=%d ID=%d>" % (
self.protocol, self.goal, len(self.settings), self.id)
def cache_key(self):
# TODO: This is not ideal, but the lookup method isn't like
# other HasFullTableCache lookup methods, so for now we use
# the unique ID as the cache key. This means that
# by_cache_key() and by_id() do the same thing.
#
# This is okay because we need by_id() quite a
# bit and by_cache_key() not as much.
return self.id
@classmethod
def for_goal(cls, _db, goal):
"""Return all external integrations by goal type.
"""
integrations = _db.query(cls).filter(
cls.goal==goal
).order_by(
cls.name
)
return integrations
@classmethod
def for_collection_and_purpose(cls, _db, collection, purpose):
"""Find the ExternalIntegration for the collection.
:param collection: Use the mirror configuration for this Collection.
:param purpose: Use the purpose of the mirror configuration.
"""
qu = _db.query(cls).join(
ExternalIntegrationLink,
ExternalIntegrationLink.other_integration_id==cls.id
).filter(
ExternalIntegrationLink.external_integration_id==collection.external_integration_id,
ExternalIntegrationLink.purpose==purpose
)
integrations = qu.all()
if not integrations:
raise CannotLoadConfiguration(
"No storage integration for collection '%s' and purpose '%s' is configured." %
(collection.name, purpose)
)
if len(integrations) > 1:
raise CannotLoadConfiguration(
"Multiple integrations found for collection '%s' and purpose '%s'" % (collection.name, purpose)
)
[integration] = integrations
return integration
@classmethod
def lookup(cls, _db, protocol, goal, library=None):
integrations = _db.query(cls).outerjoin(cls.libraries).filter(
cls.protocol==protocol, cls.goal==goal
)
if library:
integrations = integrations.filter(Library.id==library.id)
integrations = integrations.all()
if len(integrations) > 1:
logging.warn("Multiple integrations found for '%s'/'%s'" % (protocol, goal))
if filter(lambda i: i.libraries, integrations) and not library:
raise ValueError(
'This ExternalIntegration requires a library and none was provided.'
)
if not integrations:
return None
return integrations[0]
@classmethod
def with_setting_value(cls, _db, protocol, goal, key, value):
"""Find ExternalIntegrations with the given protocol, goal, and with a
particular ConfigurationSetting key/value pair.
This is useful in a scenario where an ExternalIntegration is
made unique by a ConfigurationSetting, such as
ExternalIntegration.URL, rather than by anything in the
ExternalIntecation itself.
:param protocol: ExternalIntegrations must have this protocol.
:param goal: ExternalIntegrations must have this goal.
:param key: Look only at ExternalIntegrations with
a ConfigurationSetting for this key.
:param value: Find ExternalIntegrations whose ConfigurationSetting
has this value.
:return: A Query object.
"""
return _db.query(
ExternalIntegration
).join(
ExternalIntegration.settings
).filter(
ExternalIntegration.goal==goal
).filter(
ExternalIntegration.protocol==protocol
).filter(
ConfigurationSetting.key==key
).filter(
ConfigurationSetting.value==value
)
@classmethod
def admin_authentication(cls, _db):
admin_auth = get_one(_db, cls, goal=cls.ADMIN_AUTH_GOAL)
return admin_auth
@classmethod
def for_library_and_goal(cls, _db, library, goal):
"""Find all ExternalIntegrations associated with the given
Library and the given goal.
:return: A Query.
"""
return _db.query(ExternalIntegration).join(
ExternalIntegration.libraries
).filter(
ExternalIntegration.goal==goal
).filter(
Library.id==library.id
)
@classmethod
def one_for_library_and_goal(cls, _db, library, goal):
"""Find the ExternalIntegration associated with the given
Library and the given goal.
:return: An ExternalIntegration, or None.
:raise: CannotLoadConfiguration
"""
integrations = cls.for_library_and_goal(_db, library, goal).all()
if len(integrations) == 0:
return None
if len(integrations) > 1:
raise CannotLoadConfiguration(
"Library %s defines multiple integrations with goal %s!" % (
library.name, goal
)
)
return integrations[0]
def set_setting(self, key, value):
"""Create or update a key-value setting for this ExternalIntegration."""
setting = self.setting(key)
setting.value = value
return setting
def setting(self, key):
"""Find or create a ConfigurationSetting on this ExternalIntegration.
:param key: Name of the setting.
:return: A ConfigurationSetting
"""
return ConfigurationSetting.for_externalintegration(
key, self
)
@hybrid_property
def url(self):
return self.setting(self.URL).value
@url.setter
def url(self, new_url):
self.set_setting(self.URL, new_url)
@hybrid_property
def username(self):
return self.setting(self.USERNAME).value
@username.setter
def username(self, new_username):
self.set_setting(self.USERNAME, new_username)
@hybrid_property
def password(self):
return self.setting(self.PASSWORD).value
@password.setter
def password(self, new_password):
return self.set_setting(self.PASSWORD, new_password)
@hybrid_property
def custom_accept_header(self):
return self.setting(self.CUSTOM_ACCEPT_HEADER).value
@custom_accept_header.setter
def custom_accept_header(self, new_custom_accept_header):
return self.set_setting(self.CUSTOM_ACCEPT_HEADER, new_custom_accept_header)
@hybrid_property
def primary_identifier_source(self):
return self.setting(self.PRIMARY_IDENTIFIER_SOURCE).value
@primary_identifier_source.setter
def primary_identifier_source(self, new_primary_identifier_source):
return self.set_setting(self.PRIMARY_IDENTIFIER_SOURCE,
new_primary_identifier_source)
def explain(self, library=None, include_secrets=False):
"""Create a series of human-readable strings to explain an
ExternalIntegration's settings.
:param library: Include additional settings imposed upon this
ExternalIntegration by the given Library.
:param include_secrets: For security reasons,
sensitive settings such as passwords are not displayed by default.
:return: A list of explanatory strings.
"""
lines = []
lines.append("ID: %s" % self.id)
if self.name:
lines.append("Name: %s" % self.name)
lines.append("Protocol/Goal: %s/%s" % (self.protocol, self.goal))
def key(setting):
if setting.library:
return setting.key, setting.library.name
return (setting.key, None)
for setting in sorted(self.settings, key=key):
if library and setting.library and setting.library != library:
# This is a different library's specialization of
# this integration. Ignore it.
continue
if setting.value is None:
# The setting has no value. Ignore it.
continue
explanation = "%s='%s'" % (setting.key, setting.value)
if setting.library:
explanation = "%s (applies only to %s)" % (
explanation, setting.library.name
)
if include_secrets or not setting.is_secret:
lines.append(explanation)
return lines
class ConfigurationSetting(Base, HasFullTableCache):
"""An extra piece of site configuration.
A ConfigurationSetting may be associated with an
ExternalIntegration, a Library, both, or neither.
* The secret used by the circulation manager to sign OAuth bearer
tokens is not associated with an ExternalIntegration or with a
Library.
* The link to a library's privacy policy is associated with the
Library, but not with any particular ExternalIntegration.
* The "website ID" for an Overdrive collection is associated with
an ExternalIntegration (the Overdrive integration), but not with
any particular Library (since multiple libraries might share an
Overdrive collection).
* The "identifier prefix" used to determine which library a patron
is a patron of, is associated with both a Library and an
ExternalIntegration.
"""
__tablename__ = 'configurationsettings'
id = Column(Integer, primary_key=True)
external_integration_id = Column(
Integer, ForeignKey('externalintegrations.id'), index=True
)
library_id = Column(
Integer, ForeignKey('libraries.id'), index=True
)
key = Column(Unicode, index=True)
_value = Column(Unicode, name="value")
__table_args__ = (
UniqueConstraint('external_integration_id', 'library_id', 'key'),
)
_cache = HasFullTableCache.RESET
_id_cache = HasFullTableCache.RESET
def __repr__(self):
return u'<ConfigurationSetting: key=%s, ID=%d>' % (
self.key, self.id)
@classmethod
def sitewide_secret(cls, _db, key):
"""Find or create a sitewide shared secret.
The value of this setting doesn't matter, only that it's
unique across the site and that it's always available.
"""
secret = ConfigurationSetting.sitewide(_db, key)
if not secret.value:
secret.value = random_string(24)
# Commit to get this in the database ASAP.
_db.commit()
return secret.value
@classmethod
def explain(cls, _db, include_secrets=False):
"""Explain all site-wide ConfigurationSettings."""
lines = []
site_wide_settings = []
for setting in _db.query(ConfigurationSetting).filter(
ConfigurationSetting.library==None).filter(
ConfigurationSetting.external_integration==None):
if not include_secrets and setting.key.endswith("_secret"):
continue
site_wide_settings.append(setting)
if site_wide_settings:
lines.append("Site-wide configuration settings:")
lines.append("---------------------------------")
for setting in sorted(site_wide_settings, key=lambda s: s.key):
if setting.value is None:
continue
lines.append("%s='%s'" % (setting.key, setting.value))
return lines
@classmethod
def sitewide(cls, _db, key):
"""Find or create a sitewide ConfigurationSetting."""
return cls.for_library_and_externalintegration(_db, key, None, None)
@classmethod
def for_library(cls, key, library):
"""Find or create a ConfigurationSetting for the given Library."""
_db = Session.object_session(library)
return cls.for_library_and_externalintegration(_db, key, library, None)
@classmethod
def for_externalintegration(cls, key, externalintegration):
"""Find or create a ConfigurationSetting for the given
ExternalIntegration.
"""
_db = Session.object_session(externalintegration)
return cls.for_library_and_externalintegration(
_db, key, None, externalintegration
)
@classmethod
def _cache_key(cls, library, external_integration, key):
if library:
library_id = library.id
else:
library_id = None
if external_integration:
external_integration_id = external_integration.id
else:
external_integration_id = None
return (library_id, external_integration_id, key)
def cache_key(self):
return self._cache_key(self.library, self.external_integration, self.key)
@classmethod
def for_library_and_externalintegration(
cls, _db, key, library, external_integration
):
"""Find or create a ConfigurationSetting associated with a Library
and an ExternalIntegration.
"""
def create():
"""Function called when a ConfigurationSetting is not found in cache
and must be created.
"""
return get_one_or_create(
_db, ConfigurationSetting,
library=library, external_integration=external_integration,
key=key
)
# ConfigurationSettings are stored in cache based on their library,
# external integration, and the name of the setting.
cache_key = cls._cache_key(library, external_integration, key)
setting, ignore = cls.by_cache_key(_db, cache_key, create)
return setting
@hybrid_property
def value(self):
"""What's the current value of this configuration setting?
If not present, the value may be inherited from some other
ConfigurationSetting.
"""
if self._value:
# An explicitly set value always takes precedence.
return self._value
elif self.library and self.external_integration:
# This is a library-specific specialization of an
# ExternalIntegration. Treat the value set on the
# ExternalIntegration as a default.
return self.for_externalintegration(
self.key, self.external_integration).value
elif self.library:
# This is a library-specific setting. Treat the site-wide
# value as a default.
_db = Session.object_session(self)
return self.sitewide(_db, self.key).value
return self._value
@value.setter
def value(self, new_value):
if new_value is not None:
new_value = unicode(new_value)
self._value = new_value
@classmethod
def _is_secret(self, key):
"""Should the value of the given key be treated as secret?
This will have to do, in the absence of programmatic ways of
saying that a specific setting should be treated as secret.
"""
return any(
key == x or
key.startswith('%s_' % x) or
key.endswith('_%s' % x) or
("_%s_" %x) in key
for x in ('secret', 'password')
)
@property
def is_secret(self):
"""Should the value of this key be treated as secret?"""
return self._is_secret(self.key)
def value_or_default(self, default):
"""Return the value of this setting. If the value is None,
set it to `default` and return that instead.
"""
if self.value is None:
self.value = default
return self.value
MEANS_YES = set(['true', 't', 'yes', 'y'])
@property
def bool_value(self):
"""Turn the value into a boolean if possible.
:return: A boolean, or None if there is no value.
"""
if self.value:
if self.value.lower() in self.MEANS_YES:
return True
return False
return None
@property
def int_value(self):
"""Turn the value into an int if possible.
:return: An integer, or None if there is no value.
:raise ValueError: If the value cannot be converted to an int.
"""
if self.value:
return int(self.value)
return None
@property
def float_value(self):
"""Turn the value into an float if possible.
:return: A float, or None if there is no value.
:raise ValueError: If the value cannot be converted to a float.
"""
if self.value:
return float(self.value)
return None
@property
def json_value(self):
"""Interpret the value as JSON if possible.
:return: An object, or None if there is no value.
:raise ValueError: If the value cannot be parsed as JSON.
"""
if self.value:
return json.loads(self.value)
return None
# As of this release of the software, this is our best guess as to
# which data sources should have their audiobooks excluded from
# lanes.
EXCLUDED_AUDIO_DATA_SOURCES_DEFAULT = []
@classmethod
def excluded_audio_data_sources(cls, _db):
"""List the data sources whose audiobooks should not be published in
feeds, either because this server can't fulfill them or the
expected client can't play them.
Most methods like this go into Configuration, but this one needs
to reference data model objects for its default value.
"""
value = cls.sitewide(
_db, Configuration.EXCLUDED_AUDIO_DATA_SOURCES
).json_value
if value is None:
value = cls.EXCLUDED_AUDIO_DATA_SOURCES_DEFAULT
return value
class HasExternalIntegration(object):
"""Interface allowing to get access to an external integration"""
__metaclass__ = ABCMeta
@abstractmethod
def external_integration(self, db):
"""Returns an external integration associated with this object
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:return: External integration associated with this object
:rtype: core.model.configuration.ExternalIntegration
"""
raise NotImplementedError()
class BaseConfigurationStorage(object):
"""Serializes and deserializes values as configuration settings"""
__metaclass__ = ABCMeta
@abstractmethod
def save(self, db, setting_name, value):
"""Save the value as as a new configuration setting
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param setting_name: Name of the configuration setting
:type setting_name: string
:param value: Value to be saved
:type value: Any
"""
raise NotImplementedError()
@abstractmethod
def load(self, db, setting_name):
"""Loads and returns the library's configuration setting
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param setting_name: Name of the configuration setting
:type setting_name: string
:return: Any
"""
raise NotImplementedError()
class ConfigurationStorage(BaseConfigurationStorage):
"""Serializes and deserializes values as configuration settings"""
def __init__(self, integration_association):
"""Initializes a new instance of ConfigurationStorage class
:param integration_association: Association with an external integration
:type integration_association: HasExternalIntegration
"""
self._integration_association = integration_association
def save(self, db, setting_name, value):
"""Save the value as as a new configuration setting
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param setting_name: Name of the configuration setting
:type setting_name: string
:param value: Value to be saved
:type value: Any
"""
integration = self._integration_association.external_integration(db)
ConfigurationSetting.for_externalintegration(
setting_name,
integration).value = value
def load(self, db, setting_name):
"""Loads and returns the library's configuration setting
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param setting_name: Name of the library's configuration setting
:type setting_name: string
:return: Any
"""
integration = self._integration_association.external_integration(db)
value = ConfigurationSetting.for_externalintegration(
setting_name,
integration).value
return value
class ConfigurationAttributeType(Enum):
"""Enumeration of configuration setting types"""
TEXT = 'text'
TEXTAREA = 'textarea'
SELECT = 'select'
NUMBER = 'number'
LIST = 'list'
MENU = 'menu'
def to_control_type(self):
"""Converts the value to a attribute type understandable by circulation-web
:return: String representation of attribute's type
:rtype: string
"""
# NOTE: For some reason, circulation-web converts "text" into <text> so we have to turn it into None
# In this case circulation-web will use <input>
# TODO: To be fixed in https://jira.nypl.org/browse/SIMPLY-3008
if self.value == self.TEXT.value:
return None
else:
return self.value
class ConfigurationAttribute(Enum):
"""Enumeration of configuration setting attributes"""
KEY = 'key'
LABEL = 'label'
DESCRIPTION = 'description'
TYPE = 'type'
REQUIRED = 'required'
DEFAULT = 'default'
OPTIONS = 'options'
CATEGORY = 'category'
FORMAT = 'format'
class ConfigurationOption(object):
"""Key-value pair containing information about configuration attribute option"""
def __init__(self, key, label):
"""Initializes a new instance of ConfigurationOption class
:param key: Key
:type key: string
:param label: Label
:type label: string
"""
self._key = key
self._label = label
def __eq__(self, other):
"""Compares two ConfigurationOption objects
:param other: ConfigurationOption object
:type other: ConfigurationOption
:return: Boolean value indicating whether two items are equal
:rtype: bool
"""
if not isinstance(other, ConfigurationOption):
return False
return \
self.key == other.key and \
self.label == other.label
@property
def key(self):
"""Returns option's key
:return: Option's key
:rtype: string
"""
return self._key
@property
def label(self):
"""Returns option's label
:return: Option's label
:rtype: string
"""
return self._label
def to_settings(self):
"""Returns a dictionary containing option metadata in the SETTINGS format
:return: Dictionary containing option metadata in the SETTINGS format
:rtype: Dict
"""
return {
'key': self.key,
'label': self.label
}
@staticmethod
def from_enum(cls):
"""Convers Enum to a list of options in the SETTINGS format
:param cls: Enum type
:type cls: type
:return: List of options in the SETTINGS format
:rtype: List[Dict]
"""
if not issubclass(cls, Enum):
raise ValueError('Class should be descendant of Enum')
return [
ConfigurationOption(element.value, element.name)
for element in cls
]
class HasConfigurationSettings(object):
"""Interface representing class containing ConfigurationMetadata properties"""
__metaclass__ = ABCMeta
@abstractmethod
def get_setting_value(self, setting_name):
"""Returns a settings'value
:param setting_name: Name of the setting
:type setting_name: string
:return: Setting's value
:rtype: Any
"""
raise NotImplementedError()
@abstractmethod
def set_setting_value(self, setting_name, setting_value):
"""Sets setting's value
:param setting_name: Name of the setting
:type setting_name: string
:param setting_value: New value of the setting
:type setting_value: Any
"""
raise NotImplementedError()
class ConfigurationMetadata(object):
"""Contains configuration metadata"""
_counter = 0
def __init__(
self,
key,
label,
description,
type,
required=False,
default=None,
options=None,
category=None,
format=None,
index=None
):
"""Initializes a new instance of ConfigurationMetadata class
:param key: Setting's key
:type key: string
:param label: Setting's label
:type label: string
:param description: Setting's description
:type description: string
:param type: Setting's type
:type type: ConfigurationAttributeType
:param required: Boolean value indicating whether the setting is required or not
:type required: bool
:param default: Setting's default value
:type default: Any
:param options: Setting's options (used in the case of select)
:type options: List[ConfigurationSettingAttributeOption]
:param category: Setting's category
:type category: string
"""
self._key = key
self._label = label
self._description = description
self._type = type
self._required = required
self._default = default
self._options = options
self._category = category
self._format = format
if index is not None:
self._index = index
else:
ConfigurationMetadata._counter += 1
self._index = ConfigurationMetadata._counter
def __get__(self, owner_instance, owner_type):
"""Returns a value of the setting
:param owner_instance: Instance of the owner, class having instance of ConfigurationMetadata as an attribute
:type owner_instance: Optional[ConfigurationMetadataOwner]
:param owner_type: Owner's class
:type owner_type: Optional[Type]
:return: ConfigurationMetadata instance (when called via a static method) or
the setting's value (when called via an instance method)
:rtype: Union[ConfigurationMetadata, Any]
"""
# If owner_instance is empty, it means that this method was called
# via a static method of ConfigurationMetadataOwner (for example, ConfigurationBucket.to_settings).
# In this case we need to return the metadata instance itself
if owner_instance is None:
return self
if not isinstance(owner_instance, HasConfigurationSettings):
raise Exception('owner must be an instance of ConfigurationSettingsMetadataOwner type')
return owner_instance.get_setting_value(self._key)
def __set__(self, owner_instance, value):
"""Updates the setting's value
:param owner_instance: Instance of the owner, class having instance of ConfigurationMetadata as an attribute
:type owner_instance: Optional[ConfigurationMetadataOwner]
:param value: New setting's value
:type value: Any
"""
if not isinstance(owner_instance, HasConfigurationSettings):
raise Exception('owner must be an instance ConfigurationSettingsMetadataOwner type')
return owner_instance.set_setting_value(self._key, value)
@property
def key(self):
"""Returns the setting's key
:return: Setting's key
:rtype: string
"""
return self._key
@property
def label(self):
"""Returns the setting's label
:return: Setting's label
:rtype: string
"""
return self._label
@property
def description(self):
"""Returns the setting's description
:return: Setting's description
:rtype: string
"""
return self._description
@property
def type(self):
"""Returns the setting's type
:return: Setting's type
:rtype: string
"""
return self._type
@property
def required(self):
"""Returns the boolean value indicating whether the setting is required or not
:return: Boolean value indicating whether the setting is required or not
:rtype: string
"""
return self._required
@property
def default(self):
"""Returns the setting's default value
:return: Setting's default value
:rtype: string
"""
return self._default
@property
def options(self):
"""Returns the setting's options (used in the case of select)
:return: Setting's options (used in the case of select)
:rtype: string
"""
return self._options
@property
def category(self):
"""Returns the setting's category
:return: Setting's category
:rtype: string
"""
return self._category
@property
def format(self):
"""Returns the setting's format
:return: Setting's format
:rtype: string
"""
return self._format
@property
def index(self):
return self._index
@staticmethod
def get_configuration_metadata(cls):
"""Returns a list of 2-tuples containing information ConfigurationMetadata properties in the specified class
:param cls: Class
:type cls: type
:return: List of 2-tuples containing information ConfigurationMetadata properties in the specified class
:rtype: List[Tuple[string, ConfigurationMetadata]]
"""
members = inspect.getmembers(cls)
configuration_metadata = []
for name, member in members:
if isinstance(member, ConfigurationMetadata):
configuration_metadata.append((name, member))
configuration_metadata.sort(key=lambda pair: pair[1].index)
return configuration_metadata
def to_settings(self):
return {
ConfigurationAttribute.KEY.value: self.key,
ConfigurationAttribute.LABEL.value: self.label,
ConfigurationAttribute.DESCRIPTION.value: self.description,
ConfigurationAttribute.TYPE.value: self.type.to_control_type(),
ConfigurationAttribute.REQUIRED.value: self.required,
ConfigurationAttribute.DEFAULT.value: self.default,
ConfigurationAttribute.OPTIONS.value:
[option.to_settings() for option in self.options]
if self.options
else None,
ConfigurationAttribute.CATEGORY.value: self.category,
ConfigurationAttribute.FORMAT.value: self.format
}
class ConfigurationGrouping(HasConfigurationSettings):
"""Base class for all classes containing configuration settings
NOTE: Be aware that it's valid only while a database session is valid and must not be stored between requests
"""
def __init__(self, configuration_storage, db):
"""Initializes a new instance of ConfigurationGrouping
:param configuration_storage: ConfigurationStorage object
:type configuration_storage: BaseConfigurationStorage
:param db: Database session
:type db: sqlalchemy.orm.session.Session
"""
self._logger = logging.getLogger()
self._configuration_storage = configuration_storage
self._db = db
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._db = None
def get_setting_value(self, setting_name):
"""Returns a settings'value
:param setting_name: Name of the setting
:type setting_name: string
:return: Setting's value
:rtype: Any
"""
return self._configuration_storage.load(self._db, setting_name)
def set_setting_value(self, setting_name, setting_value):
"""Sets setting's value
:param setting_name: Name of the setting
:type setting_name: string
:param setting_value: New value of the setting
:type setting_value: Any
"""
self._configuration_storage.save(self._db, setting_name, setting_value)
@classmethod
def to_settings_generator(cls):
"""Return a generator object returning settings in a format understandable by circulation-web.
:return: list of settings in a format understandable by circulation-web.
:rtype: List[Dict]
"""
for name, member in ConfigurationMetadata.get_configuration_metadata(cls):
key_attribute = getattr(member, ConfigurationAttribute.KEY.value, None)
label_attribute = getattr(member, ConfigurationAttribute.LABEL.value, None)
description_attribute = getattr(member, ConfigurationAttribute.DESCRIPTION.value, None)
type_attribute = getattr(member, ConfigurationAttribute.TYPE.value, None)
required_attribute = getattr(member, ConfigurationAttribute.REQUIRED.value, None)
default_attribute = getattr(member, ConfigurationAttribute.DEFAULT.value, None)
options_attribute = getattr(member, ConfigurationAttribute.OPTIONS.value, None)
category_attribute = getattr(member, ConfigurationAttribute.CATEGORY.value, None)
yield {
ConfigurationAttribute.KEY.value: key_attribute,
ConfigurationAttribute.LABEL.value: label_attribute,
ConfigurationAttribute.DESCRIPTION.value: description_attribute,
ConfigurationAttribute.TYPE.value: type_attribute.to_control_type(),
ConfigurationAttribute.REQUIRED.value: required_attribute,
ConfigurationAttribute.DEFAULT.value: default_attribute,
ConfigurationAttribute.OPTIONS.value:
[option.to_settings() for option in options_attribute]
if options_attribute
else None,
ConfigurationAttribute.CATEGORY.value: category_attribute
}
@classmethod
def to_settings(cls):
"""Return a list of settings in a format understandable by circulation-web.
:return: list of settings in a format understandable by circulation-web.
:rtype: List[Dict]
"""
return list(cls.to_settings_generator())
class ConfigurationFactory(object):
"""Factory creating new instances of ConfigurationGrouping class descendants."""
@contextmanager
def create(self, configuration_storage, db, configuration_grouping_class):
"""Create a new instance of ConfigurationGrouping.
:param configuration_storage: ConfigurationStorage object
:type configuration_storage: ConfigurationStorage
:param db: Database session
:type db: sqlalchemy.orm.session.Session
:param configuration_grouping_class: Configuration bucket's class
:type configuration_grouping_class: Type[ConfigurationGrouping]
:return: ConfigurationGrouping instance
:rtype: ConfigurationGrouping
"""
with configuration_grouping_class(configuration_storage, db) as configuration_bucket:
yield configuration_bucket
|
//
// QYHRetainCycleDetector.h
// QYHRetainCycleDetector
//
// Created by qinyihui on 2020/3/17.
// Copyright © 2020 qinyihui. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for QYHRetainCycleDetector.
FOUNDATION_EXPORT double QYHRetainCycleDetectorVersionNumber;
//! Project version string for QYHRetainCycleDetector.
FOUNDATION_EXPORT const unsigned char QYHRetainCycleDetectorVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <QYHRetainCycleDetector/PublicHeader.h>
#import "NSObject+QYHRCDObject.h"
#import "QYHRetainCycleFinder.h"
/**
Retain Cycle Detector is enabled by default in DEBUG builds, but you can also force it in other builds by
uncommenting the line below. Beware, Retain Cycle Detector uses some private APIs that shouldn't be compiled in
production builds.
*/
//#define QYHRCD_ENABLE 1
#ifdef QYHRCD_ENABLE
#define _INTERNAL_QYHRCD_ENABLE QYHRCD_ENABLE
#else
#define _INTERNAL_QYHRCD_ENABLE DEBUG
#endif
@interface QYHRetainCycleDetector : NSObject
+ (void)enable;
+ (void)disable;
+ (void)clearCacheAfterReceivingMemoryWarning;
@end
|
'''
MIT License
Copyright (c) 2021 Caio Alexandre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import typing
from .errors import SchemaError
__all__ = (
'SQLType',
'Integer',
'String',
'Json'
)
class SQLType:
python: typing.Any = None
def __str__(self):
return self.__class__.__name__
def to_sql(self) -> str:
raise NotImplementedError()
class Integer(SQLType):
python = int
def __init__(self, *, big: bool = False, small: bool = False, auto_increment: bool = False):
self.big = big
self.small = small
self.auto_increment = auto_increment
if big and small:
raise SchemaError('Integer column type cannot be both big and small')
def to_sql(self):
if self.auto_increment:
if self.big:
return 'BIGSERIAL'
if self.small:
return 'SMALLSERIAL'
return 'SERIAL'
if self.big:
return 'BIGINT'
if self.small:
return 'SMALLINT'
return 'INTEGER'
class String(SQLType):
python = str
def __init__(self, *, length: int = None, fixed: bool = False):
if fixed and not length:
raise SchemaError('Cannot have fixed string with no length')
self.length = length
self.fixed = fixed
def to_sql(self):
if not self.length:
return 'TEXT'
if self.fixed:
return f'CHAR({self.length})'
return f'VARCHAR({self.length})'
class Json(SQLType):
python = [list, dict]
def to_sql(self):
return 'JSONB'
|
/*global exports:false,require:false
*/
var grunt, gruntload;
grunt = require('grunt');
gruntload = require('../lib/index')(grunt);
exports['gruntload'] = {
'getNpmTasks auto': function(test) {
var tasks;
tasks = gruntload.getNpmTasks();
test.deepEqual(tasks, ['grunt-contrib-coffee', 'grunt-contrib-jshint', 'grunt-contrib-nodeunit', 'grunt-contrib-watch']);
return test.done();
},
'getNpmTasks single': function(test) {
var tasks;
tasks = gruntload.getNpmTasks('one');
test.deepEqual(tasks, ['one']);
return test.done();
},
'getNpmTasks list': function(test) {
var list, tasks;
list = ['one', 'two', 'three'];
tasks = gruntload.getNpmTasks(list);
test.deepEqual(tasks, list);
return test.done();
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BreadCrumb = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class BreadCrumb extends _react.Component {
itemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
}
renderHome() {
if (this.props.home) {
const className = (0, _classnames.default)('p-breadcrumb-home', this.props.home.className, {
'p-disabled': this.props.home.disabled
});
return _react.default.createElement("li", {
className: className,
style: this.props.home.style
}, _react.default.createElement("a", {
href: this.props.home.url || '#',
className: "p-menuitem-link",
target: this.props.home.target,
onClick: event => this.itemClick(event, this.props.home)
}, _react.default.createElement("span", {
className: this.props.home.icon
})));
} else {
return null;
}
}
renderSeparator() {
return _react.default.createElement("li", {
className: "p-breadcrumb-chevron pi pi-chevron-right"
});
}
renderMenuitem(item, index) {
const className = (0, _classnames.default)(item.className, {
'p-disabled': item.disabled
});
return _react.default.createElement("li", {
role: "menuitem",
className: className,
style: item.style
}, _react.default.createElement("a", {
href: item.url || '#',
className: "p-menuitem-link",
target: item.target,
onClick: event => this.itemClick(event, item)
}, _react.default.createElement("span", {
className: "p-menuitem-text"
}, item.label)));
}
renderMenuitems() {
if (this.props.model) {
const items = this.props.model.map((item, index) => {
const menuitem = this.renderMenuitem(item, index);
const separator = index === this.props.model.length - 1 ? null : this.renderSeparator();
return _react.default.createElement(_react.default.Fragment, {
key: item.label + '_' + index
}, menuitem, separator);
});
return items;
} else {
return null;
}
}
render() {
const className = (0, _classnames.default)('p-breadcrumb p-component', this.props.className);
const home = this.renderHome();
const items = this.renderMenuitems();
const separator = this.renderSeparator();
return _react.default.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, _react.default.createElement("ul", null, home, separator, items));
}
}
exports.BreadCrumb = BreadCrumb;
_defineProperty(BreadCrumb, "defaultProps", {
id: null,
model: null,
home: null,
style: null,
className: null
});
_defineProperty(BreadCrumb, "propTypes", {
id: _propTypes.default.string,
model: _propTypes.default.array,
home: _propTypes.default.any,
style: _propTypes.default.object,
className: _propTypes.default.string
});
|
#!/usr/bin/env python
"""
CI build script
(C) 2017 Jack Lloyd
Botan is released under the Simplified BSD License (see license.txt)
"""
import os
import platform
import subprocess
import sys
import time
import tempfile
import optparse # pylint: disable=deprecated-module
def get_concurrency():
"""
Get default concurrency level of build
"""
def_concurrency = 2
try:
import multiprocessing
return multiprocessing.cpu_count()
except ImportError:
return def_concurrency
def determine_flags(target, target_os, target_cpu, target_cc, cc_bin, ccache, root_dir, pkcs11_lib):
# pylint: disable=too-many-branches,too-many-statements,too-many-arguments,too-many-locals
"""
Return the configure.py flags as well as make/test running prefixes
"""
is_cross_target = target.startswith('cross-')
if target_os not in ['linux', 'osx', 'windows']:
print('Error unknown OS %s' % (target_os))
return (None, None, None)
if is_cross_target:
if target_os == 'osx':
target_os = 'ios'
elif target == 'cross-win64':
target_os = 'mingw'
elif target in ['cross-android-arm32', 'cross-android-arm64']:
target_os = 'android'
make_prefix = []
test_prefix = []
test_cmd = [os.path.join(root_dir, 'botan-test')]
if target in ['shared', 'static', 'sanitizer', 'fuzzers', 'gcc4.8', 'cross-i386', 'bsi', 'nist']:
test_cmd += ['--test-threads=%d' % (get_concurrency())]
fast_tests = ['block', 'aead', 'hash', 'stream', 'mac', 'modes', 'kdf',
'hmac_drbg', 'hmac_drbg_unit',
'tls', 'ffi',
'rsa_sign', 'rsa_verify', 'dh_kat',
'ecc_randomized', 'ecdh_kat', 'ecdsa_sign', 'curve25519_scalar',
'cpuid', 'simd_32', 'os_utils', 'util', 'util_dates']
install_prefix = os.path.join(tempfile.gettempdir(), 'botan-install')
flags = ['--prefix=%s' % (install_prefix),
'--cc=%s' % (target_cc),
'--os=%s' % (target_os)]
if target_cpu is not None:
flags += ['--cpu=%s' % (target_cpu)]
if target in ['shared', 'mini-shared']:
flags += ['--disable-static']
if target in ['static', 'mini-static', 'fuzzers'] or target_os in ['ios', 'mingw']:
flags += ['--disable-shared']
if target in ['mini-static', 'mini-shared']:
flags += ['--minimized-build', '--enable-modules=system_rng,sha2_32,sha2_64,aes']
if target == 'static':
# Arbitrarily test amalgamation with the static lib builds
flags += ['--amalgamation']
if target_cc == 'msvc':
flags += ['--single-amalgamation-file']
if target in ['bsi', 'nist']:
# Arbitrarily test disable static on module policy builds
# tls is optional for bsi/nist but add it so verify tests work with these minimized configs
flags += ['--module-policy=%s' % (target),
'--enable-modules=tls',
'--disable-static']
if target == 'docs':
flags += ['--with-doxygen', '--with-sphinx', '--with-rst2man']
test_cmd = None
if target == 'coverage':
flags += ['--with-coverage-info', '--test-mode', '--build-bogo-shim']
if target == 'valgrind':
# valgrind in 16.04 has a bug with rdrand handling
flags += ['--with-valgrind', '--disable-rdrand']
test_prefix = ['valgrind', '--error-exitcode=9', '-v', '--leak-check=full', '--show-reachable=yes']
test_cmd += fast_tests
if target == 'fuzzers':
flags += ['--unsafe-fuzzer-mode']
if target in ['fuzzers', 'coverage', 'valgrind']:
flags += ['--with-debug-info']
if target in ['fuzzers', 'coverage']:
flags += ['--build-fuzzers=test']
if target in ['fuzzers', 'sanitizer']:
flags += ['--with-sanitizers', '--with-debug-asserts']
if target in ['valgrind', 'sanitizer', 'fuzzers']:
flags += ['--disable-modules=locking_allocator']
if target == 'parallel':
flags += ['--with-openmp']
if target == 'sonar':
if target_os != 'linux' or target_cc != 'clang':
raise Exception('Only Linux/clang supported in Sonar target currently')
# Use of -Os here is a little odd, but the issue is that the build time
# is quite long (because ccache from Xenial doesn't work right with
# these profiling flags) but we can't use --no-optimizations as that
# will make running the tests too slow.
flags += ['--cc-abi-flags=-fprofile-instr-generate -fcoverage-mapping',
'--disable-shared',
'--optimize-for-size']
make_prefix = [os.path.join(root_dir, 'build-wrapper-linux-x86/build-wrapper-linux-x86-64'),
'--out-dir', 'bw-outputs']
if is_cross_target:
if target_os == 'ios':
make_prefix = ['xcrun', '--sdk', 'iphoneos']
test_cmd = None
if target == 'cross-arm32':
flags += ['--cpu=armv7', '--cc-abi-flags=-arch armv7 -arch armv7s -stdlib=libc++']
elif target == 'cross-arm64':
flags += ['--cpu=arm64', '--cc-abi-flags=-arch arm64 -stdlib=libc++']
else:
raise Exception("Unknown cross target '%s' for iOS" % (target))
elif target_os == 'android':
ndk = os.getenv('ANDROID_NDK')
if ndk is None:
raise Exception('Android CI build requires ANDROID_NDK env variable be set')
api_lvl = int(os.getenv('ANDROID_API_LEVEL', '0'))
if api_lvl == 0:
# If not set arbitrarily choose API 16 (Android 4.1) for ARMv7 and 28 (Android 9) for AArch64
api_lvl = 16 if target == 'cross-android-arm32' else 28
toolchain_dir = os.path.join(ndk, 'toolchains/llvm/prebuilt/linux-x86_64/bin')
test_cmd = None
if target == 'cross-android-arm32':
cc_bin = os.path.join(toolchain_dir, 'armv7a-linux-androideabi%d-clang++' % (api_lvl))
flags += ['--cpu=armv7',
'--ar-command=%s' % (os.path.join(toolchain_dir, 'arm-linux-androideabi-ar'))]
elif target == 'cross-android-arm64':
cc_bin = os.path.join(toolchain_dir, 'aarch64-linux-android%d-clang++' % (api_lvl))
flags += ['--cpu=arm64',
'--ar-command=%s' % (os.path.join(toolchain_dir, 'aarch64-linux-android-ar'))]
if api_lvl < 18:
flags += ['--without-os-features=getauxval']
if api_lvl >= 28:
flags += ['--with-os-features=getentropy']
elif target == 'cross-i386':
flags += ['--cpu=x86_32']
elif target == 'cross-win64':
# MinGW in 16.04 is lacking std::mutex for unknown reason
cc_bin = 'x86_64-w64-mingw32-g++'
flags += ['--cpu=x86_64', '--cc-abi-flags=-static',
'--ar-command=x86_64-w64-mingw32-ar', '--without-os-feature=threads']
test_cmd = [os.path.join(root_dir, 'botan-test.exe')] + test_cmd[1:]
# No runtime prefix required for Wine
else:
# Build everything but restrict what is run
test_cmd += fast_tests
if target == 'cross-arm32':
flags += ['--cpu=armv7']
cc_bin = 'arm-linux-gnueabihf-g++'
test_prefix = ['qemu-arm', '-L', '/usr/arm-linux-gnueabihf/']
elif target == 'cross-arm64':
flags += ['--cpu=aarch64']
cc_bin = 'aarch64-linux-gnu-g++'
test_prefix = ['qemu-aarch64', '-L', '/usr/aarch64-linux-gnu/']
elif target == 'cross-ppc32':
flags += ['--cpu=ppc32']
cc_bin = 'powerpc-linux-gnu-g++'
test_prefix = ['qemu-ppc', '-L', '/usr/powerpc-linux-gnu/']
elif target == 'cross-ppc64':
flags += ['--cpu=ppc64', '--with-endian=little']
cc_bin = 'powerpc64le-linux-gnu-g++'
test_prefix = ['qemu-ppc64le', '-cpu', 'POWER8', '-L', '/usr/powerpc64le-linux-gnu/']
elif target == 'cross-mips64':
flags += ['--cpu=mips64', '--with-endian=big']
cc_bin = 'mips64-linux-gnuabi64-g++'
test_prefix = ['qemu-mips64', '-L', '/usr/mips64-linux-gnuabi64/']
else:
raise Exception("Unknown cross target '%s' for Linux" % (target))
else:
# Flags specific to native targets
if target == 'gcc4.8':
cc_bin = 'g++-4.8'
if target_os in ['osx', 'linux']:
flags += ['--with-bzip2', '--with-sqlite', '--with-zlib']
if target_os in ['osx', 'ios']:
flags += ['--with-commoncrypto']
if target_os == 'osx' or target == 'coverage':
flags += ['--with-boost']
if target_os == 'windows' and target in ['shared', 'static']:
# ./configure.py needs extra hand-holding for boost on windows
boost_root = os.environ.get('BOOST_ROOT')
boost_libs = os.environ.get('BOOST_LIBRARYDIR')
boost_system = os.environ.get('BOOST_SYSTEM_LIBRARY')
if boost_root and boost_libs and boost_system:
flags += ['--with-boost',
'--with-external-includedir', boost_root,
'--with-external-libdir', boost_libs,
'--boost-library-name', boost_system]
if target_os == 'linux':
flags += ['--with-lzma']
if target_os == 'linux':
if target not in ['sanitizer', 'valgrind', 'mini-shared', 'mini-static']:
# Avoid OpenSSL when using dynamic checkers, or on OS X where it sporadically
# is not installed on the CI image
flags += ['--with-openssl']
if target in ['sonar', 'coverage']:
flags += ['--with-tpm']
test_cmd += ['--run-long-tests', '--run-online-tests']
if pkcs11_lib and os.access(pkcs11_lib, os.R_OK):
test_cmd += ['--pkcs11-lib=%s' % (pkcs11_lib)]
if ccache is None:
flags += ['--cc-bin=%s' % (cc_bin)]
elif ccache == 'clcache':
flags += ['--cc-bin=%s' % (ccache)]
else:
flags += ['--cc-bin=%s %s' % (ccache, cc_bin)]
# Avoid putting the revision in build.h, which helps ccache hit rates
flags += ['--no-store-vc-rev']
if test_cmd is None:
run_test_command = None
else:
run_test_command = test_prefix + test_cmd
return flags, run_test_command, make_prefix
def run_cmd(cmd, root_dir):
"""
Execute a command, die if it failed
"""
print("Running '%s' ..." % (' '.join(cmd)))
sys.stdout.flush()
start = time.time()
cmd = [os.path.expandvars(elem) for elem in cmd]
sub_env = os.environ.copy()
sub_env['LD_LIBRARY_PATH'] = os.path.abspath(root_dir)
sub_env['PYTHONPATH'] = os.path.abspath(os.path.join(root_dir, 'src/python'))
cwd = None
redirect_stdout = None
if len(cmd) > 3 and cmd[-2] == '>':
redirect_stdout = open(cmd[-1], 'w')
cmd = cmd[:-2]
if len(cmd) > 1 and cmd[0].startswith('indir:'):
cwd = cmd[0][6:]
cmd = cmd[1:]
while len(cmd) > 1 and cmd[0].startswith('env:') and cmd[0].find('=') > 0:
env_key, env_val = cmd[0][4:].split('=')
sub_env[env_key] = env_val
cmd = cmd[1:]
proc = subprocess.Popen(cmd, cwd=cwd, close_fds=True, env=sub_env, stdout=redirect_stdout)
proc.communicate()
time_taken = int(time.time() - start)
if time_taken > 10:
print("Ran for %d seconds" % (time_taken))
if proc.returncode != 0:
print("Command '%s' failed with error code %d" % (' '.join(cmd), proc.returncode))
if cmd[0] not in ['lcov']:
sys.exit(proc.returncode)
def parse_args(args):
"""
Parse arguments
"""
parser = optparse.OptionParser()
parser.add_option('--os', default=platform.system().lower(),
help='Set the target os (default %default)')
parser.add_option('--cc', default='gcc',
help='Set the target compiler type (default %default)')
parser.add_option('--cc-bin', default=None,
help='Set path to compiler')
parser.add_option('--root-dir', metavar='D', default='.',
help='Set directory to execute from (default %default)')
parser.add_option('--make-tool', metavar='TOOL', default='make',
help='Specify tool to run to build source (default %default)')
parser.add_option('--cpu', default=None,
help='Specify a target CPU platform')
parser.add_option('--with-debug', action='store_true', default=False,
help='Include debug information')
parser.add_option('--amalgamation', action='store_true', default=False,
help='Build via amalgamation')
parser.add_option('--disable-shared', action='store_true', default=False,
help='Disable building shared libraries')
parser.add_option('--branch', metavar='B', default=None,
help='Specify branch being built')
parser.add_option('--add-travis-folds', action='store_true', default=False,
help='Add fold markers for Travis UI')
parser.add_option('--dry-run', action='store_true', default=False,
help='Just show commands to be executed')
parser.add_option('--build-jobs', metavar='J', default=get_concurrency(),
help='Set number of jobs to run in parallel (default %default)')
parser.add_option('--compiler-cache', default=None, metavar='CC',
help='Set a compiler cache to use (ccache, sccache, clcache)')
parser.add_option('--pkcs11-lib', default=None, metavar='LIB',
help='Set PKCS11 lib to use for testing')
parser.add_option('--with-python3', dest='use_python3', action='store_true', default=None,
help='Enable using python3')
parser.add_option('--without-python3', dest='use_python3', action='store_false',
help='Disable using python3')
parser.add_option('--with-pylint3', dest='use_pylint3', action='store_true', default=True,
help='Enable using python3 pylint')
parser.add_option('--without-pylint3', dest='use_pylint3', action='store_false',
help='Disable using python3 pylint')
return parser.parse_args(args)
def have_prog(prog):
"""
Check if some named program exists in the path
"""
for path in os.environ['PATH'].split(os.pathsep):
exe_file = os.path.join(path, prog)
if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
return True
return False
def main(args=None):
# pylint: disable=too-many-branches,too-many-statements,too-many-locals,too-many-return-statements
"""
Parse options, do the things
"""
if os.getenv('COVERITY_SCAN_BRANCH') == '1':
print('Skipping build COVERITY_SCAN_BRANCH set in environment')
return 0
if args is None:
args = sys.argv
print("Invoked as '%s'" % (' '.join(args)))
(options, args) = parse_args(args)
if len(args) != 2:
print('Usage: %s [options] target' % (args[0]))
return 1
target = args[1]
use_python2 = have_prog('python2')
if options.use_python3 is None:
use_python3 = have_prog('python3')
else:
use_python3 = options.use_python3
py_interp = 'python'
if use_python3:
py_interp = 'python3'
if options.cc_bin is None:
if options.cc == 'gcc':
options.cc_bin = 'g++'
elif options.cc == 'clang':
options.cc_bin = 'clang++'
elif options.cc == 'msvc':
options.cc_bin = 'cl'
else:
print('Error unknown compiler %s' % (options.cc))
return 1
if options.compiler_cache is None and options.cc != 'msvc':
# Autodetect ccache, unless using clang profiling - ccache seems to misbehave there
if have_prog('ccache') and target not in ['sonar']:
options.compiler_cache = 'ccache'
if options.compiler_cache == 'clcache' and target in ['sanitizer']:
# clcache doesn't support /Zi so using it just adds overhead with
# no benefit
options.compiler_cache = None
if target == 'sonar' and os.getenv('SONAR_TOKEN') is None:
print('Skipping Sonar scan due to missing SONAR_TOKEN env variable')
return 0
root_dir = options.root_dir
if not os.access(root_dir, os.R_OK):
raise Exception('Bad root dir setting, dir %s not readable' % (root_dir))
cmds = []
if target == 'lint':
if not use_python2 and not use_python3:
raise Exception('No python interpreters found cannot lint')
pylint_rc = '--rcfile=%s' % (os.path.join(root_dir, 'src/configs/pylint.rc'))
pylint_flags = [pylint_rc, '--reports=no']
# Some disabled rules specific to Python2
# superfluous-parens: needed for Python3 compatible print statements
# too-many-locals: variable counting differs from pylint3
py2_flags = '--disable=superfluous-parens,too-many-locals'
# Some disabled rules specific to Python3
# useless-object-inheritance: complains about code still useful in Python2
py3_flags = '--disable=useless-object-inheritance'
py_scripts = [
'configure.py',
'src/python/botan2.py',
'src/scripts/ci_build.py',
'src/scripts/install.py',
'src/scripts/dist.py',
'src/scripts/cleanup.py',
'src/scripts/build_docs.py',
'src/scripts/website.py',
'src/scripts/bench.py',
'src/scripts/test_python.py',
'src/scripts/test_fuzzers.py',
'src/scripts/test_cli.py',
'src/scripts/python_unittests.py',
'src/scripts/python_unittests_unix.py']
full_paths = [os.path.join(root_dir, s) for s in py_scripts]
if use_python2:
cmds.append(['python2', '-m', 'pylint'] + pylint_flags + [py2_flags] + full_paths)
if use_python3 and options.use_pylint3:
cmds.append(['python3', '-m', 'pylint'] + pylint_flags + [py3_flags] + full_paths)
else:
config_flags, run_test_command, make_prefix = determine_flags(
target, options.os, options.cpu, options.cc,
options.cc_bin, options.compiler_cache, root_dir,
options.pkcs11_lib)
cmds.append([py_interp, os.path.join(root_dir, 'configure.py')] + config_flags)
make_cmd = [options.make_tool]
if root_dir != '.':
make_cmd += ['-C', root_dir]
if options.build_jobs > 1:
make_cmd += ['-j%d' % (options.build_jobs)]
make_cmd += ['-k']
if target == 'docs':
cmds.append(make_cmd + ['docs'])
else:
ccache_show_stats = {
'ccache': '--show-stats',
'sccache': '--show-stats',
'clcache': '-s'
}
if options.compiler_cache in ccache_show_stats:
cmds.append([options.compiler_cache, ccache_show_stats[options.compiler_cache]])
make_targets = ['libs', 'tests', 'cli']
if target in ['coverage', 'fuzzers']:
make_targets += ['tests', 'cli', 'fuzzers', 'fuzzer_corpus_zip']
if target in ['coverage']:
make_targets += ['bogo_shim']
cmds.append(make_prefix + make_cmd + make_targets)
if options.compiler_cache in ccache_show_stats:
cmds.append([options.compiler_cache, ccache_show_stats[options.compiler_cache]])
if run_test_command is not None:
cmds.append(run_test_command)
if target == 'coverage':
runner_dir = os.path.abspath(os.path.join(root_dir, 'boringssl', 'ssl', 'test', 'runner'))
cmds.append(['indir:%s' % (runner_dir),
'go', 'test', '-pipe',
'-num-workers', str(4*get_concurrency()),
'-shim-path', os.path.abspath(os.path.join(root_dir, 'botan_bogo_shim')),
'-shim-config', os.path.abspath(os.path.join(root_dir, 'src', 'bogo_shim', 'config.json'))])
if target in ['coverage', 'fuzzers']:
cmds.append([py_interp, os.path.join(root_dir, 'src/scripts/test_fuzzers.py'),
os.path.join(root_dir, 'fuzzer_corpus'),
os.path.join(root_dir, 'build/fuzzer')])
if target in ['shared', 'coverage'] and options.os != 'windows':
botan_exe = os.path.join(root_dir, 'botan-cli.exe' if options.os == 'windows' else 'botan')
test_scripts = ['cli_tests.py', 'test_cli.py']
for script in test_scripts:
cmds.append([py_interp, os.path.join(root_dir, 'src/scripts', script),
botan_exe])
python_tests = os.path.join(root_dir, 'src/scripts/test_python.py')
if target in ['shared', 'coverage']:
if options.os == 'windows':
if options.cpu == 'x86':
# Python on AppVeyor is a 32-bit binary so only test for 32-bit
cmds.append([py_interp, '-b', python_tests])
else:
if use_python2:
cmds.append(['python2', '-b', python_tests])
if use_python3:
cmds.append(['python3', '-b', python_tests])
if target in ['shared', 'static', 'bsi', 'nist']:
cmds.append(make_cmd + ['install'])
if target in ['sonar']:
cmds.append(['llvm-profdata', 'merge', '-sparse', 'default.profraw', '-o', 'botan.profdata'])
cmds.append(['llvm-cov', 'show', './botan-test',
'-instr-profile=botan.profdata',
'>', 'build/cov_report.txt'])
sonar_config = os.path.join(root_dir, 'src/configs/sonar-project.properties')
cmds.append(['sonar-scanner',
'-Dproject.settings=%s' % (sonar_config),
'-Dsonar.login=$SONAR_TOKEN'])
if target in ['coverage']:
if not have_prog('lcov'):
print('Error: lcov not found in PATH (%s)' % (os.getenv('PATH')))
return 1
if not have_prog('gcov'):
print('Error: gcov not found in PATH (%s)' % (os.getenv('PATH')))
return 1
cov_file = 'coverage.info'
raw_cov_file = 'coverage.info.raw'
cmds.append(['lcov', '--capture', '--directory', options.root_dir,
'--output-file', raw_cov_file])
cmds.append(['lcov', '--remove', raw_cov_file, '/usr/*', '--output-file', cov_file])
cmds.append(['lcov', '--list', cov_file])
if have_prog('coverage'):
cmds.append(['coverage', 'run', '--branch',
'--rcfile', os.path.join(root_dir, 'src/configs/coverage.rc'),
python_tests])
if have_prog('codecov'):
# If codecov exists assume we are on Travis and report to codecov.io
cmds.append(['codecov'])
else:
# Otherwise generate a local HTML report
cmds.append(['genhtml', cov_file, '--output-directory', 'lcov-out'])
cmds.append(make_cmd + ['clean'])
cmds.append(make_cmd + ['distclean'])
for cmd in cmds:
if options.dry_run:
print('$ ' + ' '.join(cmd))
else:
run_cmd(cmd, root_dir)
return 0
if __name__ == '__main__':
sys.exit(main())
|
// threejs.org/license
(function(l,za){"object"===typeof exports&&"undefined"!==typeof module?za(exports):"function"===typeof define&&define.amd?define(["exports"],za):za(l.THREE=l.THREE||{})})(this,function(l){function za(){}function C(a,b){this.x=a||0;this.y=b||0}function ea(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:Ze++});this.uuid=T.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function ga(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Bb(a,b,c){this.uuid=T.generateUUID();this.width=
a;this.height=b;this.scissor=new ga(0,0,a,b);this.scissorTest=!1;this.viewport=new ga(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ea(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Cb(a,b,c){Bb.call(this,a,b,c);this.activeMipMapLevel=
this.activeCubeFace=0}function ca(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function q(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function Q(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function Xa(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];ea.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Db(a,b,c){var d=a[0];if(0>=d||0<d)return a;
var e=b*c,f=se[e];void 0===f&&(f=new Float32Array(e),se[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function te(a,b){var c=ue[b];void 0===c&&(c=new Int32Array(b),ue[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function $e(a,b){a.uniform1f(this.addr,b)}function af(a,b){a.uniform1i(this.addr,b)}function bf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function cf(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):
void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,b)}function df(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function ef(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function ff(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,!1,b):(ve.set(b.elements),a.uniformMatrix3fv(this.addr,!1,ve))}function gf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(we.set(b.elements),a.uniformMatrix4fv(this.addr,!1,we))}function hf(a,
b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||xe,d)}function jf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||ye,d)}function ze(a,b){a.uniform2iv(this.addr,b)}function Ae(a,b){a.uniform3iv(this.addr,b)}function Be(a,b){a.uniform4iv(this.addr,b)}function kf(a){switch(a){case 5126:return $e;case 35664:return bf;case 35665:return cf;case 35666:return df;case 35674:return ef;case 35675:return ff;case 35676:return gf;case 35678:return hf;case 35680:return jf;
case 5124:case 35670:return af;case 35667:case 35671:return ze;case 35668:case 35672:return Ae;case 35669:case 35673:return Be}}function lf(a,b){a.uniform1fv(this.addr,b)}function mf(a,b){a.uniform1iv(this.addr,b)}function nf(a,b){a.uniform2fv(this.addr,Db(b,this.size,2))}function of(a,b){a.uniform3fv(this.addr,Db(b,this.size,3))}function pf(a,b){a.uniform4fv(this.addr,Db(b,this.size,4))}function qf(a,b){a.uniformMatrix2fv(this.addr,!1,Db(b,this.size,4))}function rf(a,b){a.uniformMatrix3fv(this.addr,
!1,Db(b,this.size,9))}function sf(a,b){a.uniformMatrix4fv(this.addr,!1,Db(b,this.size,16))}function tf(a,b,c){var d=b.length,e=te(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||xe,e[a])}function uf(a,b,c){var d=b.length,e=te(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||ye,e[a])}function vf(a){switch(a){case 5126:return lf;case 35664:return nf;case 35665:return of;case 35666:return pf;case 35674:return qf;case 35675:return rf;case 35676:return sf;case 35678:return tf;
case 35680:return uf;case 5124:case 35670:return mf;case 35667:case 35671:return ze;case 35668:case 35672:return Ae;case 35669:case 35673:return Be}}function wf(a,b,c){this.id=a;this.addr=c;this.setValue=kf(b.type)}function xf(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=vf(b.type)}function Ce(a){this.id=a;this.seq=[];this.map={}}function Ya(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),
f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=h.length;for(Pd.lastIndex=0;;){var m=Pd.exec(h),u=Pd.lastIndex,p=m[1],n=m[3];"]"===m[2]&&(p|=0);if(void 0===n||"["===n&&u+2===k){h=g;e=void 0===n?new wf(p,e,f):new xf(p,e,f);h.seq.push(e);h.map[e.id]=e;break}else n=g.map[p],void 0===n&&(n=new Ce(p),p=g,g=n,p.seq.push(g),p.map[g.id]=g),g=n}}}function J(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function cb(a,b,c,d,e,f,g,h,k,m,u,p){ea.call(this,null,f,g,h,k,m,d,e,u,p);this.image=
{data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function id(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function yf(a,b){var c,d,e,f,g,h,k,m,u,p,n=a.context,r=a.state,l,t,z,w,y,M;this.render=function(v,F,G){if(0!==b.length){v=new q;var A=G.w/G.z,H=.5*G.z,ba=.5*G.w,Fa=16/G.w,U=new C(Fa*A,Fa),na=new q(1,1,0),db=new C(1,1),Ta=new id;Ta.min.set(G.x,
G.y);Ta.max.set(G.x+(G.z-16),G.y+(G.w-16));if(void 0===w){var Fa=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),P=new Uint16Array([0,1,2,0,2,3]);l=n.createBuffer();t=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,l);n.bufferData(n.ARRAY_BUFFER,Fa,n.STATIC_DRAW);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t);n.bufferData(n.ELEMENT_ARRAY_BUFFER,P,n.STATIC_DRAW);y=n.createTexture();M=n.createTexture();r.bindTexture(n.TEXTURE_2D,y);n.texImage2D(n.TEXTURE_2D,0,n.RGB,16,16,0,n.RGB,n.UNSIGNED_BYTE,null);
n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);r.bindTexture(n.TEXTURE_2D,M);n.texImage2D(n.TEXTURE_2D,0,n.RGBA,16,16,0,n.RGBA,n.UNSIGNED_BYTE,null);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);n.texParameteri(n.TEXTURE_2D,
n.TEXTURE_MAG_FILTER,n.NEAREST);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST);var Fa=z={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nvUV = uv;\nvec2 pos = position;\nif ( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility = visibility.r / 9.0;\nvVisibility *= 1.0 - visibility.g / 9.0;\nvVisibility *= visibility.b / 9.0;\nvVisibility *= 1.0 - visibility.a / 9.0;\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif ( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if ( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},P=n.createProgram(),K=n.createShader(n.FRAGMENT_SHADER),
L=n.createShader(n.VERTEX_SHADER),S="precision "+a.getPrecision()+" float;\n";n.shaderSource(K,S+Fa.fragmentShader);n.shaderSource(L,S+Fa.vertexShader);n.compileShader(K);n.compileShader(L);n.attachShader(P,K);n.attachShader(P,L);n.linkProgram(P);w=P;u=n.getAttribLocation(w,"position");p=n.getAttribLocation(w,"uv");c=n.getUniformLocation(w,"renderType");d=n.getUniformLocation(w,"map");e=n.getUniformLocation(w,"occlusionMap");f=n.getUniformLocation(w,"opacity");g=n.getUniformLocation(w,"color");h=
n.getUniformLocation(w,"scale");k=n.getUniformLocation(w,"rotation");m=n.getUniformLocation(w,"screenPosition")}n.useProgram(w);r.initAttributes();r.enableAttribute(u);r.enableAttribute(p);r.disableUnusedAttributes();n.uniform1i(e,0);n.uniform1i(d,1);n.bindBuffer(n.ARRAY_BUFFER,l);n.vertexAttribPointer(u,2,n.FLOAT,!1,16,0);n.vertexAttribPointer(p,2,n.FLOAT,!1,16,8);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t);r.disable(n.CULL_FACE);r.buffers.depth.setMask(!1);P=0;for(K=b.length;P<K;P++)if(Fa=16/G.w,U.set(Fa*
A,Fa),L=b[P],v.set(L.matrixWorld.elements[12],L.matrixWorld.elements[13],L.matrixWorld.elements[14]),v.applyMatrix4(F.matrixWorldInverse),v.applyMatrix4(F.projectionMatrix),na.copy(v),db.x=G.x+na.x*H+H-8,db.y=G.y+na.y*ba+ba-8,!0===Ta.containsPoint(db)){r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,null);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,y);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGB,db.x,db.y,16,16,0);n.uniform1i(c,0);n.uniform2f(h,U.x,U.y);n.uniform3f(m,na.x,na.y,na.z);r.disable(n.BLEND);
r.enable(n.DEPTH_TEST);n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0);r.activeTexture(n.TEXTURE0);r.bindTexture(n.TEXTURE_2D,M);n.copyTexImage2D(n.TEXTURE_2D,0,n.RGBA,db.x,db.y,16,16,0);n.uniform1i(c,1);r.disable(n.DEPTH_TEST);r.activeTexture(n.TEXTURE1);r.bindTexture(n.TEXTURE_2D,y);n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0);L.positionScreen.copy(na);L.customUpdateCallback?L.customUpdateCallback(L):L.updateLensFlares();n.uniform1i(c,2);r.enable(n.BLEND);for(var S=0,qa=L.lensFlares.length;S<
qa;S++){var V=L.lensFlares[S];.001<V.opacity&&.001<V.scale&&(na.x=V.x,na.y=V.y,na.z=V.z,Fa=V.size*V.scale/G.w,U.x=Fa*A,U.y=Fa,n.uniform3f(m,na.x,na.y,na.z),n.uniform2f(h,U.x,U.y),n.uniform1f(k,V.rotation),n.uniform1f(f,V.opacity),n.uniform3f(g,V.color.r,V.color.g,V.color.b),r.setBlending(V.blending,V.blendEquation,V.blendSrc,V.blendDst),a.setTexture2D(V.texture,1),n.drawElements(n.TRIANGLES,6,n.UNSIGNED_SHORT,0))}}r.enable(n.CULL_FACE);r.enable(n.DEPTH_TEST);r.buffers.depth.setMask(!0);a.resetGLState()}}}
function zf(a,b){var c,d,e,f,g,h,k,m,u,p,n,r,l,t,z,w,y;function M(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var v=a.context,F=a.state,G,A,H,ba,Fa=new q,U=new ca,na=new q;this.render=function(q,Ta){if(0!==b.length){if(void 0===H){var P=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),K=new Uint16Array([0,1,2,0,2,3]);G=v.createBuffer();A=v.createBuffer();v.bindBuffer(v.ARRAY_BUFFER,G);v.bufferData(v.ARRAY_BUFFER,P,v.STATIC_DRAW);
v.bindBuffer(v.ELEMENT_ARRAY_BUFFER,A);v.bufferData(v.ELEMENT_ARRAY_BUFFER,K,v.STATIC_DRAW);var P=v.createProgram(),K=v.createShader(v.VERTEX_SHADER),L=v.createShader(v.FRAGMENT_SHADER);v.shaderSource(K,["precision "+a.getPrecision()+" float;","uniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position * scale;\nvec2 rotatedPosition;\nrotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\nrotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\nvec4 finalPosition;\nfinalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition;\nfinalPosition = projectionMatrix * finalPosition;\ngl_Position = finalPosition;\n}"].join("\n"));
v.shaderSource(L,["precision "+a.getPrecision()+" float;","uniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\nif ( texture.a < alphaTest ) discard;\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\nif ( fogType > 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n"));
v.compileShader(K);v.compileShader(L);v.attachShader(P,K);v.attachShader(P,L);v.linkProgram(P);H=P;w=v.getAttribLocation(H,"position");y=v.getAttribLocation(H,"uv");c=v.getUniformLocation(H,"uvOffset");d=v.getUniformLocation(H,"uvScale");e=v.getUniformLocation(H,"rotation");f=v.getUniformLocation(H,"scale");g=v.getUniformLocation(H,"color");h=v.getUniformLocation(H,"map");k=v.getUniformLocation(H,"opacity");m=v.getUniformLocation(H,"modelViewMatrix");u=v.getUniformLocation(H,"projectionMatrix");p=
v.getUniformLocation(H,"fogType");n=v.getUniformLocation(H,"fogDensity");r=v.getUniformLocation(H,"fogNear");l=v.getUniformLocation(H,"fogFar");t=v.getUniformLocation(H,"fogColor");z=v.getUniformLocation(H,"alphaTest");P=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");P.width=8;P.height=8;K=P.getContext("2d");K.fillStyle="white";K.fillRect(0,0,8,8);ba=new ea(P);ba.needsUpdate=!0}v.useProgram(H);F.initAttributes();F.enableAttribute(w);F.enableAttribute(y);F.disableUnusedAttributes();
F.disable(v.CULL_FACE);F.enable(v.BLEND);v.bindBuffer(v.ARRAY_BUFFER,G);v.vertexAttribPointer(w,2,v.FLOAT,!1,16,0);v.vertexAttribPointer(y,2,v.FLOAT,!1,16,8);v.bindBuffer(v.ELEMENT_ARRAY_BUFFER,A);v.uniformMatrix4fv(u,!1,Ta.projectionMatrix.elements);F.activeTexture(v.TEXTURE0);v.uniform1i(h,0);K=P=0;(L=q.fog)?(v.uniform3f(t,L.color.r,L.color.g,L.color.b),L.isFog?(v.uniform1f(r,L.near),v.uniform1f(l,L.far),v.uniform1i(p,1),K=P=1):L.isFogExp2&&(v.uniform1f(n,L.density),v.uniform1i(p,2),K=P=2)):(v.uniform1i(p,
0),K=P=0);for(var L=0,S=b.length;L<S;L++){var qa=b[L];qa.modelViewMatrix.multiplyMatrices(Ta.matrixWorldInverse,qa.matrixWorld);qa.z=-qa.modelViewMatrix.elements[14]}b.sort(M);for(var V=[],L=0,S=b.length;L<S;L++){var qa=b[L],C=qa.material;!1!==C.visible&&(v.uniform1f(z,C.alphaTest),v.uniformMatrix4fv(m,!1,qa.modelViewMatrix.elements),qa.matrixWorld.decompose(Fa,U,na),V[0]=na.x,V[1]=na.y,qa=0,q.fog&&C.fog&&(qa=K),P!==qa&&(v.uniform1i(p,qa),P=qa),null!==C.map?(v.uniform2f(c,C.map.offset.x,C.map.offset.y),
v.uniform2f(d,C.map.repeat.x,C.map.repeat.y)):(v.uniform2f(c,0,0),v.uniform2f(d,1,1)),v.uniform1f(k,C.opacity),v.uniform3f(g,C.color.r,C.color.g,C.color.b),v.uniform1f(e,C.rotation),v.uniform2fv(f,V),F.setBlending(C.blending,C.blendEquation,C.blendSrc,C.blendDst),F.buffers.depth.setTest(C.depthTest),F.buffers.depth.setMask(C.depthWrite),C.map?a.setTexture2D(C.map,0):a.setTexture2D(ba,0),v.drawElements(v.TRIANGLES,6,v.UNSIGNED_SHORT,0))}F.enable(v.CULL_FACE);a.resetGLState()}}}function X(){Object.defineProperty(this,
"id",{value:Af++});this.uuid=T.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.shading=2;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=
!1;this.alphaTest=this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.premultipliedAlpha=!1;this.overdraw=0;this._needsUpdate=this.visible=!0}function Ga(a){X.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=
this.morphTargets=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function Za(a){X.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=!1;this.displacementMap=
this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function Ua(a,b){this.min=void 0!==a?a:new q(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new q(-Infinity,-Infinity,-Infinity)}function Aa(a,b){this.center=void 0!==a?a:new q;this.radius=void 0!==b?b:0}function Ba(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}
function ia(a,b){this.normal=void 0!==a?a:new q(1,0,0);this.constant=void 0!==b?b:0}function jd(a,b,c,d,e,f){this.planes=[void 0!==a?a:new ia,void 0!==b?b:new ia,void 0!==c?c:new ia,void 0!==d?d:new ia,void 0!==e?e:new ia,void 0!==f?f:new ia]}function De(a,b,c,d){function e(b,c,d,e){var f=b.geometry,g;g=t;var h=b.customDepthMaterial;d&&(g=z,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:
f&&f.isGeometry&&(h=f.morphTargets&&0<f.morphTargets.length)),b=b.isSkinnedMesh,f=0,h&&(f|=1),b&&(f|=2),g=g[f]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(f=g.uuid,h=c.uuid,b=w[f],void 0===b&&(b={},w[f]=b),f=b[h],void 0===f&&(f=g.clone(),b[h]=f),g=f);g.visible=c.visible;g.wireframe=c.wireframe;h=c.side;ba.renderSingleSided&&2==h&&(h=0);ba.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=
c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(b,d,g,h){if(!1!==b.visible){if(b.layers.test(d.layers)&&(b.isMesh||b.isLine||b.isPoints)&&b.castShadow&&(!b.frustumCulled||k.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,b.matrixWorld);var m=c.update(b),n=b.material;if(Array.isArray(n))for(var u=m.groups,p=0,r=u.length;p<r;p++){var w=u[p],y=n[w.materialIndex];y&&y.visible&&(y=e(b,y,h,
l),a.renderBufferDirect(g,null,m,y,b,w))}else n.visible&&(y=e(b,n,h,l),a.renderBufferDirect(g,null,m,y,b,null))}b=b.children;m=0;for(n=b.length;m<n;m++)f(b[m],d,g,h)}}var g=a.context,h=a.state,k=new jd,m=new Q,u=b.shadows,p=new C,n=new C(d.maxTextureSize,d.maxTextureSize),r=new q,l=new q,t=Array(4),z=Array(4),w={},y=[new q(1,0,0),new q(-1,0,0),new q(0,0,1),new q(0,0,-1),new q(0,1,0),new q(0,-1,0)],M=[new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,1,0),new q(0,0,1),new q(0,0,-1)],v=[new ga,new ga,
new ga,new ga,new ga,new ga];b=new Za;b.depthPacking=3201;b.clipping=!0;d=$a.distanceRGBA;for(var F=Ja.clone(d.uniforms),G=0;4!==G;++G){var A=0!==(G&1),H=b.clone();H.morphTargets=A;t[G]=H;A=new Ga({defines:{USE_SHADOWMAP:""},uniforms:F,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:A,clipping:!0});z[G]=A}var ba=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c){if(!1!==ba.enabled&&
(!1!==ba.autoUpdate||!1!==ba.needsUpdate)&&0!==u.length){h.disable(g.BLEND);h.buffers.color.setClear(1,1,1,1);h.buffers.depth.setTest(!0);h.setScissorTest(!1);for(var d,e,w=0,t=u.length;w<t;w++){var q=u[w],z=q.shadow;if(void 0===z)console.warn("THREE.WebGLShadowMap:",q,"has no shadow.");else{var A=z.camera;p.copy(z.mapSize);p.min(n);if(q&&q.isPointLight){d=6;e=!0;var G=p.x,F=p.y;v[0].set(2*G,F,G,F);v[1].set(0,F,G,F);v[2].set(3*G,F,G,F);v[3].set(G,F,G,F);v[4].set(3*G,0,G,F);v[5].set(G,0,G,F);p.x*=
4;p.y*=2}else d=1,e=!1;null===z.map&&(z.map=new Bb(p.x,p.y,{minFilter:1003,magFilter:1003,format:1023}),z.map.texture.name=q.name+".shadowMap",A.updateProjectionMatrix());z.isSpotLightShadow&&z.update(q);z&&z.isRectAreaLightShadow&&z.update(q);G=z.map;z=z.matrix;l.setFromMatrixPosition(q.matrixWorld);A.position.copy(l);a.setRenderTarget(G);a.clear();for(G=0;G<d;G++)e?(r.copy(A.position),r.add(y[G]),A.up.copy(M[G]),A.lookAt(r),h.viewport(v[G])):(r.setFromMatrixPosition(q.target.matrixWorld),A.lookAt(r)),
A.updateMatrixWorld(),A.matrixWorldInverse.getInverse(A.matrixWorld),z.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),z.multiply(A.projectionMatrix),z.multiply(A.matrixWorldInverse),m.multiplyMatrices(A.projectionMatrix,A.matrixWorldInverse),k.setFromMatrix(m),f(b,c,A,e)}}d=a.getClearColor();e=a.getClearAlpha();a.setClearColor(d,e);ba.needsUpdate=!1}}}function eb(a,b){this.origin=void 0!==a?a:new q;this.direction=void 0!==b?b:new q}function ab(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=
d||ab.DefaultOrder}function Qd(){this.mask=1}function E(){Object.defineProperty(this,"id",{value:Bf++});this.uuid=T.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=E.DefaultUp.clone();var a=new q,b=new ab,c=new ca,d=new q(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,{position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},
scale:{enumerable:!0,value:d},modelViewMatrix:{value:new Q},normalMatrix:{value:new Ba}});this.matrix=new Q;this.matrixWorld=new Q;this.matrixAutoUpdate=E.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Qd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={};this.onBeforeRender=function(){};this.onAfterRender=function(){}}function Eb(a,b){this.start=void 0!==a?a:new q;this.end=void 0!==b?b:new q}function Ka(a,b,c){this.a=
void 0!==a?a:new q;this.b=void 0!==b?b:new q;this.c=void 0!==c?c:new q}function ua(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new q;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new J;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function La(a){X.call(this);this.type="MeshBasicMaterial";this.color=new J(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=
this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=!1;this.setValues(a)}function W(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");Object.defineProperty(this,"id",{value:Cf++});this.uuid=T.generateUUID();this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===
c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function qc(a,b){W.call(this,new Int8Array(a),b)}function rc(a,b){W.call(this,new Uint8Array(a),b)}function sc(a,b){W.call(this,new Uint8ClampedArray(a),b)}function tc(a,b){W.call(this,new Int16Array(a),b)}function fb(a,b){W.call(this,new Uint16Array(a),b)}function uc(a,b){W.call(this,new Int32Array(a),b)}function gb(a,b){W.call(this,new Uint32Array(a),b)}function B(a,b){W.call(this,new Float32Array(a),
b)}function vc(a,b){W.call(this,new Float64Array(a),b)}function Ee(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Rd(a){for(var b=a.length,c=-Infinity;b--;)a[b]>c&&(c=a[b]);return c}function R(){Object.defineProperty(this,
"id",{value:Sd++});this.uuid=T.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function I(){Object.defineProperty(this,
"id",{value:Sd++});this.uuid=T.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function wa(a,b){E.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new I;this.material=void 0!==b?b:new La({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Fb(a,b,c,d,e,f){R.call(this);this.type="BoxGeometry";this.parameters=
{width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new hb(a,b,c,d,e,f));this.mergeVertices()}function hb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,l,G,A,H){var ba=f/G,C=g/A,U=f/2,na=g/2,E=l/2;g=G+1;var B=A+1,P=f=0,K,L,S=new q;for(L=0;L<B;L++){var I=L*C-na;for(K=0;K<g;K++)S[a]=(K*ba-U)*d,S[b]=I*e,S[c]=E,m.push(S.x,S.y,S.z),S[a]=0,S[b]=0,S[c]=0<l?1:-1,u.push(S.x,S.y,S.z),p.push(K/G),p.push(1-L/A),f+=1}for(L=0;L<A;L++)for(K=0;K<G;K++)a=n+K+g*(L+1),b=n+(K+
1)+g*(L+1),c=n+(K+1)+g*L,k.push(n+K+g*L,a,c),k.push(a,b,c),P+=6;h.addGroup(r,P,H);r+=P;n+=f}I.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=[],m=[],u=[],p=[],n=0,r=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",
-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",new B(m,3));this.addAttribute("normal",new B(u,3));this.addAttribute("uv",new B(p,2))}function wc(a,b,c,d){R.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new ib(a,b,c,d))}function ib(a,b,c,d){I.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||
1;var g=c+1,h=d+1,k=a/c,m=b/d,u=[],p=[],n=[],r=[];for(a=0;a<h;a++){var l=a*m-f;for(b=0;b<g;b++)p.push(b*k-e,-l,0),n.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,u.push(b+g*a,e,h),u.push(e,f,h);this.setIndex(u);this.addAttribute("position",new B(p,3));this.addAttribute("normal",new B(n,3));this.addAttribute("uv",new B(r,2))}function da(){E.call(this);this.type="Camera";this.matrixWorldInverse=new Q;this.projectionMatrix=new Q}function Ea(a,
b,c,d){da.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function Gb(a,b,c,d,e,f){da.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Df(a){var b=
{};return{get:function(a){a.isInterleavedBufferAttribute&&(a=a.data);return b[a.id]},remove:function(c){var d=b[c.id];d&&(a.deleteBuffer(d.buffer),delete b[c.id])},update:function(c,d){c.isInterleavedBufferAttribute&&(c=c.data);var e=b[c.id];if(void 0===e){var e=c.id,f=c,g=f.array,h=f.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,k=a.createBuffer();a.bindBuffer(d,k);a.bufferData(d,g,h);f.onUploadCallback();h=a.FLOAT;g instanceof Float32Array?h=a.FLOAT:g instanceof Float64Array?console.warn("Unsupported data buffer format: Float64Array"):
g instanceof Uint16Array?h=a.UNSIGNED_SHORT:g instanceof Int16Array?h=a.SHORT:g instanceof Uint32Array?h=a.UNSIGNED_INT:g instanceof Int32Array?h=a.INT:g instanceof Int8Array?h=a.BYTE:g instanceof Uint8Array&&(h=a.UNSIGNED_BYTE);b[e]={buffer:k,type:h,bytesPerElement:g.BYTES_PER_ELEMENT,version:f.version}}else e.version<c.version&&(f=c,g=f.array,k=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,g,a.STATIC_DRAW):-1===k.count?a.bufferSubData(d,0,g):0===k.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):
(a.bufferSubData(d,k.offset*g.BYTES_PER_ELEMENT,g.subarray(k.offset,k.offset+k.count)),k.count=0),e.version=c.version)}}}function Ef(a,b,c){var d,e,f;return{setMode:function(a){d=a},setIndex:function(c){c.array instanceof Uint32Array&&b.get("OES_element_index_uint")?(e=a.UNSIGNED_INT,f=4):c.array instanceof Uint16Array?(e=a.UNSIGNED_SHORT,f=2):(e=a.UNSIGNED_BYTE,f=1)},render:function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)},renderInstances:function(g,
h,k){var m=b.get("ANGLE_instanced_arrays");null===m?console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(m.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=k*g.maxInstancedCount,d===a.TRIANGLES&&(c.faces+=g.maxInstancedCount*k/3))}}}function Ff(a,b,c){var d;return{setMode:function(a){d=a},render:function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES&&(c.faces+=
f/3)},renderInstances:function(e){var f=b.get("ANGLE_instanced_arrays");if(null===f)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{var g=e.attributes.position,g=g.isInterleavedBufferAttribute?g.data.count:g.count;f.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES&&(c.faces+=e.maxInstancedCount*g/3)}}}}function Gf(a,b,c){function d(a){a=
a.target;var h=e[a.id];null!==h.index&&b.remove(h.index);for(var k in h.attributes)b.remove(h.attributes[k]);a.removeEventListener("dispose",d);delete e[a.id];if(k=f[a.id])b.remove(k),delete f[a.id];if(k=f[h.id])b.remove(k),delete f[h.id];c.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new I).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;
return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=c[f],e=0,u=d.length;e<u;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;var d=[],e=c.index,m=c.attributes;if(null!==e)for(var e=e.array,m=0,u=e.length;m<u;m+=3){var p=e[m+0],n=e[m+1],r=e[m+2];d.push(p,n,n,r,r,p)}else for(e=m.position.array,m=0,u=e.length/3-1;m<u;m+=
3)p=m+0,n=m+1,r=m+2,d.push(p,n,n,r,r,p);d=new (65535<Rd(d)?gb:fb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Hf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];var c;switch(b.type){case "DirectionalLight":c={direction:new q,color:new J,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new q,direction:new q,color:new J,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};
break;case "PointLight":c={position:new q,color:new J,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "HemisphereLight":c={direction:new q,skyColor:new J,groundColor:new J};break;case "RectAreaLight":c={color:new J,position:new q,halfWidth:new q,halfHeight:new q}}return a[b.id]=c}}}function If(a,b,c){var d={};return{update:function(a){var f=c.frame,g=a.geometry,h=b.get(a,g);d[h.id]!==f&&(g.isGeometry&&h.updateFromObject(a),b.update(h),d[h.id]=f);return h},
clear:function(){d={}}}}function Jf(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Fe(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),Jf(c));return d}function Ge(a){switch(a){case 3E3:return["Linear",
"( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Td(a,b){var c=Ge(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function Kf(a,b){var c=Ge(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+
c[0]+c[1]+"; }"}function Lf(a,b){var c;switch(b){case 1:c="Linear";break;case 2:c="Reinhard";break;case 3:c="Uncharted2";break;case 4:c="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function Mf(a,b,c){a=a||{};return[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?
"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(xc).join("\n")}function Nf(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function xc(a){return""!==a}function He(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,
b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Ud(a){return a.replace(/#include +<([\w\d.]+)>/g,function(a,c){var d=Y[c];if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Ud(d)})}function Ie(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function Of(a,b,c,d){var e=
a.context,f=c.extensions,g=c.defines,h=c.__webglShader.vertexShader,k=c.__webglShader.fragmentShader,m="SHADOWMAP_TYPE_BASIC";1===d.shadowMapType?m="SHADOWMAP_TYPE_PCF":2===d.shadowMapType&&(m="SHADOWMAP_TYPE_PCF_SOFT");var u="ENVMAP_TYPE_CUBE",p="ENVMAP_MODE_REFLECTION",n="ENVMAP_BLENDING_MULTIPLY";if(d.envMap){switch(c.envMap.mapping){case 301:case 302:u="ENVMAP_TYPE_CUBE";break;case 306:case 307:u="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:u="ENVMAP_TYPE_EQUIREC";break;case 305:u="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:p=
"ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:n="ENVMAP_BLENDING_MULTIPLY";break;case 1:n="ENVMAP_BLENDING_MIX";break;case 2:n="ENVMAP_BLENDING_ADD"}}var r=0<a.gammaFactor?a.gammaFactor:1,f=Mf(f,d,a.extensions),l=Nf(g),t=e.createProgram();c.isRawShaderMaterial?(g=[l,"\n"].filter(xc).join("\n"),m=[f,l,"\n"].filter(xc).join("\n")):(g=["precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.supportsVertexTextures?"#define VERTEX_TEXTURES":
"","#define GAMMA_FACTOR "+r,"#define MAX_BONES "+d.maxBones,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":"",d.map?"#define USE_MAP":"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+p:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":"",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.displacementMap&&d.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",d.specularMap?"#define USE_SPECULARMAP":
"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?"#define USE_COLOR":"",d.flatShading?"#define FLAT_SHADED":"",d.skinning?"#define USE_SKINNING":"",d.useVertexTexture?"#define BONE_TEXTURE":"",d.morphTargets?"#define USE_MORPHTARGETS":"",d.morphNormals&&!1===d.flatShading?"#define USE_MORPHNORMALS":"",d.doubleSided?"#define DOUBLE_SIDED":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+
d.numClippingPlanes,d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.sizeAttenuation?"#define USE_SIZEATTENUATION":"",d.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;",
"attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;",
"\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(xc).join("\n"),m=[f,"precision "+d.precision+" float;","precision "+d.precision+" int;","#define SHADER_NAME "+c.__webglShader.name,l,d.alphaTest?"#define ALPHATEST "+d.alphaTest:"","#define GAMMA_FACTOR "+r,d.useFog&&d.fog?"#define USE_FOG":"",d.useFog&&d.fogExp?"#define FOG_EXP2":"",d.map?"#define USE_MAP":
"",d.envMap?"#define USE_ENVMAP":"",d.envMap?"#define "+u:"",d.envMap?"#define "+p:"",d.envMap?"#define "+n:"",d.lightMap?"#define USE_LIGHTMAP":"",d.aoMap?"#define USE_AOMAP":"",d.emissiveMap?"#define USE_EMISSIVEMAP":"",d.bumpMap?"#define USE_BUMPMAP":"",d.normalMap?"#define USE_NORMALMAP":"",d.specularMap?"#define USE_SPECULARMAP":"",d.roughnessMap?"#define USE_ROUGHNESSMAP":"",d.metalnessMap?"#define USE_METALNESSMAP":"",d.alphaMap?"#define USE_ALPHAMAP":"",d.vertexColors?"#define USE_COLOR":
"",d.gradientMap?"#define USE_GRADIENTMAP":"",d.flatShading?"#define FLAT_SHADED":"",d.doubleSided?"#define DOUBLE_SIDED":"",d.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+d.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(d.numClippingPlanes-d.numClipIntersection),d.shadowMapEnabled?"#define USE_SHADOWMAP":"",d.shadowMapEnabled?"#define "+m:"",d.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",d.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",d.logarithmicDepthBuffer?
"#define USE_LOGDEPTHBUF":"",d.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",d.envMap&&a.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==d.toneMapping?"#define TONE_MAPPING":"",0!==d.toneMapping?Y.tonemapping_pars_fragment:"",0!==d.toneMapping?Lf("toneMapping",d.toneMapping):"",d.outputEncoding||d.mapEncoding||d.envMapEncoding||d.emissiveMapEncoding?Y.encodings_pars_fragment:
"",d.mapEncoding?Td("mapTexelToLinear",d.mapEncoding):"",d.envMapEncoding?Td("envMapTexelToLinear",d.envMapEncoding):"",d.emissiveMapEncoding?Td("emissiveMapTexelToLinear",d.emissiveMapEncoding):"",d.outputEncoding?Kf("linearToOutputTexel",d.outputEncoding):"",d.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(xc).join("\n"));h=Ud(h,d);h=He(h,d);k=Ud(k,d);k=He(k,d);c.isShaderMaterial||(h=Ie(h),k=Ie(k));k=m+k;h=Fe(e,e.VERTEX_SHADER,g+h);k=Fe(e,e.FRAGMENT_SHADER,k);e.attachShader(t,
h);e.attachShader(t,k);void 0!==c.index0AttributeName?e.bindAttribLocation(t,0,c.index0AttributeName):!0===d.morphTargets&&e.bindAttribLocation(t,0,"position");e.linkProgram(t);d=e.getProgramInfoLog(t);u=e.getShaderInfoLog(h);p=e.getShaderInfoLog(k);r=n=!0;if(!1===e.getProgramParameter(t,e.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",e.getError(),"gl.VALIDATE_STATUS",e.getProgramParameter(t,e.VALIDATE_STATUS),"gl.getProgramInfoLog",d,u,p);else if(""!==d)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",
d);else if(""===u||""===p)r=!1;r&&(this.diagnostics={runnable:n,material:c,programLog:d,vertexShader:{log:u,prefix:g},fragmentShader:{log:p,prefix:m}});e.deleteShader(h);e.deleteShader(k);var q;this.getUniforms=function(){void 0===q&&(q=new Ya(e,t,a));return q};var w;this.getAttributes=function(){if(void 0===w){for(var a={},b=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=e.getActiveAttrib(t,c).name;a[d]=e.getAttribLocation(t,d)}w=a}return w};this.destroy=function(){e.deleteProgram(t);
this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=Pf++;this.code=b;this.usedTimes=1;this.program=t;this.vertexShader=h;this.fragmentShader=k;return this}function Qf(a,b){function c(a,b){var c;a?a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&
(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding):c=3E3;3E3===c&&b&&(c=3007);return c}var d=[],e={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},
f="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking".split(" ");
this.getParameters=function(d,f,k,m,u,p){var n=e[d.type],r;if(p.isSkinnedMesh){r=p.skeleton;var l=r.bones;if(b.floatVertexTextures){if(void 0===r.boneTexture){var l=Math.sqrt(4*l.length),l=T.nextPowerOfTwo(Math.ceil(l)),l=Math.max(l,4),t=new Float32Array(l*l*4);t.set(r.boneMatrices);var q=new cb(t,l,l,1023,1015);r.boneMatrices=t;r.boneTexture=q;r.boneTextureSize=l}r=1024}else r=Math.min(Math.floor((b.maxVertexUniforms-20)/4),l.length),r<l.length&&(console.warn("THREE.WebGLRenderer: Skeleton has "+
l.length+" bones. This GPU supports "+r+"."),r=0)}else r=0;l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));t=a.getCurrentRenderTarget();return{shaderID:n,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(t?t.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,
a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,displacementMap:!!d.displacementMap,roughnessMap:!!d.roughnessMap,metalnessMap:!!d.metalnessMap,specularMap:!!d.specularMap,alphaMap:!!d.alphaMap,gradientMap:!!d.gradientMap,combine:d.combine,vertexColors:d.vertexColors,fog:!!k,useFog:d.fog,fogExp:k&&k.isFogExp2,
flatShading:1===d.shading,sizeAttenuation:d.sizeAttenuation,logarithmicDepthBuffer:b.logarithmicDepthBuffer,skinning:p&&p.isSkinnedMesh&&0<r,maxBones:r,useVertexTexture:b.floatVertexTextures,morphTargets:d.morphTargets,morphNormals:d.morphNormals,maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:u,
shadowMapEnabled:a.shadowMap.enabled&&p.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,alphaTest:d.alphaTest,doubleSided:2===d.side,flipSided:1===d.side,depthPacking:void 0!==d.depthPacking?d.depthPacking:!1}};this.getProgramCode=function(a,b){var c=[];b.shaderID?c.push(b.shaderID):(c.push(a.fragmentShader),c.push(a.vertexShader));if(void 0!==a.defines)for(var d in a.defines)c.push(d),
c.push(a.defines[d]);for(d=0;d<f.length;d++)c.push(b[f[d]]);return c.join()};this.acquireProgram=function(b,c,e){for(var f,u=0,p=d.length;u<p;u++){var n=d[u];if(n.code===e){f=n;++f.usedTimes;break}}void 0===f&&(f=new Of(a,e,b,c),d.push(f));return f};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=d.indexOf(a);d[b]=d[d.length-1];d.pop();a.destroy()}};this.programs=d}function Rf(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml",
"canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return T.isPowerOfTwo(a.width)&&T.isPowerOfTwo(a.height)}function m(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function u(b){b=b.target;b.removeEventListener("dispose",u);a:{var c=d.get(b);if(b.image&&
c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);
else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function n(b,m){var n=d.get(b);if(0<b.version&&n.__version!==b.version){var p=b.image;if(void 0===p)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===p.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===n.__webglInit&&(n.__webglInit=
!0,b.addEventListener("dispose",u),n.__webglTexture=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_2D,n.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var l=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(l))if(p=l,p instanceof HTMLImageElement||p instanceof HTMLCanvasElement){var t=
document.createElementNS("http://www.w3.org/1999/xhtml","canvas");t.width=T.nearestPowerOfTwo(p.width);t.height=T.nearestPowerOfTwo(p.height);t.getContext("2d").drawImage(p,0,0,t.width,t.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+p.width+"x"+p.height+"). Resized to "+t.width+"x"+t.height,p);l=t}else l=p;var p=k(l),t=f(b.format),x=f(b.type);r(a.TEXTURE_2D,b,p);var H=b.mipmaps;if(b.isDepthTexture){H=a.DEPTH_COMPONENT;if(1015===b.type){if(!q)throw Error("Float Depth Texture only supported in WebGL2.0");
H=a.DEPTH_COMPONENT32F}else q&&(H=a.DEPTH_COMPONENT16);1026===b.format&&H===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,x=f(b.type));1027===b.format&&(H=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,x=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,H,l.width,l.height,0,t,x,null)}else if(b.isDataTexture)if(0<
H.length&&p){for(var ba=0,C=H.length;ba<C;ba++)l=H[ba],c.texImage2D(a.TEXTURE_2D,ba,t,l.width,l.height,0,t,x,l.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,t,l.width,l.height,0,t,x,l.data);else if(b.isCompressedTexture)for(ba=0,C=H.length;ba<C;ba++)l=H[ba],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(t)?c.compressedTexImage2D(a.TEXTURE_2D,ba,t,l.width,l.height,0,l.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
c.texImage2D(a.TEXTURE_2D,ba,t,l.width,l.height,0,t,x,l.data);else if(0<H.length&&p){ba=0;for(C=H.length;ba<C;ba++)l=H[ba],c.texImage2D(a.TEXTURE_2D,ba,t,t,x,l);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,t,t,x,l);b.generateMipmaps&&p&&a.generateMipmap(a.TEXTURE_2D);n.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_2D,n.__webglTexture)}function r(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,
f(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,m(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,m(g.minFilter)),
1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=
g.anisotropy)}function l(b,e,g,h){var k=f(e.texture.format),m=f(e.texture.type);c.texImage2D(h,0,k,e.width,e.height,0,k,m,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function t(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,
b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var q="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext;this.setTexture2D=n;this.setTextureCube=function(b,m){var n=d.get(b);if(6===b.image.length)if(0<b.version&&n.__version!==
b.version){n.__image__webglTextureCube||(b.addEventListener("dispose",u),n.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+m);c.bindTexture(a.TEXTURE_CUBE_MAP,n.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var p=b&&b.isCompressedTexture,l=b.image[0]&&b.image[0].isDataTexture,t=[],x=0;6>x;x++)t[x]=p||l?l?b.image[x].image:b.image[x]:h(b.image[x],e.maxCubemapSize);var q=k(t[0]),z=f(b.format),C=f(b.type);r(a.TEXTURE_CUBE_MAP,b,q);for(x=
0;6>x;x++)if(p)for(var U,na=t[x].mipmaps,E=0,B=na.length;E<B;E++)U=na[E],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(z)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,E,z,U.width,U.height,0,U.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,E,z,U.width,U.height,0,z,C,U.data);else l?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,0,z,t[x].width,t[x].height,
0,z,C,t[x].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+x,0,z,z,C,t[x]);b.generateMipmaps&&q&&a.generateMipmap(a.TEXTURE_CUBE_MAP);n.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+m),c.bindTexture(a.TEXTURE_CUBE_MAP,n.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",
p);f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,m=k(b);if(h){e.__webglFramebuffer=[];for(var u=0;6>u;u++)e.__webglFramebuffer[u]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);r(a.TEXTURE_CUBE_MAP,b.texture,m);for(u=0;6>u;u++)l(e.__webglFramebuffer[u],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+u);b.texture.generateMipmaps&&m&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,
null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),r(a.TEXTURE_2D,b.texture,m),l(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),b.texture.generateMipmaps&&m&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,
e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);n(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,
a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),t(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),t(e.__webglDepthbuffer,
b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture;e.generateMipmaps&&k(b)&&1003!==e.minFilter&&1006!==e.minFilter&&(b=b&&b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function Sf(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function Tf(a,b,c){function d(b,
c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==y[b]&&(a.enable(b),y[b]=!0)}function f(b){!1!==y[b]&&(a.disable(b),y[b]=!1)}function g(b,d,g,h,k,m,n,u){0!==b?e(a.BLEND):f(a.BLEND);if(b!==v||u!==U)2===b?u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,
a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR)):4===b?u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR)):u?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),
a.blendFuncSeparate(a.ONE,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)),v=b,U=u;if(5===b){k=k||d;m=m||g;n=n||h;if(d!==F||k!==H)a.blendEquationSeparate(c(d),c(k)),F=d,H=k;if(g!==G||h!==A||m!==ba||n!==C)a.blendFuncSeparate(c(g),c(h),c(m),c(n)),G=g,A=h,ba=m,C=n}else C=ba=H=A=G=F=null}function h(b){E!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),E=b)}function k(b){0!==
b?(e(a.CULL_FACE),b!==B&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);B=b}function m(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),P!==c||K!==d)a.polygonOffset(c,d),P=c,K=d}else f(a.POLYGON_OFFSET_FILL)}function u(b){void 0===b&&(b=a.TEXTURE0+S-1);V!==b&&(a.activeTexture(b),V=b)}var p=new function(){var b=!1,c=new ga,d=null,e=new ga;return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},setClear:function(b,d,f,g,
h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(0,0,0,1)}}},n=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);
break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=null,d=null,g=null,h=null,k=null,m=null,n=null,u=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,
c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(k!==b||m!==c||n!==d)a.stencilOp(b,c,d),k=b,m=c,n=d},setLocked:function(a){b=a},setClear:function(b){u!==b&&(a.clearStencil(b),u=b)},reset:function(){b=!1;u=n=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=new Uint8Array(l),q=new Uint8Array(l),w=new Uint8Array(l),y={},M=null,v=null,F=null,G=null,A=null,H=null,ba=null,C=null,U=!1,E=null,B=null,I=null,P=null,K=null,L=null,S=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),
l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),J=1<=parseFloat(l),V=null,Q={},O=new ga,R=new ga,N={};N[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);N[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:p,depth:n,stencil:r},init:function(){p.setClear(0,0,0,1);n.setClear(1);r.setClear(0);e(a.DEPTH_TEST);n.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=t.length;a<b;a++)t[a]=0},enableAttribute:function(c){t[c]=
1;0===q[c]&&(a.enableVertexAttribArray(c),q[c]=1);0!==w[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),w[c]=0)},enableAttributeAndDivisor:function(b,c,d){t[b]=1;0===q[b]&&(a.enableVertexAttribArray(b),q[b]=1);w[b]!==c&&(d.vertexAttribDivisorANGLE(b,c),w[b]=c)},disableUnusedAttributes:function(){for(var b=0,c=q.length;b!==c;++b)q[b]!==t[b]&&(a.disableVertexAttribArray(b),q[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===M&&(M=[],b.get("WEBGL_compressed_texture_pvrtc")||
b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)M.push(c[d]);return M},setBlending:g,setMaterial:function(b){2===b.side?f(a.CULL_FACE):e(a.CULL_FACE);h(1===b.side);!0===b.transparent?g(b.blending,b.blendEquation,b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);n.setFunc(b.depthFunc);n.setTest(b.depthTest);n.setMask(b.depthWrite);p.setMask(b.colorWrite);
m(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==I&&(J&&a.lineWidth(b),I=b)},setPolygonOffset:m,getScissorTest:function(){return L},setScissorTest:function(b){(L=b)?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:u,bindTexture:function(b,c){null===V&&u();var d=Q[V];void 0===d&&(d={type:void 0,texture:void 0},Q[V]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||N[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,
arguments)}catch(b){console.error(b)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(b){console.error(b)}},scissor:function(b){!1===O.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),O.copy(b))},viewport:function(b){!1===R.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),R.copy(b))},reset:function(){for(var b=0;b<q.length;b++)1===q[b]&&(a.disableVertexAttribArray(b),q[b]=0);y={};V=M=null;Q={};B=E=v=null;p.reset();n.reset();r.reset()}}}function Uf(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,
a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=!0===c.logarithmicDepthBuffer&&!!b.get("EXT_frag_depth");
var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),u=a.getParameter(a.MAX_VERTEX_ATTRIBS),p=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),n=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,t=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=
null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:m,maxAttributes:u,maxVertexUniforms:p,maxVaryings:n,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:t,floatVertexTextures:l&&t}}function Vf(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];var d;switch(c){case "WEBGL_depth_texture":d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||
a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||
a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Wf(){function a(){m.value!==d&&(m.value=d,m.needsUpdate=0<e);c.numPlanes=e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=m.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;
k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new ia,k=new Ba,m={value:null,needsUpdate:!1};this.uniform=m;this.numIntersection=this.numPlanes=0;this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=
!1;a()};this.setState=function(c,h,k,l,x,t){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var q=4*k,w=x.clippingState||null;m.value=w;w=b(c,l,q,t);for(c=0;c!==q;++c)w[c]=d[c];x.clippingState=w;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Vd(a){function b(){aa.init();aa.scissor(W.copy(ea).multiplyScalar(Va));aa.viewport(yc.copy(fa).multiplyScalar(Va));aa.buffers.color.setClear(Ma.r,Ma.g,Ma.b,jb,A)}function c(){T=S=null;O="";N=-1;aa.reset()}function d(a){a.preventDefault();
c();b();ia.clear();Aa.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ia.remove(a)}function f(a){var b=ia.get(a).program;a.program=void 0;void 0!==b&&Ba.releaseProgram(b)}function g(a,b,c){a.render(function(a){L.renderBufferImmediate(a,b,c)})}function h(a,b){return Math.abs(b[0])-Math.abs(a[0])}function k(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-b.object.renderOrder:a.material.program&&b.material.program&&a.material.program!==b.material.program?
a.material.program.id-b.material.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function m(a,b){return a.object.renderOrder!==b.object.renderOrder?a.object.renderOrder-b.object.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function u(a,b,c,d,e){var f;c.transparent?(d=B,f=++R):(d=E,f=++U);(f=d[f])?(f.id=a.id,f.object=a,f.geometry=b,f.material=c,f.z=da.z,f.group=e):(f={id:a.id,object:a,geometry:b,material:c,z:da.z,group:e},d.push(f))}function p(a,b,c){if(a.visible){if(a.layers.test(b.layers))if(a.isLight)C.push(a);
else if(a.isSprite)a.frustumCulled&&!ka.intersectsSprite(a)||P.push(a);else if(a.isLensFlare)K.push(a);else if(a.isImmediateRenderObject)c&&da.setFromMatrixPosition(a.matrixWorld).applyMatrix4(pa),u(a,null,a.material,da.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||ka.intersectsObject(a)){c&&da.setFromMatrixPosition(a.matrixWorld).applyMatrix4(pa);var d=Aa.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var k=
f[g],m=e[k.materialIndex];m&&m.visible&&u(a,d,m,da.z,k)}else e.visible&&u(a,d,e,da.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)p(a[g],b,c)}}function n(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var h=a[e],k=h.object,m=h.geometry,n=void 0===d?h.material:d,h=h.group;k.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,k.matrixWorld);k.normalMatrix.getNormalMatrix(k.modelViewMatrix);k.onBeforeRender(L,b,c,m,n,h);if(k.isImmediateRenderObject){aa.setMaterial(n);var u=l(c,b.fog,n,k);O="";g(k,u,n)}else L.renderBufferDirect(c,
b.fog,m,n,k,h);k.onAfterRender(L,b,c,m,n,h)}}function l(a,b,c,d){Y=0;var g=ia.get(c);oa&&(ra||a!==T)&&ca.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,g,a===T&&c.id===N);!1===c.needsUpdate&&(void 0===g.program?c.needsUpdate=!0:c.fog&&g.fog!==b?c.needsUpdate=!0:c.lights&&g.lightsHash!==Z.hash?c.needsUpdate=!0:void 0===g.numClippingPlanes||g.numClippingPlanes===ca.numPlanes&&g.numIntersection===ca.numIntersection||(c.needsUpdate=!0));if(c.needsUpdate){a:{var h=ia.get(c),k=Ba.getParameters(c,
Z,b,ca.numPlanes,ca.numIntersection,d),m=Ba.getProgramCode(c,k),n=h.program,u=!0;if(void 0===n)c.addEventListener("dispose",e);else if(n.code!==m)f(c);else if(void 0!==k.shaderID)break a;else u=!1;u&&(k.shaderID?(n=$a[k.shaderID],h.__webglShader={name:c.type,uniforms:Ja.clone(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader}):h.__webglShader={name:c.type,uniforms:c.uniforms,vertexShader:c.vertexShader,fragmentShader:c.fragmentShader},c.__webglShader=h.__webglShader,n=Ba.acquireProgram(c,
k,m),h.program=n,c.program=n);k=n.getAttributes();if(c.morphTargets)for(m=c.numSupportedMorphTargets=0;m<L.maxMorphTargets;m++)0<=k["morphTarget"+m]&&c.numSupportedMorphTargets++;if(c.morphNormals)for(m=c.numSupportedMorphNormals=0;m<L.maxMorphNormals;m++)0<=k["morphNormal"+m]&&c.numSupportedMorphNormals++;k=h.__webglShader.uniforms;if(!c.isShaderMaterial&&!c.isRawShaderMaterial||!0===c.clipping)h.numClippingPlanes=ca.numPlanes,h.numIntersection=ca.numIntersection,k.clippingPlanes=ca.uniform;h.fog=
b;h.lightsHash=Z.hash;c.lights&&(k.ambientLightColor.value=Z.ambient,k.directionalLights.value=Z.directional,k.spotLights.value=Z.spot,k.rectAreaLights.value=Z.rectArea,k.pointLights.value=Z.point,k.hemisphereLights.value=Z.hemi,k.directionalShadowMap.value=Z.directionalShadowMap,k.directionalShadowMatrix.value=Z.directionalShadowMatrix,k.spotShadowMap.value=Z.spotShadowMap,k.spotShadowMatrix.value=Z.spotShadowMatrix,k.pointShadowMap.value=Z.pointShadowMap,k.pointShadowMatrix.value=Z.pointShadowMatrix);
m=h.program.getUniforms();k=Ya.seqWithValue(m.seq,k);h.uniformsList=k}c.needsUpdate=!1}var p=!1,u=n=!1,h=g.program,k=h.getUniforms(),m=g.__webglShader.uniforms;h.id!==S&&(D.useProgram(h.program),S=h.id,u=n=p=!0);c.id!==N&&(N=c.id,n=!0);if(p||a!==T){k.set(D,a,"projectionMatrix");la.logarithmicDepthBuffer&&k.setValue(D,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));a!==T&&(T=a,u=n=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)p=k.map.cameraPosition,void 0!==p&&
p.setValue(D,da.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||d.isSkinnedMesh)&&k.setValue(D,"viewMatrix",a.matrixWorldInverse);k.set(D,L,"toneMappingExposure");k.set(D,L,"toneMappingWhitePoint")}d.isSkinnedMesh&&(k.setOptional(D,d,"bindMatrix"),k.setOptional(D,d,"bindMatrixInverse"),a=d.skeleton)&&(la.floatVertexTextures?(k.set(D,a,"boneTexture"),k.set(D,a,"boneTextureSize")):k.setOptional(D,
a,"boneMatrices"));if(n){c.lights&&(a=u,m.ambientLightColor.needsUpdate=a,m.directionalLights.needsUpdate=a,m.pointLights.needsUpdate=a,m.spotLights.needsUpdate=a,m.rectAreaLights.needsUpdate=a,m.hemisphereLights.needsUpdate=a);b&&c.fog&&(m.fogColor.value=b.color,b.isFog?(m.fogNear.value=b.near,m.fogFar.value=b.far):b.isFogExp2&&(m.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){m.opacity.value=
c.opacity;m.diffuse.value=c.color;c.emissive&&m.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);m.map.value=c.map;m.specularMap.value=c.specularMap;m.alphaMap.value=c.alphaMap;c.lightMap&&(m.lightMap.value=c.lightMap,m.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(m.aoMap.value=c.aoMap,m.aoMapIntensity.value=c.aoMapIntensity);var r;c.map?r=c.map:c.specularMap?r=c.specularMap:c.displacementMap?r=c.displacementMap:c.normalMap?r=c.normalMap:c.bumpMap?r=c.bumpMap:c.roughnessMap?
r=c.roughnessMap:c.metalnessMap?r=c.metalnessMap:c.alphaMap?r=c.alphaMap:c.emissiveMap&&(r=c.emissiveMap);void 0!==r&&(r.isWebGLRenderTarget&&(r=r.texture),b=r.offset,r=r.repeat,m.offsetRepeat.value.set(b.x,b.y,r.x,r.y));m.envMap.value=c.envMap;m.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;m.reflectivity.value=c.reflectivity;m.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity):c.isLineDashedMaterial?(m.diffuse.value=c.color,
m.opacity.value=c.opacity,m.dashSize.value=c.dashSize,m.totalSize.value=c.dashSize+c.gapSize,m.scale.value=c.scale):c.isPointsMaterial?(m.diffuse.value=c.color,m.opacity.value=c.opacity,m.size.value=c.size*Va,m.scale.value=.5*zc,m.map.value=c.map,null!==c.map&&(r=c.map.offset,c=c.map.repeat,m.offsetRepeat.value.set(r.x,r.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(m.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(x(m,c),c.gradientMap&&(m.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?
x(m,c):c.isMeshPhysicalMaterial?(m.clearCoat.value=c.clearCoat,m.clearCoatRoughness.value=c.clearCoatRoughness,t(m,c)):c.isMeshStandardMaterial?t(m,c):c.isMeshDepthMaterial?c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,m.displacementBias.value=c.displacementBias):c.isMeshNormalMaterial&&(c.bumpMap&&(m.bumpMap.value=c.bumpMap,m.bumpScale.value=c.bumpScale),c.normalMap&&(m.normalMap.value=c.normalMap,m.normalScale.value.copy(c.normalScale)),
c.displacementMap&&(m.displacementMap.value=c.displacementMap,m.displacementScale.value=c.displacementScale,m.displacementBias.value=c.displacementBias));void 0!==m.ltcMat&&(m.ltcMat.value=THREE.UniformsLib.LTC_MAT_TEXTURE);void 0!==m.ltcMag&&(m.ltcMag.value=THREE.UniformsLib.LTC_MAG_TEXTURE);Ya.upload(D,g.uniformsList,m,L)}k.set(D,d,"modelViewMatrix");k.set(D,d,"normalMatrix");k.setValue(D,"modelMatrix",d.matrixWorld);return h}function x(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,
1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function t(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&
(a.metalnessMap.value=b.metalnessMap);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function z(a){var b;if(1E3===a)return D.REPEAT;if(1001===
a)return D.CLAMP_TO_EDGE;if(1002===a)return D.MIRRORED_REPEAT;if(1003===a)return D.NEAREST;if(1004===a)return D.NEAREST_MIPMAP_NEAREST;if(1005===a)return D.NEAREST_MIPMAP_LINEAR;if(1006===a)return D.LINEAR;if(1007===a)return D.LINEAR_MIPMAP_NEAREST;if(1008===a)return D.LINEAR_MIPMAP_LINEAR;if(1009===a)return D.UNSIGNED_BYTE;if(1017===a)return D.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return D.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return D.UNSIGNED_SHORT_5_6_5;if(1010===a)return D.BYTE;if(1011===a)return D.SHORT;
if(1012===a)return D.UNSIGNED_SHORT;if(1013===a)return D.INT;if(1014===a)return D.UNSIGNED_INT;if(1015===a)return D.FLOAT;if(1016===a&&(b=ja.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return D.ALPHA;if(1022===a)return D.RGB;if(1023===a)return D.RGBA;if(1024===a)return D.LUMINANCE;if(1025===a)return D.LUMINANCE_ALPHA;if(1026===a)return D.DEPTH_COMPONENT;if(1027===a)return D.DEPTH_STENCIL;if(100===a)return D.FUNC_ADD;if(101===a)return D.FUNC_SUBTRACT;if(102===a)return D.FUNC_REVERSE_SUBTRACT;
if(200===a)return D.ZERO;if(201===a)return D.ONE;if(202===a)return D.SRC_COLOR;if(203===a)return D.ONE_MINUS_SRC_COLOR;if(204===a)return D.SRC_ALPHA;if(205===a)return D.ONE_MINUS_SRC_ALPHA;if(206===a)return D.DST_ALPHA;if(207===a)return D.ONE_MINUS_DST_ALPHA;if(208===a)return D.DST_COLOR;if(209===a)return D.ONE_MINUS_DST_COLOR;if(210===a)return D.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ja.get("WEBGL_compressed_texture_s3tc"),null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;
if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ja.get("WEBGL_compressed_texture_pvrtc"),null!==b){if(2100===a)return b.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===a)return b.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===a)return b.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===a)return b.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===a&&(b=ja.get("WEBGL_compressed_texture_etc1"),
null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ja.get("EXT_blend_minmax"),null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ja.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","85dev");a=a||{};var w=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),y=void 0!==a.context?a.context:null,M=void 0!==a.alpha?a.alpha:!1,v=void 0!==a.depth?a.depth:!0,F=void 0!==
a.stencil?a.stencil:!0,G=void 0!==a.antialias?a.antialias:!1,A=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,H=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,C=[],E=[],U=-1,B=[],R=-1,Ta=new Float32Array(8),P=[],K=[];this.domElement=w;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=
!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var L=this,S=null,qa=null,V=null,N=-1,O="",T=null,W=new ga,X=null,yc=new ga,Y=0,Ma=new J(0),jb=0,kd=w.width,zc=w.height,Va=1,ea=new ga(0,0,kd,zc),ha=!1,fa=new ga(0,0,kd,zc),ka=new jd,ca=new Wf,oa=!1,ra=!1,pa=new Q,da=new q,xa=new Q,va=new Q,Z={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],
point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},za={geometries:0,textures:0},ma={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:ma,memory:za,programs:null};var D;try{M={alpha:M,depth:v,stencil:F,antialias:G,premultipliedAlpha:A,preserveDrawingBuffer:H};D=y||w.getContext("webgl",M)||w.getContext("experimental-webgl",M);if(null===D){if(null!==w.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";throw"Error creating WebGL context.";
}void 0===D.getShaderPrecisionFormat&&(D.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});w.addEventListener("webglcontextlost",d,!1)}catch(Xf){console.error("THREE.WebGLRenderer: "+Xf)}var ja=new Vf(D);ja.get("WEBGL_depth_texture");ja.get("OES_texture_float");ja.get("OES_texture_float_linear");ja.get("OES_texture_half_float");ja.get("OES_texture_half_float_linear");ja.get("OES_standard_derivatives");ja.get("ANGLE_instanced_arrays");ja.get("OES_element_index_uint")&&
(I.MaxIndex=4294967296);var la=new Uf(D,ja,a),aa=new Tf(D,ja,z),ia=new Sf,ua=new Rf(D,ja,aa,ia,la,z,za),Da=new Df(D),Ia=new Gf(D,Da,za),Aa=new If(D,Ia,ma),Ba=new Qf(this,la),Ca=new Hf;this.info.programs=Ba.programs;var Oa=new Ff(D,ja,ma),Pa=new Ef(D,ja,ma),Ha,ya,sa,ta;b();this.context=D;this.capabilities=la;this.extensions=ja;this.properties=ia;this.state=aa;var Ra=new De(this,Z,Aa,la);this.shadowMap=Ra;var Sa=new zf(this,P),Ua=new yf(this,K);this.getContext=function(){return D};this.getContextAttributes=
function(){return D.getContextAttributes()};this.forceContextLoss=function(){ja.get("WEBGL_lose_context").loseContext()};this.getMaxAnisotropy=function(){return la.getMaxAnisotropy()};this.getPrecision=function(){return la.precision};this.getPixelRatio=function(){return Va};this.setPixelRatio=function(a){void 0!==a&&(Va=a,this.setSize(fa.z,fa.w,!1))};this.getSize=function(){return{width:kd,height:zc}};this.setSize=function(a,b,c){kd=a;zc=b;w.width=a*Va;w.height=b*Va;!1!==c&&(w.style.width=a+"px",
w.style.height=b+"px");this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){aa.viewport(fa.set(a,b,c,d))};this.setScissor=function(a,b,c,d){aa.scissor(ea.set(a,b,c,d))};this.setScissorTest=function(a){aa.setScissorTest(ha=a)};this.getClearColor=function(){return Ma};this.setClearColor=function(a,b){Ma.set(a);jb=void 0!==b?b:1;aa.buffers.color.setClear(Ma.r,Ma.g,Ma.b,jb,A)};this.getClearAlpha=function(){return jb};this.setClearAlpha=function(a){jb=a;aa.buffers.color.setClear(Ma.r,Ma.g,Ma.b,
jb,A)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=D.COLOR_BUFFER_BIT;if(void 0===b||b)d|=D.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=D.STENCIL_BUFFER_BIT;D.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.resetGLState=c;this.dispose=function(){B=[];R=-1;E=[];U=-1;w.removeEventListener("webglcontextlost",
d,!1)};this.renderBufferImmediate=function(a,b,c){aa.initAttributes();var d=ia.get(a);a.hasPositions&&!d.position&&(d.position=D.createBuffer());a.hasNormals&&!d.normal&&(d.normal=D.createBuffer());a.hasUvs&&!d.uv&&(d.uv=D.createBuffer());a.hasColors&&!d.color&&(d.color=D.createBuffer());b=b.getAttributes();a.hasPositions&&(D.bindBuffer(D.ARRAY_BUFFER,d.position),D.bufferData(D.ARRAY_BUFFER,a.positionArray,D.DYNAMIC_DRAW),aa.enableAttribute(b.position),D.vertexAttribPointer(b.position,3,D.FLOAT,!1,
0,0));if(a.hasNormals){D.bindBuffer(D.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&1===c.shading)for(var e=0,f=3*a.count;e<f;e+=9){var g=a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,k=(g[e+1]+g[e+4]+g[e+7])/3,m=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=k;g[e+2]=m;g[e+3]=h;g[e+4]=k;g[e+5]=m;g[e+6]=h;g[e+7]=k;g[e+8]=m}D.bufferData(D.ARRAY_BUFFER,a.normalArray,D.DYNAMIC_DRAW);aa.enableAttribute(b.normal);D.vertexAttribPointer(b.normal,3,D.FLOAT,!1,
0,0)}a.hasUvs&&c.map&&(D.bindBuffer(D.ARRAY_BUFFER,d.uv),D.bufferData(D.ARRAY_BUFFER,a.uvArray,D.DYNAMIC_DRAW),aa.enableAttribute(b.uv),D.vertexAttribPointer(Da.uv,2,D.FLOAT,!1,0,0));a.hasColors&&0!==c.vertexColors&&(D.bindBuffer(D.ARRAY_BUFFER,d.color),D.bufferData(D.ARRAY_BUFFER,a.colorArray,D.DYNAMIC_DRAW),aa.enableAttribute(b.color),D.vertexAttribPointer(b.color,3,D.FLOAT,!1,0,0));aa.disableUnusedAttributes();D.drawArrays(D.TRIANGLES,0,a.count);a.count=0};var Ka,Qa,Na;this.renderBufferDirect=
function(a,b,c,d,e,f){aa.setMaterial(d);Ka=l(a,b,d,e);Qa=c.id+"_"+Ka.id+"_"+d.wireframe;Na=!1;Qa!==O&&(O=Qa,Na=!0);var g=e.morphTargetInfluences;if(void 0!==g){var k=[];a=0;for(var m=g.length;a<m;a++)b=g[a],k.push([b,a]);k.sort(h);8<k.length&&(k.length=8);g=c.morphAttributes;a=0;for(m=k.length;a<m;a++)b=k[a],Ta[a]=b[0],0!==b[0]?(b=b[1],!0===d.morphTargets&&g.position&&c.addAttribute("morphTarget"+a,g.position[b]),!0===d.morphNormals&&g.normal&&c.addAttribute("morphNormal"+a,g.normal[b])):(!0===d.morphTargets&&
c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=k.length;for(b=Ta.length;a<b;a++)Ta[a]=0;Ka.getUniforms().setValue(D,"morphTargetInfluences",Ta);Na=!0}b=c.index;m=c.attributes.position;k=1;!0===d.wireframe&&(b=Ia.getWireframeAttribute(c),k=2);a=Oa;null!==b&&(a=Pa,a.setIndex(b));if(Na){a:{var n=Ka,g=void 0,u;if(c&&c.isInstancedBufferGeometry&&(u=ja.get("ANGLE_instanced_arrays"),null===u)){console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
break a}void 0===g&&(g=0);aa.initAttributes();var p=c.attributes,n=n.getAttributes(),t=d.defaultAttributeValues,x;for(x in n){var q=n[x];if(0<=q){var v=p[x];if(void 0!==v){var y=v.normalized,w=v.itemSize,z=Da.get(v),A=z.buffer,M=z.type,z=z.bytesPerElement;if(v.isInterleavedBufferAttribute){var G=v.data,H=G.stride,v=v.offset;G&&G.isInstancedInterleavedBuffer?(aa.enableAttributeAndDivisor(q,G.meshPerAttribute,u),void 0===c.maxInstancedCount&&(c.maxInstancedCount=G.meshPerAttribute*G.count)):aa.enableAttribute(q);
D.bindBuffer(D.ARRAY_BUFFER,A);D.vertexAttribPointer(q,w,M,y,H*z,(g*H+v)*z)}else v.isInstancedBufferAttribute?(aa.enableAttributeAndDivisor(q,v.meshPerAttribute,u),void 0===c.maxInstancedCount&&(c.maxInstancedCount=v.meshPerAttribute*v.count)):aa.enableAttribute(q),D.bindBuffer(D.ARRAY_BUFFER,A),D.vertexAttribPointer(q,w,M,y,0,g*w*z)}else if(void 0!==t&&(y=t[x],void 0!==y))switch(y.length){case 2:D.vertexAttrib2fv(q,y);break;case 3:D.vertexAttrib3fv(q,y);break;case 4:D.vertexAttrib4fv(q,y);break;
default:D.vertexAttrib1fv(q,y)}}}aa.disableUnusedAttributes()}null!==b&&D.bindBuffer(D.ELEMENT_ARRAY_BUFFER,Da.get(b).buffer)}u=0;null!==b?u=b.count:void 0!==m&&(u=m.count);b=c.drawRange.start*k;m=null!==f?f.start*k:0;x=Math.max(b,m);f=Math.max(0,Math.min(u,b+c.drawRange.count*k,m+(null!==f?f.count*k:Infinity))-1-x+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)aa.setLineWidth(d.wireframeLinewidth*(null===qa?Va:1)),a.setMode(D.LINES);else switch(e.drawMode){case 0:a.setMode(D.TRIANGLES);break;case 1:a.setMode(D.TRIANGLE_STRIP);
break;case 2:a.setMode(D.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),aa.setLineWidth(d*(null===qa?Va:1)),e.isLineSegments?a.setMode(D.LINES):e.isLineLoop?a.setMode(D.LINE_LOOP):a.setMode(D.LINE_STRIP)):e.isPoints&&a.setMode(D.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,x,f):a.render(x,f)}};this.render=function(a,b,c,d){if(void 0!==b&&!0!==b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else{O=
"";N=-1;T=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();b.matrixWorldInverse.getInverse(b.matrixWorld);pa.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);ka.setFromMatrix(pa);C.length=0;R=U=-1;P.length=0;K.length=0;ra=this.localClippingEnabled;oa=ca.init(this.clippingPlanes,ra,b);p(a,b,L.sortObjects);E.length=U+1;B.length=R+1;!0===L.sortObjects&&(E.sort(k),B.sort(m));oa&&ca.beginShadows();for(var e=C,f=0,g=0,h=e.length;g<h;g++){var u=e[g];u.castShadow&&
(Z.shadows[f]=u,f++)}Z.shadows.length=f;Ra.render(a,b);for(var e=C,r,l=u=0,t=0,x,q,v,y=b.matrixWorldInverse,z=0,w=0,M=0,G=0,H=0,f=0,g=e.length;f<g;f++)if(h=e[f],r=h.color,x=h.intensity,q=h.distance,v=h.shadow&&h.shadow.map?h.shadow.map.texture:null,h.isAmbientLight)u+=r.r*x,l+=r.g*x,t+=r.b*x;else if(h.isDirectionalLight){var F=Ca.get(h);F.color.copy(h.color).multiplyScalar(h.intensity);F.direction.setFromMatrixPosition(h.matrixWorld);da.setFromMatrixPosition(h.target.matrixWorld);F.direction.sub(da);
F.direction.transformDirection(y);if(F.shadow=h.castShadow)r=h.shadow,F.shadowBias=r.bias,F.shadowRadius=r.radius,F.shadowMapSize=r.mapSize;Z.directionalShadowMap[z]=v;Z.directionalShadowMatrix[z]=h.shadow.matrix;Z.directional[z]=F;z++}else if(h.isSpotLight){F=Ca.get(h);F.position.setFromMatrixPosition(h.matrixWorld);F.position.applyMatrix4(y);F.color.copy(r).multiplyScalar(x);F.distance=q;F.direction.setFromMatrixPosition(h.matrixWorld);da.setFromMatrixPosition(h.target.matrixWorld);F.direction.sub(da);
F.direction.transformDirection(y);F.coneCos=Math.cos(h.angle);F.penumbraCos=Math.cos(h.angle*(1-h.penumbra));F.decay=0===h.distance?0:h.decay;if(F.shadow=h.castShadow)r=h.shadow,F.shadowBias=r.bias,F.shadowRadius=r.radius,F.shadowMapSize=r.mapSize;Z.spotShadowMap[M]=v;Z.spotShadowMatrix[M]=h.shadow.matrix;Z.spot[M]=F;M++}else if(h.isRectAreaLight)F=Ca.get(h),F.color.copy(r).multiplyScalar(x/(h.width*h.height)),F.position.setFromMatrixPosition(h.matrixWorld),F.position.applyMatrix4(y),va.identity(),
xa.copy(h.matrixWorld),xa.premultiply(y),va.extractRotation(xa),F.halfWidth.set(.5*h.width,0,0),F.halfHeight.set(0,.5*h.height,0),F.halfWidth.applyMatrix4(va),F.halfHeight.applyMatrix4(va),Z.rectArea[G]=F,G++;else if(h.isPointLight){F=Ca.get(h);F.position.setFromMatrixPosition(h.matrixWorld);F.position.applyMatrix4(y);F.color.copy(h.color).multiplyScalar(h.intensity);F.distance=h.distance;F.decay=0===h.distance?0:h.decay;if(F.shadow=h.castShadow)r=h.shadow,F.shadowBias=r.bias,F.shadowRadius=r.radius,
F.shadowMapSize=r.mapSize;Z.pointShadowMap[w]=v;void 0===Z.pointShadowMatrix[w]&&(Z.pointShadowMatrix[w]=new Q);da.setFromMatrixPosition(h.matrixWorld).negate();Z.pointShadowMatrix[w].identity().setPosition(da);Z.point[w]=F;w++}else h.isHemisphereLight&&(F=Ca.get(h),F.direction.setFromMatrixPosition(h.matrixWorld),F.direction.transformDirection(y),F.direction.normalize(),F.skyColor.copy(h.color).multiplyScalar(x),F.groundColor.copy(h.groundColor).multiplyScalar(x),Z.hemi[H]=F,H++);Z.ambient[0]=u;
Z.ambient[1]=l;Z.ambient[2]=t;Z.directional.length=z;Z.spot.length=M;Z.rectArea.length=G;Z.point.length=w;Z.hemi.length=H;Z.hash=z+","+w+","+M+","+G+","+H+","+Z.shadows.length;oa&&ca.endShadows();ma.frame++;ma.calls=0;ma.vertices=0;ma.faces=0;ma.points=0;void 0===c&&(c=null);this.setRenderTarget(c);e=a.background;null===e?aa.buffers.color.setClear(Ma.r,Ma.g,Ma.b,jb,A):e&&e.isColor&&(aa.buffers.color.setClear(e.r,e.g,e.b,1,A),d=!0);(this.autoClear||d)&&this.clear(this.autoClearColor,this.autoClearDepth,
this.autoClearStencil);e&&e.isCubeTexture?(void 0===sa&&(sa=new Ea,ta=new wa(new hb(5,5,5),new Ga({uniforms:$a.cube.uniforms,vertexShader:$a.cube.vertexShader,fragmentShader:$a.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}))),sa.projectionMatrix.copy(b.projectionMatrix),sa.matrixWorld.extractRotation(b.matrixWorld),sa.matrixWorldInverse.getInverse(sa.matrixWorld),ta.material.uniforms.tCube.value=e,ta.modelViewMatrix.multiplyMatrices(sa.matrixWorldInverse,ta.matrixWorld),Aa.update(ta),
L.renderBufferDirect(sa,null,ta.geometry,ta.material,ta,null)):e&&e.isTexture&&(void 0===Ha&&(Ha=new Gb(-1,1,1,-1,0,1),ya=new wa(new ib(2,2),new La({depthTest:!1,depthWrite:!1,fog:!1}))),ya.material.map=e,Aa.update(ya),L.renderBufferDirect(Ha,null,ya.geometry,ya.material,ya,null));a.overrideMaterial?(d=a.overrideMaterial,n(E,a,b,d),n(B,a,b,d)):(aa.setBlending(0),n(E,a,b),n(B,a,b));Sa.render(a,b);Ua.render(a,b,yc);c&&ua.updateRenderTargetMipmap(c);aa.buffers.depth.setTest(!0);aa.buffers.depth.setMask(!0);
aa.buffers.color.setMask(!0)}};this.setFaceCulling=function(a,b){aa.setCullFace(a);aa.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=Y;a>=la.maxTextures&&console.warn("WebGLRenderer: trying to use "+a+" texture units while this GPU supports only "+la.maxTextures);Y+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),
a=!0),b=b.texture);ua.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);ua.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&
6===b.image.length?ua.setTextureCube(b,c):ua.setTextureCubeDynamic(b,c)}}();this.getCurrentRenderTarget=function(){return qa};this.setRenderTarget=function(a){(qa=a)&&void 0===ia.get(a).__webglFramebuffer&&ua.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,c;a?(c=ia.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,W.copy(a.scissor),X=a.scissorTest,yc.copy(a.viewport)):(c=null,W.copy(ea).multiplyScalar(Va),X=ha,yc.copy(fa).multiplyScalar(Va));V!==c&&(D.bindFramebuffer(D.FRAMEBUFFER,
c),V=c);aa.scissor(W);aa.setScissorTest(X);aa.viewport(yc);b&&(b=ia.get(a.texture),D.framebufferTexture2D(D.FRAMEBUFFER,D.COLOR_ATTACHMENT0,D.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!1===(a&&a.isWebGLRenderTarget))console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");else{var g=ia.get(a).__webglFramebuffer;if(g){var h=!1;g!==V&&(D.bindFramebuffer(D.FRAMEBUFFER,
g),h=!0);try{var k=a.texture,m=k.format,n=k.type;1023!==m&&z(m)!==D.getParameter(D.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||z(n)===D.getParameter(D.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ja.get("OES_texture_float")||ja.get("WEBGL_color_buffer_float"))||1016===n&&ja.get("EXT_color_buffer_half_float")?D.checkFramebufferStatus(D.FRAMEBUFFER)===D.FRAMEBUFFER_COMPLETE?0<=b&&
b<=a.width-d&&0<=c&&c<=a.height-e&&D.readPixels(b,c,d,e,z(m),z(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&D.bindFramebuffer(D.FRAMEBUFFER,V)}}}}}function Hb(a,b){this.name="";this.color=new J(a);this.density=void 0!==b?b:2.5E-4}function Ib(a,b,c){this.name="";this.color=
new J(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function ld(){E.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Wd(a,b,c,d,e){E.call(this);this.lensFlares=[];this.positionScreen=new q;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function bb(a){X.call(this);this.type="SpriteMaterial";this.color=new J(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function Ac(a){E.call(this);
this.type="Sprite";this.material=void 0!==a?a:new bb}function Bc(){E.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Cc(a,b){this.identityMatrix=new Q;a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else{console.warn("THREE.Skeleton boneInverses is the wrong length.");this.boneInverses=[];for(var c=0,d=this.bones.length;c<
d;c++)this.boneInverses.push(new Q)}}function md(){E.call(this);this.type="Bone"}function nd(a,b){wa.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new Q;this.bindMatrixInverse=new Q;var c=[];if(this.geometry&&void 0!==this.geometry.bones){for(var d,e,f=0,g=this.geometry.bones.length;f<g;++f)e=this.geometry.bones[f],d=new md,c.push(d),d.name=e.name,d.position.fromArray(e.pos),d.quaternion.fromArray(e.rotq),void 0!==e.scl&&d.scale.fromArray(e.scl);f=0;for(g=this.geometry.bones.length;f<
g;++f)e=this.geometry.bones[f],-1!==e.parent&&null!==e.parent&&void 0!==c[e.parent]?c[e.parent].add(c[f]):this.add(c[f])}this.normalizeSkinWeights();this.updateMatrixWorld(!0);this.bind(new Cc(c),this.matrixWorld)}function ka(a){X.call(this);this.type="LineBasicMaterial";this.color=new J(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;this.setValues(a)}function Ca(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),
new ha(a,b);E.call(this);this.type="Line";this.geometry=void 0!==a?a:new I;this.material=void 0!==b?b:new ka({color:16777215*Math.random()})}function ha(a,b){Ca.call(this,a,b);this.type="LineSegments"}function od(a,b){Ca.call(this,a,b);this.type="LineLoop"}function Oa(a){X.call(this);this.type="PointsMaterial";this.color=new J(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Jb(a,b){E.call(this);this.type="Points";this.geometry=void 0!==a?a:new I;
this.material=void 0!==b?b:new Oa({color:16777215*Math.random()})}function Dc(){E.call(this);this.type="Group"}function pd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(u.needsUpdate=!0)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var u=this;m()}function Kb(a,b,c,d,e,f,g,h,k,m,u,p){ea.call(this,null,f,g,h,k,m,d,e,u,p);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function qd(a,b,c,d,e,f,g,h,k){ea.call(this,
a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Ec(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);ea.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Lb(a){function b(a,b){return a-b}I.call(this);this.type=
"WireframeGeometry";var c=[],d,e,f,g,h=[0,0],k={},m,u=["a","b","c"];if(a&&a.isGeometry){var p=a.faces;d=0;for(f=p.length;d<f;d++){var n=p[d];for(e=0;3>e;e++)h[0]=n[u[e]],h[1]=n[u[(e+1)%3]],h.sort(b),m=h.toString(),void 0===k[m]&&(k[m]={index1:h[0],index2:h[1]})}for(m in k)d=k[m],u=a.vertices[d.index1],c.push(u.x,u.y,u.z),u=a.vertices[d.index2],c.push(u.x,u.y,u.z)}else if(a&&a.isBufferGeometry){var r,u=new q;if(null!==a.index){p=a.attributes.position;n=a.index;r=a.groups;0===r.length&&(r=[{start:0,
count:n.count,materialIndex:0}]);a=0;for(g=r.length;a<g;++a)for(d=r[a],e=d.start,f=d.count,d=e,f=e+f;d<f;d+=3)for(e=0;3>e;e++)h[0]=n.getX(d+e),h[1]=n.getX(d+(e+1)%3),h.sort(b),m=h.toString(),void 0===k[m]&&(k[m]={index1:h[0],index2:h[1]});for(m in k)d=k[m],u.fromBufferAttribute(p,d.index1),c.push(u.x,u.y,u.z),u.fromBufferAttribute(p,d.index2),c.push(u.x,u.y,u.z)}else for(p=a.attributes.position,d=0,f=p.count/3;d<f;d++)for(e=0;3>e;e++)k=3*d+e,u.fromBufferAttribute(p,k),c.push(u.x,u.y,u.z),k=3*d+(e+
1)%3,u.fromBufferAttribute(p,k),c.push(u.x,u.y,u.z)}this.addAttribute("position",new B(c,3))}function Fc(a,b,c){R.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Mb(a,b,c));this.mergeVertices()}function Mb(a,b,c){I.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g,h,k=b+1;for(g=0;g<=c;g++){var m=g/c;for(h=0;h<=b;h++){var u=h/b,p=a(u,m);e.push(p.x,p.y,p.z);f.push(u,m)}}for(g=
0;g<c;g++)for(h=0;h<b;h++)a=g*k+h+1,m=(g+1)*k+h+1,u=(g+1)*k+h,d.push(g*k+h,a,u),d.push(a,m,u);this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("uv",new B(f,2));this.computeVertexNormals()}function Gc(a,b,c,d){R.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new xa(a,b,c,d));this.mergeVertices()}function xa(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){var d=3*b;c.x=a[d+0];c.y=a[d+1];
c.z=a[d+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}I.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;var h=[],k=[];(function(a){for(var c=new q,d=new q,g=new q,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k=c,l=d,z=g,w=Math.pow(2,a),y=[],M,v;for(M=0;M<=w;M++){y[M]=[];var F=k.clone().lerp(z,M/w),G=l.clone().lerp(z,M/w),A=w-M;for(v=0;v<=A;v++)y[M][v]=0===v&&M===w?F:F.clone().lerp(G,
v/A)}for(M=0;M<w;M++)for(v=0;v<2*(w-M)-1;v++)k=Math.floor(v/2),0===v%2?(e(y[M][k+1]),e(y[M+1][k]),e(y[M][k])):(e(y[M][k+1]),e(y[M+1][k+1]),e(y[M+1][k]))}})(d||0);(function(a){for(var b=new q,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new q,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=
new q,b=new q,c=new q,d=new q,e=new C,f=new C,l=new C,z=0,w=0;z<h.length;z+=9,w+=6){a.set(h[z+0],h[z+1],h[z+2]);b.set(h[z+3],h[z+4],h[z+5]);c.set(h[z+6],h[z+7],h[z+8]);e.set(k[w+0],k[w+1]);f.set(k[w+2],k[w+3]);l.set(k[w+4],k[w+5]);d.copy(a).add(b).add(c).divideScalar(3);var y=Math.atan2(d.z,-d.x);g(e,w+0,a,y);g(f,w+2,b,y);g(l,w+4,c,y)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",
new B(h,3));this.addAttribute("normal",new B(h.slice(),3));this.addAttribute("uv",new B(k,2));this.normalizeNormals()}function Hc(a,b){R.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Nb(a,b));this.mergeVertices()}function Nb(a,b){xa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ic(a,b){R.call(this);this.type="OctahedronGeometry";
this.parameters={radius:a,detail:b};this.fromBufferGeometry(new kb(a,b));this.mergeVertices()}function kb(a,b){xa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Jc(a,b){R.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Ob(a,b){var c=(1+Math.sqrt(5))/2;xa.call(this,
[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[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],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b){R.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;
xa.call(this,[-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,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[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],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}
function Lc(a,b,c,d,e,f){R.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Qb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Qb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(p=0;p<=d;p++){var u=p/d*Math.PI*2,l=Math.sin(u),
u=-Math.cos(u);k.x=u*m.x+l*e.x;k.y=u*m.y+l*e.y;k.z=u*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;n.push(h.x,h.y,h.z)}}I.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new q,k=new q,m=new C,u,p,n=[],r=[],l=[],t=[];for(u=0;u<b;u++)f(u);f(!1===e?
b:0);for(u=0;u<=b;u++)for(p=0;p<=d;p++)m.x=u/b,m.y=p/d,l.push(m.x,m.y);(function(){for(p=1;p<=b;p++)for(u=1;u<=d;u++){var a=(d+1)*p+(u-1),c=(d+1)*p+u,e=(d+1)*(p-1)+u;t.push((d+1)*(p-1)+(u-1),a,e);t.push(a,c,e)}})();this.setIndex(t);this.addAttribute("position",new B(n,3));this.addAttribute("normal",new B(r,3));this.addAttribute("uv",new B(l,2))}function Mc(a,b,c,d,e,f,g){R.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==
g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");this.fromBufferGeometry(new Rb(a,b,c,d,e,f));this.mergeVertices()}function Rb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}I.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||
8;e=e||2;f=f||3;var h=[],k=[],m=[],u=[],p,n,l=new q,x=new q;new C;var t=new q,z=new q,w=new q,y=new q,M=new q;for(p=0;p<=c;++p)for(n=p/c*e*Math.PI*2,g(n,e,f,a,t),g(n+.01,e,f,a,z),y.subVectors(z,t),M.addVectors(z,t),w.crossVectors(y,M),M.crossVectors(w,y),w.normalize(),M.normalize(),n=0;n<=d;++n){var v=n/d*Math.PI*2,F=-b*Math.cos(v),v=b*Math.sin(v);l.x=t.x+(F*M.x+v*w.x);l.y=t.y+(F*M.y+v*w.y);l.z=t.z+(F*M.z+v*w.z);k.push(l.x,l.y,l.z);x.subVectors(l,t).normalize();m.push(x.x,x.y,x.z);u.push(p/c);u.push(n/
d)}for(n=1;n<=c;n++)for(p=1;p<=d;p++)a=(d+1)*n+(p-1),b=(d+1)*n+p,e=(d+1)*(n-1)+p,h.push((d+1)*(n-1)+(p-1),a,e),h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new B(k,3));this.addAttribute("normal",new B(m,3));this.addAttribute("uv",new B(u,2))}function Nc(a,b,c,d,e){R.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Sb(a,b,c,d,e))}function Sb(a,b,c,d,e){I.call(this);this.type="TorusBufferGeometry";
this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new q,u=new q,p=new q,n,l;for(n=0;n<=c;n++)for(l=0;l<=d;l++){var x=l/d*e,t=n/c*Math.PI*2;u.x=(a+b*Math.cos(t))*Math.cos(x);u.y=(a+b*Math.cos(t))*Math.sin(x);u.z=b*Math.sin(t);g.push(u.x,u.y,u.z);m.x=a*Math.cos(x);m.y=a*Math.sin(x);p.subVectors(u,m).normalize();h.push(p.x,p.y,p.z);k.push(l/d);k.push(n/c)}for(n=1;n<=c;n++)for(l=1;l<=
d;l++)a=(d+1)*(n-1)+l-1,b=(d+1)*(n-1)+l,e=(d+1)*n+l,f.push((d+1)*n+l-1,a,e),f.push(a,b,e);this.setIndex(f);this.addAttribute("position",new B(g,3));this.addAttribute("normal",new B(h,3));this.addAttribute("uv",new B(k,2))}function Da(a,b){"undefined"!==typeof a&&(R.call(this),this.type="ExtrudeGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeFaceNormals())}function Oc(a,b){b=b||{};var c=b.font;if(!1===(c&&c.isFont))return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),
new R;c=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);Da.call(this,c,b);this.type="TextGeometry"}function Pc(a,b,c,d,e,f,g){R.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new lb(a,b,c,d,e,f,g))}function lb(a,
b,c,d,e,f,g){I.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,m,u=0,p=[],n=new q,l=new q,x=[],t=[],z=[],w=[];for(m=0;m<=c;m++){var y=[],M=m/c;for(k=0;k<=b;k++){var v=k/b;n.x=-a*Math.cos(d+v*e)*Math.sin(f+M*g);n.y=a*Math.cos(f+M*g);
n.z=a*Math.sin(d+v*e)*Math.sin(f+M*g);t.push(n.x,n.y,n.z);l.set(n.x,n.y,n.z).normalize();z.push(l.x,l.y,l.z);w.push(v,1-M);y.push(u++)}p.push(y)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=p[m][k+1],d=p[m][k],e=p[m+1][k],g=p[m+1][k+1],(0!==m||0<f)&&x.push(a,d,g),(m!==c-1||h<Math.PI)&&x.push(d,e,g);this.setIndex(x);this.addAttribute("position",new B(t,3));this.addAttribute("normal",new B(z,3));this.addAttribute("uv",new B(w,2))}function Qc(a,b,c,d,e,f){R.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,
outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Tb(a,b,c,d,e,f))}function Tb(a,b,c,d,e,f){I.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||20;b=b||50;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],m=[],u=a,p=(b-a)/d,n=new q,l=new C,x,t;for(x=0;x<=d;x++){for(t=0;t<=c;t++)a=e+
t/c*f,n.x=u*Math.cos(a),n.y=u*Math.sin(a),h.push(n.x,n.y,n.z),k.push(0,0,1),l.x=(n.x/b+1)/2,l.y=(n.y/b+1)/2,m.push(l.x,l.y);u+=p}for(x=0;x<d;x++)for(b=x*(c+1),t=0;t<c;t++)a=t+b,e=a+c+1,f=a+c+2,u=a+1,g.push(a,e,u),g.push(e,f,u);this.setIndex(g);this.addAttribute("position",new B(h,3));this.addAttribute("normal",new B(k,3));this.addAttribute("uv",new B(m,2))}function Rc(a,b,c,d){R.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Ub(a,
b,c,d));this.mergeVertices()}function Ub(a,b,c,d){I.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=T.clamp(d,0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new q,m=new C,u,p;for(u=0;u<=b;u++){p=c+u*h*d;var n=Math.sin(p),l=Math.cos(p);for(p=0;p<=a.length-1;p++)k.x=a[p].x*n,k.y=a[p].y,k.z=a[p].x*l,f.push(k.x,k.y,k.z),m.x=u/b,m.y=p/(a.length-1),g.push(m.x,m.y)}for(u=0;u<b;u++)for(p=0;p<a.length-1;p++)c=p+u*
a.length,h=c+a.length,k=c+a.length+1,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new B(f,3));this.addAttribute("uv",new B(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=this.attributes.normal.array,e=new q,f=new q,g=new q,c=b*a.length*3,p=u=0;u<a.length;u++,p+=3)e.x=d[p+0],e.y=d[p+1],e.z=d[p+2],f.x=d[c+p+0],f.y=d[c+p+1],f.z=d[c+p+2],g.addVectors(e,f).normalize(),d[p+0]=d[c+p+0]=g.x,d[p+1]=d[c+p+1]=g.y,d[p+2]=d[c+p+2]=g.z}function Vb(a,b){R.call(this);
this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){function c(a){var c,h,m=e.length/3;a=a.extractPoints(b);var l=a.shape,t=a.holes;if(!1===Pa.isClockWise(l))for(l=l.reverse(),a=0,c=t.length;a<c;a++)h=t[a],!0===Pa.isClockWise(h)&&(t[a]=h.reverse());var q=Pa.triangulateShape(l,t);a=0;for(c=t.length;a<
c;a++)h=t[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],e.push(h.x,h.y,0),f.push(0,0,1),g.push(h.x,h.y);a=0;for(c=q.length;a<c;a++)l=q[a],d.push(l[0]+m,l[1]+m,l[2]+m),k+=3}I.call(this);this.type="ShapeBufferGeometry";this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("normal",new B(f,3));
this.addAttribute("uv",new B(g,2))}function Xb(a,b){function c(a,b){return a-b}I.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var d=[],e=Math.cos(T.DEG2RAD*(void 0!==b?b:1)),f=[0,0],g={},h,k=["a","b","c"],m;a.isBufferGeometry?(m=new R,m.fromBufferGeometry(a)):m=a.clone();m.mergeVertices();m.computeFaceNormals();var u=m.vertices;m=m.faces;for(var l=0,n=m.length;l<n;l++)for(var r=m[l],x=0;3>x;x++)f[0]=r[k[x]],f[1]=r[k[(x+1)%3]],f.sort(c),h=f.toString(),void 0===g[h]?g[h]=
{index1:f[0],index2:f[1],face1:l,face2:void 0}:g[h].face2=l;for(h in g)if(f=g[h],void 0===f.face2||m[f.face1].normal.dot(m[f.face2].normal)<=e)k=u[f.index1],d.push(k.x,k.y,k.z),k=u[f.index2],d.push(k.x,k.y,k.z);this.addAttribute("position",new B(d,3))}function mb(a,b,c,d,e,f,g,h){R.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Qa(a,b,c,d,e,f,g,h));this.mergeVertices()}
function Qa(a,b,c,d,e,f,g,h){function k(c){var e,f,k,t=new C,A=new q,H=0,ba=!0===c?a:b,E=!0===c?1:-1;f=x;for(e=1;e<=d;e++)l.push(0,z*E,0),n.push(0,E,0),r.push(.5,.5),x++;k=x;for(e=0;e<=d;e++){var U=e/d*h+g,B=Math.cos(U),U=Math.sin(U);A.x=ba*U;A.y=z*E;A.z=ba*B;l.push(A.x,A.y,A.z);n.push(0,E,0);t.x=.5*B+.5;t.y=.5*U*E+.5;r.push(t.x,t.y);x++}for(e=0;e<d;e++)t=f+e,A=k+e,!0===c?u.push(A,A+1,t):u.push(A+1,A,t),H+=3;m.addGroup(w,H,!0===c?1:2);w+=H}I.call(this);this.type="CylinderBufferGeometry";this.parameters=
{radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var u=[],l=[],n=[],r=[],x=0,t=[],z=c/2,w=0;(function(){var f,k,v=new q,F=new q,G=0,A=(b-a)/c;for(k=0;k<=e;k++){var H=[],C=k/e,E=C*(b-a)+a;for(f=0;f<=d;f++){var U=f/d,B=U*h+g,I=Math.sin(B),B=Math.cos(B);F.x=E*I;F.y=-C*c+z;F.z=E*
B;l.push(F.x,F.y,F.z);v.set(I,A,B).normalize();n.push(v.x,v.y,v.z);r.push(U,1-C);H.push(x++)}t.push(H)}for(f=0;f<d;f++)for(k=0;k<e;k++)v=t[k+1][f],F=t[k+1][f+1],A=t[k][f+1],u.push(t[k][f],v,A),u.push(v,F,A),G+=6;m.addGroup(w,G,0);w+=G})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(u);this.addAttribute("position",new B(l,3));this.addAttribute("normal",new B(n,3));this.addAttribute("uv",new B(r,2))}function Sc(a,b,c,d,e,f,g){mb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters=
{radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Tc(a,b,c,d,e,f,g){Qa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Uc(a,b,c,d){R.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new Yb(a,b,c,d))}function Yb(a,b,c,d){I.call(this);this.type=
"CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||50;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=[],g=[],h=[],k,m,u=new q,l=new C;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);m=0;for(k=3;m<=b;m++,k+=3){var n=c+m/b*d;u.x=a*Math.cos(n);u.y=a*Math.sin(n);f.push(u.x,u.y,u.z);g.push(0,0,1);l.x=(f[k]/a+1)/2;l.y=(f[k+1]/a+1)/2;h.push(l.x,l.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new B(f,
3));this.addAttribute("normal",new B(g,3));this.addAttribute("uv",new B(h,2))}function Zb(){Ga.call(this,{uniforms:Ja.merge([N.lights,{opacity:{value:1}}]),vertexShader:Y.shadow_vert,fragmentShader:Y.shadow_frag});this.transparent=this.lights=!0;Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(a){this.uniforms.opacity.value=a}}})}function $b(a){Ga.call(this,a);this.type="RawShaderMaterial"}function Ra(a){X.call(this);this.defines=
{STANDARD:""};this.type="MeshStandardMaterial";this.color=new J(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new J(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=
1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=!1;this.setValues(a)}function nb(a){Ra.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ha(a){X.call(this);this.type="MeshPhongMaterial";this.color=new J(16777215);this.specular=new J(1118481);this.shininess=30;this.lightMap=this.map=
null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new J(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=
this.morphTargets=!1;this.setValues(a)}function ob(a){Ha.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function pb(a){X.call(this,a);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.lights=this.fog=!1;this.setValues(a)}
function qb(a){X.call(this);this.type="MeshLambertMaterial";this.color=new J(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new J(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=!1;this.setValues(a)}
function rb(a){X.call(this);this.type="LineDashedMaterial";this.color=new J(16777215);this.scale=this.linewidth=1;this.dashSize=3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Xd(a,b,c){var d=this,e=!1,f=0,g=0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=
function(a){if(void 0!==d.onError)d.onError(a)}}function ya(a){this.manager=void 0!==a?a:ma}function Je(a){this.manager=void 0!==a?a:ma;this._parser=null}function Yd(a){this.manager=void 0!==a?a:ma;this._parser=null}function Vc(a){this.manager=void 0!==a?a:ma}function Zd(a){this.manager=void 0!==a?a:ma}function rd(a){this.manager=void 0!==a?a:ma}function fa(a,b){E.call(this);this.type="Light";this.color=new J(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function sd(a,b,c){fa.call(this,
a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(E.DefaultUp);this.updateMatrix();this.groundColor=new J(b)}function sb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new Q}function td(){sb.call(this,new Ea(50,1,.5,500))}function ud(a,b,c,d,e,f){fa.call(this,a,b);this.type="SpotLight";this.position.copy(E.DefaultUp);this.updateMatrix();this.target=new E;Object.defineProperty(this,"power",{get:function(){return this.intensity*
Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new td}function vd(a,b,c,d){fa.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new sb(new Ea(90,1,.5,500))}function wd(){sb.call(this,
new Gb(-5,5,5,-5,.5,500))}function xd(a,b){fa.call(this,a,b);this.type="DirectionalLight";this.position.copy(E.DefaultUp);this.updateMatrix();this.target=new E;this.shadow=new wd}function yd(a,b){fa.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function zd(a,b,c,d){fa.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function la(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=
void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Ad(a,b,c,d){la.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Wc(a,b,c,d){la.call(this,a,b,c,d)}function Bd(a,b,c,d){la.call(this,a,b,c,d)}function tb(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=ra.convertArray(b,this.TimeBufferType);this.values=ra.convertArray(c,
this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function ac(a,b,c,d){tb.call(this,a,b,c,d)}function Cd(a,b,c,d){la.call(this,a,b,c,d)}function Xc(a,b,c,d){tb.call(this,a,b,c,d)}function bc(a,b,c,d){tb.call(this,a,b,c,d)}function Dd(a,b,c,d){tb.call(this,a,b,c,d)}function Ed(a,b,c){tb.call(this,a,b,c)}function Fd(a,b,c,d){tb.call(this,a,b,c,d)}function ub(a,b,c,d){tb.apply(this,arguments)}function Ia(a,b,c){this.name=a;this.tracks=c;this.duration=
void 0!==b?b:-1;this.uuid=T.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Gd(a){this.manager=void 0!==a?a:ma;this.textures={}}function $d(a){this.manager=void 0!==a?a:ma}function cc(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function ae(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:ma;this.withCredentials=!1}
function Ke(a){this.manager=void 0!==a?a:ma;this.texturePath=""}function Le(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function vb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function wb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function va(){}function Sa(a,b){this.v1=a;this.v2=b}function Yc(){this.curves=[];this.autoClose=!1}function Na(a,b,c,d,e,f,g,h){this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=
e;this.aEndAngle=f;this.aClockwise=g;this.aRotation=h||0}function xb(a){this.points=void 0===a?[]:a}function dc(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d}function ec(a,b,c){this.v0=a;this.v1=b;this.v2=c}function Zc(a){Yc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function yb(){Zc.apply(this,arguments);this.holes=[]}function be(){this.subPaths=[];this.currentPath=null}function ce(a){this.data=a}function Me(a){this.manager=void 0!==a?a:ma}function de(a){this.manager=void 0!==a?
a:ma}function Ne(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Ea;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Ea;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function Hd(a,b,c){E.call(this);this.type="CubeCamera";var d=new Ea(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new q(1,0,0));this.add(d);var e=new Ea(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new q(-1,0,0));this.add(e);var f=new Ea(90,1,a,b);f.up.set(0,0,1);f.lookAt(new q(0,
1,0));this.add(f);var g=new Ea(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new q(0,-1,0));this.add(g);var h=new Ea(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new q(0,0,1));this.add(h);var k=new Ea(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new q(0,0,-1));this.add(k);this.renderTarget=new Cb(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,n=c.texture.generateMipmaps;c.texture.generateMipmaps=
!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=n;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function ee(){E.call(this);this.type="AudioListener";this.context=fe.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function fc(a){E.call(this);this.type="Audio";this.context=
a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function ge(a){fc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function he(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);
a.getOutput().connect(this.analyser)}function ie(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Oe(a,b,c){c=c||pa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function pa(a,b,c){this.path=b;this.parsedPath=c||pa.parseTrackName(b);
this.node=pa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Pe(a){this.uuid=T.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}
function Qe(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=
this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Re(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Id(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function zb(){I.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function je(a,b,c,d){this.uuid=T.generateUUID();
this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function gc(a,b){this.uuid=T.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function hc(a,b,c){gc.call(this,a,b);this.meshPerAttribute=c||1}function ic(a,b,c){W.call(this,a,b);this.meshPerAttribute=c||1}function Se(a,b,c,d){this.ray=new eb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},
LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function Te(a,b){return a.distance-b.distance}function ke(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)ke(a[d],b,c,!0)}}function Ue(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function Ve(a,
b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function We(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function oa(a,b){wa.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function $c(a){E.call(this);this.material=a;this.render=function(a){}}function ad(a,b,c,d){this.object=
a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new I;b=new B(6*b,3);c.addAttribute("position",b);ha.call(this,c,new ka({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function jc(a){E.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new I;for(var b=[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],c=0,d=1;32>c;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new B(b,3));b=new ka({fog:!1});this.cone=new ha(a,b);this.add(this.cone);this.update()}function kc(a){this.bones=this.getBoneList(a);for(var b=new I,c=[],d=[],e=new J(0,0,1),f=new J(0,1,0),g=0;g<this.bones.length;g++){var h=this.bones[g];h.parent&&h.parent.isBone&&(c.push(0,0,0),c.push(0,0,0),d.push(e.r,e.g,e.b),d.push(f.r,f.g,f.b))}b.addAttribute("position",
new B(c,3));b.addAttribute("color",new B(d,3));c=new ka({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});ha.call(this,b,c);this.root=a;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function lc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new lb(b,4,2),d=new La({wireframe:!0,fog:!1});d.color.copy(this.light.color).multiplyScalar(this.light.intensity);wa.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1}function mc(a){E.call(this);this.light=
a;this.light.updateMatrixWorld();var b=new La({color:a.color,fog:!1});a=new La({color:a.color,fog:!1,wireframe:!0});var c=new I;c.addAttribute("position",new W(new Float32Array(18),3));this.add(new wa(c,b));this.add(new wa(c,a));this.update()}function nc(a,b){E.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=new kb(b);c.rotateY(.5*Math.PI);var d=new La({vertexColors:2,wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);
c.addAttribute("color",new W(e,3));this.add(new wa(c,d));this.update()}function bd(a,b,c,d){a=a||10;b=b||10;c=new J(void 0!==c?c:4473924);d=new J(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,m=0,u=-g;k<=b;k++,u+=f){a.push(-g,0,u,g,0,u);a.push(u,0,-g,u,0,g);var l=k===e?c:d;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3}b=new I;b.addAttribute("position",new B(a,3));b.addAttribute("color",new B(h,3));c=new ka({vertexColors:2});ha.call(this,b,c)}function Jd(a,
b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new J(void 0!==e?e:4473924);f=new J(void 0!==f?f:8947848);var g=[],h=[],k,m,u,l,n;for(u=0;u<=b;u++)m=u/b*2*Math.PI,k=Math.sin(m)*a,m=Math.cos(m)*a,g.push(0,0,0),g.push(k,0,m),n=u&1?e:f,h.push(n.r,n.g,n.b),h.push(n.r,n.g,n.b);for(u=0;u<=c;u++)for(n=u&1?e:f,l=a-a/c*u,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(n.r,n.g,n.b);a=new I;a.addAttribute("position",
new B(g,3));a.addAttribute("color",new B(h,3));g=new ka({vertexColors:2});ha.call(this,a,g)}function cd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new I;b=new B(6*b,3);c.addAttribute("position",b);ha.call(this,c,new ka({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}
function oc(a,b){E.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new I;c.addAttribute("position",new B([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ka({fog:!1});this.add(new Ca(c,d));c=new I;c.addAttribute("position",new B([0,0,0,0,0,1],3));this.add(new Ca(c,d));this.update()}function dd(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/
3-1)}var d=new I,e=new ka({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new J(16755200),m=new J(16711680),u=new J(43775),l=new J(16777215),n=new J(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p","n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",u);b("u2","u3",u);b("u3","u1",u);b("c","t",l);b("p","c",n);b("cn1","cn2",n);b("cn3","cn4",n);
b("cf1","cf2",n);b("cf3","cf4",n);d.addAttribute("position",new B(f,3));d.addAttribute("color",new B(g,3));ha.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function pc(a,b){void 0===b&&(b=16776960);var c=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]),d=new Float32Array(24),e=new I;e.setIndex(new W(c,1));e.addAttribute("position",new W(d,3));ha.call(this,
e,new ka({color:b}));void 0!==a&&this.update(a)}function Ab(a,b,c,d,e,f){E.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Kd&&(Kd=new I,Kd.addAttribute("position",new B([0,0,0,0,1,0],3)),le=new Qa(0,.5,1,5,1),le.translate(0,-.5,0));this.position.copy(b);this.line=new Ca(Kd,new ka({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new wa(le,new La({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);
this.setLength(c,e,f)}function Ld(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new I;a.addAttribute("position",new B(b,3));a.addAttribute("color",new B([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ka({vertexColors:2});ha.call(this,a,b)}function me(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*(h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,m,u){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+u)+(h-g)/
u)*m;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function sa(a){this.points=a||[];this.closed=!1}function ed(a,b,c,d){this.v0=a;this.v1=b;this.v2=c;this.v3=d}function fd(a,b,c){this.v0=a;this.v1=b;this.v2=c}function gd(a,b){this.v1=a;this.v2=b}function Md(a,b,c,d,e,f){Na.call(this,a,b,c,c,d,e,f)}function Xe(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");sa.call(this,a);this.type="catmullrom";this.closed=
!0}function Ye(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");sa.call(this,a);this.type="catmullrom"}function ne(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");sa.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});
void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(za.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},
hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,1)}}},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;var c=[],d,e=b.length;for(d=0;d<e;d++)c[d]=b[d];for(d=0;d<e;d++)c[d].call(this,a)}}}});var T={DEG2RAD:Math.PI/
180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-
b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*T.DEG2RAD},radToDeg:function(a){return a*T.RAD2DEG},
isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=
this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,
b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),
this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=
Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){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);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.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)},lengthManhattan:function(){return Math.abs(this.x)+
Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length())},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=
(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);
return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}});var Ze=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;Object.defineProperty(ea.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ea.prototype,za.prototype,{constructor:ea,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);
this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.4,
type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=T.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml",
"canvas"),g.width=c.width,g.height=c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=
1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(ga.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},
setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,
this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors: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;return this},
addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;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;return this},multiplyScalar:function(a){this.x*=
a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/
b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781):
(c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,
a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a=new ga,b=new ga;return function(c,d){a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),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);return this},
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);return this},round: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},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},
negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length())},
setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=
[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Bb.prototype,za.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,
0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Cb.prototype=Object.create(Bb.prototype);Cb.prototype.constructor=Cb;Cb.prototype.isWebGLRenderTargetCube=!0;Object.assign(ca,{slerp:function(a,b,
c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var u=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==u||m!==l){f=1-g;var n=h*d+k*u+m*l+c*e,r=0<=n?1:-1,x=1-n*n;x>Number.EPSILON&&(x=Math.sqrt(x),n=Math.atan2(x,n*r),f=Math.sin(f*n)/x,g=Math.sin(g*n)/x);r*=g;h=h*f+d*r;k=k*f+u*r;m=m*f+l*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(ca.prototype,{x:{get:function(){return this._x},
set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(ca.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,
this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!1===(a&&a.isEuler))throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z,f=a.order,g=Math.cos,h=Math.sin,k=g(c/2),m=g(d/2),g=g(e/2),c=h(c/2),d=h(d/2),e=h(e/2);"XYZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"YXZ"===f?(this._x=c*m*g+
k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"ZXY"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"ZYX"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"YZX"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g-c*d*e):"XZY"===f&&(this._x=c*m*g-k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,
b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0<m?(c=.5/Math.sqrt(m+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=
.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new q,b;return function(c,d){void 0===a&&(a=new q);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=
-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},
multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();
return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*
k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=
a;return this},onChangeCallback:function(){}});Object.assign(q.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;
case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},
addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=
a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new ca;return function(b){!1===(b&&b.isEuler)&&console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");
return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new ca;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12];this.y=a[1]*b+a[5]*c+a[9]*d+a[13];this.z=a[2]*b+a[6]*c+a[10]*d+a[14];
return this.divideScalar(a[3]*b+a[7]*c+a[11]*d+a[15])},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new Q;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new Q;return function(b){a.multiplyMatrices(b.matrixWorld,
a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=
Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new q,b=new q;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.multiplyScalar(Math.max(a,Math.min(b,c))/c)},floor:function(){this.x=Math.floor(this.x);
this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;
this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.multiplyScalar(a/this.length())},lerp:function(a,b){this.x+=(a.x-this.x)*
b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=
e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new q;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new q;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(T.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},
distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){return this.setFromMatrixColumn(a,
3)},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=
this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(Q.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,u,l,n,r,x,t){var q=this.elements;q[0]=a;q[4]=b;q[8]=c;q[12]=d;q[1]=e;q[5]=f;q[9]=g;q[13]=h;q[2]=k;q[6]=m;q[10]=u;q[14]=l;q[3]=n;q[7]=r;q[11]=x;q[15]=t;return this},identity:function(){this.set(1,
0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new Q).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)b[c]=a[c];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,
b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new q;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){!1===(a&&a.isEuler)&&console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");
var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,u=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-u*d;b[9]=-c*g;b[2]=u-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,u=d*e,b[0]=a+u*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=u+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,u=d*e,b[0]=a-u*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=u-a*c,b[2]=
-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,u=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+u,b[1]=g*e,b[5]=u*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,u=c*d,b[0]=g*h,b[4]=u-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-u*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,u=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+u,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=u*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=
this.elements,c=a.x,d=a.y,e=a.z,f=a.w,g=c+c,h=d+d,k=e+e;a=c*g;var m=c*h,c=c*k,u=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(u+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+u);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new q,b=new q,c=new q;return function(d,e,f){var g=this.elements;c.subVectors(d,e).normalize();0===c.lengthSq()&&(c.z=1);a.crossVectors(f,c).normalize();0===a.lengthSq()&&(c.z+=1E-4,a.crossVectors(f,c).normalize());
b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=
c[1],u=c[5],l=c[9],n=c[13],r=c[2],q=c[6],t=c[10],z=c[14],w=c[3],y=c[7],M=c[11],c=c[15],v=d[0],F=d[4],G=d[8],A=d[12],H=d[1],C=d[5],E=d[9],U=d[13],B=d[2],I=d[6],J=d[10],P=d[14],K=d[3],L=d[7],S=d[11],d=d[15];e[0]=f*v+g*H+h*B+k*K;e[4]=f*F+g*C+h*I+k*L;e[8]=f*G+g*E+h*J+k*S;e[12]=f*A+g*U+h*P+k*d;e[1]=m*v+u*H+l*B+n*K;e[5]=m*F+u*C+l*I+n*L;e[9]=m*G+u*E+l*J+n*S;e[13]=m*A+u*U+l*P+n*d;e[2]=r*v+q*H+t*B+z*K;e[6]=r*F+q*C+t*I+z*L;e[10]=r*G+q*E+t*J+z*S;e[14]=r*A+q*U+t*P+z*d;e[3]=w*v+y*H+M*B+c*K;e[7]=w*F+y*C+M*I+c*
L;e[11]=w*G+y*E+M*J+c*S;e[15]=w*A+y*U+M*P+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new q;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=this.elements,b=a[0],c=a[4],
d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],k=a[13],m=a[2],l=a[6],p=a[10],n=a[14];return a[3]*(+e*h*l-d*k*l-e*g*p+c*k*p+d*g*n-c*h*n)+a[7]*(+b*h*n-b*k*p+e*f*p-d*f*n+d*k*m-e*h*m)+a[11]*(+b*k*l-b*g*n-e*f*l+c*f*n+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*l+b*g*p+d*f*l-c*f*p+c*h*m)},transpose:function(){var a=this.elements,b;b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=this.elements;
b[12]=a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[1],g=d[2],h=d[3],k=d[4],m=d[5],l=d[6],p=d[7],n=d[8],r=d[9],q=d[10],t=d[11],z=d[12],w=d[13],y=d[14],d=d[15],M=r*y*p-w*q*p+w*l*t-m*y*t-r*l*d+m*q*d,v=z*q*p-n*y*p-z*l*t+k*y*t+n*l*d-k*q*d,F=n*w*p-z*r*p+z*m*t-k*w*t-n*m*d+k*r*d,G=z*r*l-n*w*l-z*m*q+k*w*q+n*m*y-k*r*y,A=e*M+f*v+g*F+h*G;if(0===A){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");
return this.identity()}A=1/A;c[0]=M*A;c[1]=(w*q*h-r*y*h-w*g*t+f*y*t+r*g*d-f*q*d)*A;c[2]=(m*y*h-w*l*h+w*g*p-f*y*p-m*g*d+f*l*d)*A;c[3]=(r*l*h-m*q*h-r*g*p+f*q*p+m*g*t-f*l*t)*A;c[4]=v*A;c[5]=(n*y*h-z*q*h+z*g*t-e*y*t-n*g*d+e*q*d)*A;c[6]=(z*l*h-k*y*h-z*g*p+e*y*p+k*g*d-e*l*d)*A;c[7]=(k*q*h-n*l*h+n*g*p-e*q*p-k*g*t+e*l*t)*A;c[8]=F*A;c[9]=(z*r*h-n*w*h-z*f*t+e*w*t+n*f*d-e*r*d)*A;c[10]=(k*w*h-z*m*h+z*f*p-e*w*p-k*f*d+e*m*d)*A;c[11]=(n*m*h-k*r*h-n*f*p+e*r*p+k*f*t-e*m*t)*A;c[12]=G*A;c[13]=(n*w*g-z*r*g+z*f*q-e*w*
q-n*f*y+e*r*y)*A;c[14]=(z*m*g-k*w*g-z*f*l+e*w*l+k*f*y-e*m*y)*A;c[15]=(k*r*g-n*m*g+n*f*l-e*r*l-k*f*q+e*m*q)*A;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,
0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*
g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new q,b=new Q;return function(c,d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),
k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];for(c=0;16>c;c++)b.elements[c]=this.elements[c];c=1/g;var f=1/h,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");
var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;
a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});Xa.prototype=Object.create(ea.prototype);
Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var xe=new ea,ye=new Xa,se=[],ue=[],we=new Float32Array(16),ve=new Float32Array(9);Ce.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Pd=/([\w\d_]+)(\])?(\[|\.)?/g;Ya.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};Ya.prototype.set=
function(a,b,c){var d=this.map[c];void 0!==d&&d.setValue(a,b[c],this.renderer)};Ya.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};Ya.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};Ya.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var Ja={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=
d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},Y={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",
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( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",
begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\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}\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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, 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_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, 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\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\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\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\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",
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 = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\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\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n",
clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n",
clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n",
color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",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#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(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}\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};\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 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n",
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(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\n",
defaultnormal_vertex:"#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",
emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",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.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\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.w );\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.w );\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.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, 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.x, 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 = value.rgb * cLogLuvM;\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 = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n",
envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, 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, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * 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\n",
envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n",
envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\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\n",
fog_vertex:"\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n varying float fogDepth;\n#endif\n",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\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\n",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\n",
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\n",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",
lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\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\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\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\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",
lights_pars:"uniform vec3 ambientLightColor;\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};\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 ltcMat;\tuniform sampler2D ltcMag;\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\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\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( 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 blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, 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(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 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\n",
lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",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};\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n\t}\n#endif\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_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",
lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n",
lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#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 matDiffColor = material.diffuseColor;\n\t\tvec3 matSpecColor = material.specularColor;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 spec = Rect_Area_Light_Specular_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n\t\t\t\troughness,\n\t\t\t\tltcMat, ltcMag );\n\t\tvec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n\t\t\t\tgeometry,\n\t\t\t\trectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n\t\treflectedLight.directSpecular += lightColor * matSpecColor * spec;\n\t\treflectedLight.directDiffuse += lightColor * matDiffColor * diff;\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#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\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 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\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\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}\n",
lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 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\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? 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\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? 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\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 irradiance = getAmbientLightIrradiance( ambientLightColor );\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 ( NUM_HEMI_LIGHTS > 0 )\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\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
logdepthbuf_fragment:"#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n",
map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n",
metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",
morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n",
normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",normal_fragment:"#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 ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n",
packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\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}\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}\n",
premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",
roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\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 ) / size;\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\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\treturn (\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( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, 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( 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 / 9.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\treturn (\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#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\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\n",
shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n",
shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",
shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
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",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform 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\n",
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\tskinned = bindMatrixInverse * skinned;\n#endif\n",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#endif\n",
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",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#define saturate(a) clamp( a, 0.0, 1.0 )\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}\n",
uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n",
uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",
uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
cube_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
depth_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",
distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n",
equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n",
meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\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 <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
meshbasic_vert:"#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n",
meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\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 <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\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 <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",
shadow_frag:"uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n"},Yf={aliceblue:15792383,antiquewhite:16444375,
aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,
darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,
indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,
maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,
papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,
white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(J.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,
c,d){0>d&&(d+=1);1<d&&--d;return d<1/6?a+6*(c-a)*d:.5>d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=T.euclideanModulo(b,1);c=T.clamp(c,0,1);d=T.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];
switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=
/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+
c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&(c=Yf[a],void 0!==c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);var c=
0<b?1/b:1;this.r=Math.pow(a.r,c);this.g=Math.pow(a.g,c);this.b=Math.pow(a.b,c);return this},convertGammaToLinear:function(){var a=this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,
l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=
a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-
this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){void 0===b&&(b=0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}});cb.prototype=Object.create(ea.prototype);cb.prototype.constructor=cb;cb.prototype.isDataTexture=!0;var N={common:{diffuse:{value:new J(15658734)},opacity:{value:1},
map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new C(1,1)}},displacementmap:{displacementMap:{value:null},
displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:2.5E-4},fogNear:{value:1},fogFar:{value:2E3},fogColor:{value:new J(16777215)}},lights:{ambientLightColor:{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:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],
properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new J(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new ga(0,0,1,1)}}},$a={basic:{uniforms:Ja.merge([N.common,N.aomap,N.lightmap,N.fog]),vertexShader:Y.meshbasic_vert,fragmentShader:Y.meshbasic_frag},lambert:{uniforms:Ja.merge([N.common,N.aomap,N.lightmap,N.emissivemap,N.fog,N.lights,{emissive:{value:new J(0)}}]),vertexShader:Y.meshlambert_vert,fragmentShader:Y.meshlambert_frag},
phong:{uniforms:Ja.merge([N.common,N.aomap,N.lightmap,N.emissivemap,N.bumpmap,N.normalmap,N.displacementmap,N.gradientmap,N.fog,N.lights,{emissive:{value:new J(0)},specular:{value:new J(1118481)},shininess:{value:30}}]),vertexShader:Y.meshphong_vert,fragmentShader:Y.meshphong_frag},standard:{uniforms:Ja.merge([N.common,N.aomap,N.lightmap,N.emissivemap,N.bumpmap,N.normalmap,N.displacementmap,N.roughnessmap,N.metalnessmap,N.fog,N.lights,{emissive:{value:new J(0)},roughness:{value:.5},metalness:{value:0},
envMapIntensity:{value:1}}]),vertexShader:Y.meshphysical_vert,fragmentShader:Y.meshphysical_frag},points:{uniforms:Ja.merge([N.points,N.fog]),vertexShader:Y.points_vert,fragmentShader:Y.points_frag},dashed:{uniforms:Ja.merge([N.common,N.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Y.linedashed_vert,fragmentShader:Y.linedashed_frag},depth:{uniforms:Ja.merge([N.common,N.displacementmap]),vertexShader:Y.depth_vert,fragmentShader:Y.depth_frag},normal:{uniforms:Ja.merge([N.common,
N.bumpmap,N.normalmap,N.displacementmap,{opacity:{value:1}}]),vertexShader:Y.normal_vert,fragmentShader:Y.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Y.cube_vert,fragmentShader:Y.cube_frag},equirect:{uniforms:{tEquirect:{value:null},tFlip:{value:-1}},vertexShader:Y.equirect_vert,fragmentShader:Y.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new q}},vertexShader:Y.distanceRGBA_vert,fragmentShader:Y.distanceRGBA_frag}};$a.physical={uniforms:Ja.merge([$a.standard.uniforms,
{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:Y.meshphysical_vert,fragmentShader:Y.meshphysical_frag};Object.assign(id.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),clone:function(){return(new this.constructor).copy(this)},
copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);
return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-
this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);
this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});var Af=0;Object.defineProperty(X.prototype,"needsUpdate",{get:function(){return this._needsUpdate},set:function(a){!0===a&&this.update();this._needsUpdate=a}});Object.assign(X.prototype,za.prototype,{isMaterial:!0,setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+
this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.4,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());
void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);
this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,
d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&
(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===
this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=
this.wireframeLinejoin);d.morphTargets=this.morphTargets;c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;this.lights=a.lights;this.blending=a.blending;this.side=a.side;this.shading=a.shading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=
a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=
a.visible;this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=a[d].clone();this.clippingPlanes=b;return this},update:function(){this.dispatchEvent({type:"update"})},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ga.prototype=Object.create(X.prototype);Ga.prototype.constructor=Ga;Ga.prototype.isShaderMaterial=!0;Ga.prototype.copy=function(a){X.prototype.copy.call(this,a);this.fragmentShader=
a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Ja.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};Ga.prototype.toJSON=function(a){a=X.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};
Za.prototype=Object.create(X.prototype);Za.prototype.constructor=Za;Za.prototype.isMeshDepthMaterial=!0;Za.prototype.copy=function(a){X.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Object.assign(Ua.prototype,
{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var m=a[h],l=a[h+1],p=a[h+2];m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),
l=a.getY(h),p=a.getZ(h);m<b&&(b=m);l<c&&(c=l);p<d&&(d=p);m>e&&(e=m);l>f&&(f=l);p>g&&(g=p)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new q;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},
copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new q;return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new q;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},
expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){var a=new q;return function(b){var c=this;b.updateMatrixWorld(!0);b.traverse(function(b){var e,f;e=b.geometry;if(void 0!==e)if(e.isGeometry){var g=e.vertices;e=0;for(f=g.length;e<f;e++)a.copy(g[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}else if(e.isBufferGeometry&&
(g=e.attributes.position,void 0!==g))for(e=0,f=g.count;e<f;e++)a.fromBufferAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(a)});return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new q).set((a.x-this.min.x)/
(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new q;return function(b){this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0<a.normal.x?(b=a.normal.x*this.min.x,c=a.normal.x*
this.max.x):(b=a.normal.x*this.max.x,c=a.normal.x*this.min.x);0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,b){return(b||new q).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new q;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),
getBoundingSphere:function(){var a=new q;return function(b){b=b||new Aa;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new q,new q,new q,new q,new q,new q,new q,new q];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);
a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);
return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Aa.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Ua;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,d.distanceToSquared(b[f]));this.radius=Math.sqrt(e);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);
this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},
clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new q;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=a||new Ua;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&
a.radius===this.radius}});Object.assign(Ba.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;c++)b[c]=a[c];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],
a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new q;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},
getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3.getInverse no longer takes a Matrix4 argument.");var c=a.elements,d=this.elements,e=c[0],f=c[1],g=c[2],h=c[3],k=c[4],m=c[5],l=c[6],p=c[7],c=c[8],n=c*k-m*p,r=m*l-c*h,q=p*h-k*l,t=e*n+f*r+g*q;if(0===t){if(!0===b)throw Error("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0");return this.identity()}t=1/t;d[0]=n*t;d[1]=(g*p-c*f)*t;d[2]=
(m*f-g*k)*t;d[3]=r*t;d[4]=(c*e-g*l)*t;d[5]=(g*h-m*e)*t;d[6]=q*t;d[7]=(f*l-p*e)*t;d[8]=(k*e-f*h)*t;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},fromArray:function(a,
b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});Object.assign(ia.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);
this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new q,b=new q;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=
-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new q).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new q;return function(b,c){var d=c||new q,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=
-(b.start.dot(this.normal)+this.constant)/f,0>f||1<f?void 0:d.copy(e).multiplyScalar(f).add(b.start)}}(),intersectsLine:function(a){var b=this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new q).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new q,b=new Ba;return function(c,d){var e=
this.coplanarPoint(a).applyMatrix4(c),f=d||b.getNormalMatrix(c),f=this.normal.applyMatrix3(f).normalize();this.constant=-e.dot(f);return this}}(),translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(jd.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},
copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],l=c[8],p=c[9],n=c[10],r=c[11],q=c[12],t=c[13],z=c[14],c=c[15];b[0].setComponents(f-a,m-g,r-l,c-q).normalize();b[1].setComponents(f+a,m+g,r+l,c+q).normalize();b[2].setComponents(f+d,m+h,r+p,c+t).normalize();b[3].setComponents(f-d,m-h,r-p,c-t).normalize();b[4].setComponents(f-e,m-k,r-n,c-z).normalize();
b[5].setComponents(f+e,m+k,r+n,c+z).normalize();return this},intersectsObject:function(){var a=new Aa;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Aa;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;
a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new q,b=new q;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=
this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});Object.assign(eb.prototype,{set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new q).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=
new q;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){var c=b||new q;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new q;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);
a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new q,b=new q,c=new q;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),p=c.lengthSq(),n=Math.abs(1-k*k),r;0<n?(d=k*l-m,e=k*m-l,r=h*n,0<=d?e>=-r?e<=r?(h=1/n,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+p):(e=h,d=Math.max(0,-(k*
e+m)),k=-d*d+e*(e+2*l)+p):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+p):e<=r?(d=0,e=Math.min(Math.max(-h,-l),h),k=e*(e+2*l)+p):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+p)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+p);f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new q;
return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d,f=b.radius*b.radius;if(e>f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,
b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;
if(f<d||d!==d)d=f;0<=g?(e=(a.min.z-h.z)*g,g*=a.max.z-h.z):(e=(a.max.z-h.z)*g,g*=a.min.z-h.z);if(c>g||e>d)return null;if(e>c||c!==c)c=e;if(g<d||d!==d)d=g;return 0>d?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new q;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new q,b=new q,c=new q,d=new q;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0<f){if(h)return null;h=1}else if(0>f)h=
-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.direction.add(this.origin).applyMatrix4(a);this.origin.applyMatrix4(a);this.direction.sub(this.origin);this.direction.normalize();return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});ab.RotationOrders=
"XYZ YZX ZXY XZY YXZ ZYX".split(" ");ab.DefaultOrder="XYZ";Object.defineProperties(ab.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(ab.prototype,{isEuler:!0,set:function(a,
b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=T.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],p=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?
(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(p,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(p,-1,1)),.99999>Math.abs(p)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._x=Math.atan2(p,e),this._z=Math.atan2(h,a)):(this._x=
0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(p,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=
new Q;return function(b,c,d){a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new ca;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();
return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new q(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Qd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=
~(1<<a|0)},test:function(a){return 0!==(this.mask&a.mask)}});var Bf=0;E.DefaultUp=new q(0,1,0);E.DefaultMatrixAutoUpdate=!0;Object.assign(E.prototype,za.prototype,{isObject3D:!0,applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},
setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new ca;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new q(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=new q(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new q(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new q;
return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new q(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new q(0,1,0);return function(b){return this.translateOnAxis(a,b)}}(),translateZ:function(){var a=new q(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=
new Q;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new Q;return function(b){0===this.position.distanceToSquared(b)?console.warn("THREE.Object3D.lookAt(): target vector is the same as object position."):(this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up),this.quaternion.setFromRotationMatrix(a))}}(),add:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===
this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a);return this},remove:function(a){if(1<arguments.length)for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),
this.children.splice(b,1))},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new q;this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new q,
b=new q;return function(c){c=c||new ca;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new ca;return function(b){b=b||new ab;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new q,b=new ca;return function(c){c=c||new q;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new ca;return function(b){b=b||new q;this.getWorldQuaternion(a);
return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&
this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a||""===a,d={};c&&(a={geometries:{},materials:{},textures:{},images:{}},d.metadata={version:4.4,
type:"Object",generator:"Object3D.toJSON"});var e={};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);"{}"!==JSON.stringify(this.userData)&&(e.userData=this.userData);!0===this.castShadow&&(e.castShadow=!0);!0===this.receiveShadow&&(e.receiveShadow=!0);!1===this.visible&&(e.visible=!1);e.matrix=this.matrix.toArray();void 0!==this.geometry&&(void 0===a.geometries[this.geometry.uuid]&&(a.geometries[this.geometry.uuid]=this.geometry.toJSON(a)),e.geometry=this.geometry.uuid);void 0!==
this.material&&(void 0===a.materials[this.material.uuid]&&(a.materials[this.material.uuid]=this.material.toJSON(a)),e.material=this.material.uuid);if(0<this.children.length){e.children=[];for(var f=0;f<this.children.length;f++)e.children.push(this.children[f].toJSON(a).object)}if(c){var c=b(a.geometries),f=b(a.materials),g=b(a.textures);a=b(a.images);0<c.length&&(d.geometries=c);0<f.length&&(d.materials=f);0<g.length&&(d.textures=g);0<a.length&&(d.images=a)}d.object=e;return d},clone:function(a){return(new this.constructor).copy(this,
a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;this.layers.mask=a.layers.mask;this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;
this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(var c=0;c<a.children.length;c++)this.add(a.children[c].clone());return this}});Object.assign(Eb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){return(a||new q).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new q).subVectors(this.end,
this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new q;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new q,b=new q;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=T.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,
b);c=c||new q;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Ka,{normal:function(){var a=new q;return function(b,c,d,e){e=e||new q;e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new q,b=new q,c=new q;
return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var m=d*k-e*e;h=h||new q;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new q;return function(b,c,d,e){b=Ka.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Ka.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},
setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new q,b=new q;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new q).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Ka.normal(this.a,
this.b,this.c,a)},plane:function(a){return(a||new ia).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Ka.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Ka.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new ia,b=[new Eb,new Eb,new Eb],c=new q,d=new q;return function(e,f){var g=f||new q,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);
else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k<b.length;k++){b[k].closestPointToPoint(c,!0,d);var m=c.distanceToSquared(d);m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});Object.assign(ua.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;
for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});La.prototype=Object.create(X.prototype);La.prototype.constructor=La;La.prototype.isMeshBasicMaterial=!0;La.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=
a.aoMapIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.morphTargets=a.morphTargets;return this};var Cf=0;Object.defineProperty(W.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(W.prototype,
{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<
e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new J);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=
this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new q);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=
a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new ga);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*
this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+
3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,this.itemSize)).copy(this)}});qc.prototype=Object.create(W.prototype);qc.prototype.constructor=qc;rc.prototype=Object.create(W.prototype);rc.prototype.constructor=rc;sc.prototype=Object.create(W.prototype);sc.prototype.constructor=sc;tc.prototype=Object.create(W.prototype);tc.prototype.constructor=tc;fb.prototype=Object.create(W.prototype);fb.prototype.constructor=fb;
uc.prototype=Object.create(W.prototype);uc.prototype.constructor=uc;gb.prototype=Object.create(W.prototype);gb.prototype.constructor=gb;B.prototype=Object.create(W.prototype);B.prototype.constructor=B;vc.prototype=Object.create(W.prototype);vc.prototype.constructor=vc;Object.assign(Ee.prototype,{computeGroups:function(a){var b,c=[],d=void 0;a=a.faces;for(var e=0;e<a.length;e++){var f=a[e];f.materialIndex!==d&&(d=f.materialIndex,void 0!==b&&(b.count=3*e-b.start,c.push(b)),b={start:3*e,materialIndex:d})}void 0!==
b&&(b.count=3*e-b.start,c.push(b));this.groups=c},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,p=l.length,n;if(0<p){n=[];for(m=0;m<p;m++)n[m]=[];this.morphTargets.normal=n}for(var r=a.skinIndices,q=a.skinWeights,t=r.length===c.length,z=q.length===c.length,m=0;m<b.length;m++){var w=b[m];this.vertices.push(c[w.a],
c[w.b],c[w.c]);var y=w.vertexNormals;3===y.length?this.normals.push(y[0],y[1],y[2]):(y=w.normal,this.normals.push(y,y,y));y=w.vertexColors;3===y.length?this.colors.push(y[0],y[1],y[2]):(y=w.color,this.colors.push(y,y,y));!0===e&&(y=d[0][m],void 0!==y?this.uvs.push(y[0],y[1],y[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new C,new C,new C)));!0===f&&(y=d[1][m],void 0!==y?this.uvs2.push(y[0],y[1],y[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",
m),this.uvs2.push(new C,new C,new C)));for(y=0;y<h;y++){var M=g[y].vertices;k[y].push(M[w.a],M[w.b],M[w.c])}for(y=0;y<p;y++)M=l[y].vertexNormals[m],n[y].push(M.a,M.b,M.c);t&&this.skinIndices.push(r[w.a],r[w.b],r[w.c]);z&&this.skinWeights.push(q[w.a],q[w.b],q[w.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});
var Sd=0;Object.assign(R.prototype,za.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new Ba).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=
this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new Q;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new Q;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new Q;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new Q;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new Q;
return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new E;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[l[a].clone(),l[b].clone(),l[d].clone()]:[],r=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new ua(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([p[a].clone(),p[b].clone(),p[d].clone()]);void 0!==
m&&c.faceVertexUvs[1].push([n[a].clone(),n[b].clone(),n[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var l=[],p=[],n=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new q(f[e],f[e+1],f[e+2])),void 0!==g&&l.push(new q(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new J(h[e],
h[e+1],h[e+2])),void 0!==k&&p.push(new C(k[r],k[r+1])),void 0!==m&&n.push(new C(m[r],m[r+1]));if(void 0!==d)if(f=a.groups,0<f.length)for(e=0;e<f.length;e++)for(var x=f[e],t=x.start,z=x.count,r=t,t=t+z;r<t;r+=3)b(d[r],d[r+1],d[r+2],x.materialIndex);else for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());
return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new Q;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new q,b=new q,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];
a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===a&&(a=!0);var b,c,d;d=Array(this.vertices.length);b=0;for(c=this.vertices.length;b<c;b++)d[b]=new q;if(a){var e,f,g,h=new q,k=new q;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=this.vertices[c.a],f=this.vertices[c.b],g=this.vertices[c.c],h.subVectors(g,f),k.subVectors(e,f),h.cross(k),d[c.a].add(h),d[c.b].add(h),d[c.c].add(h)}else for(this.computeFaceNormals(),
a=0,b=this.faces.length;a<b;a++)c=this.faces[a],d[c.a].add(c.normal),d[c.b].add(c.normal),d[c.c].add(c.normal);b=0;for(c=this.vertices.length;b<c;b++)d[b].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=c.vertexNormals,3===e.length?(e[0].copy(d[c.a]),e[1].copy(d[c.b]),e[2].copy(d[c.c])):(e[0]=d[c.a].clone(),e[1]=d[c.b].clone(),e[2]=d[c.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;this.computeFaceNormals();a=0;for(b=this.faces.length;a<
b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b,c,d,e;c=0;for(d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,
b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):e.__originalVertexNormals[a]=e.vertexNormals[a].clone();var f=new R;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={};this.morphNormals[a].faceNormals=[];this.morphNormals[a].vertexNormals=[];e=this.morphNormals[a].faceNormals;var g=this.morphNormals[a].vertexNormals,h,k;c=0;for(d=this.faces.length;c<d;c++)h=new q,k={a:new q,
b:new q,c:new q},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();f.computeVertexNormals();c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(e.normal),k.a.copy(e.vertexNormals[0]),k.b.copy(e.vertexNormals[1]),k.c.copy(e.vertexNormals[2])}c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__originalVertexNormals},computeLineDistances:function(){for(var a=
0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Ua);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Aa);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(!1===(a&&a.isGeometry))console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a);
else{var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,m=this.faceVertexUvs[0],l=a.faceVertexUvs[0],p=this.colors,n=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new Ba).getNormalMatrix(b));a=0;for(var r=g.length;a<r;a++){var q=g[a].clone();void 0!==b&&q.applyMatrix4(b);f.push(q)}a=0;for(r=n.length;a<r;a++)p.push(n[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],t=g.vertexNormals,n=g.vertexColors,p=new ua(g.a+e,g.b+e,g.c+e);p.normal.copy(g.normal);void 0!==d&&p.normal.applyMatrix3(d).normalize();
b=0;for(f=t.length;b<f;b++)q=t[b].clone(),void 0!==d&&q.applyMatrix3(d).normalize(),p.vertexNormals.push(q);p.color.copy(g.color);b=0;for(f=n.length;b<f;b++)q=n[b],p.vertexColors.push(q.clone());p.materialIndex=g.materialIndex+c;h.push(p)}a=0;for(r=l.length;a<r;a++)if(c=l[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());m.push(d)}}},mergeMesh:function(a){!1===(a&&a.isMesh)?console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a):(a.matrixAutoUpdate&&a.updateMatrix(),
this.merge(a.geometry,a.matrix))},mergeVertices:function(){var a={},b=[],c=[],d,e=Math.pow(10,4),f,g;f=0;for(g=this.vertices.length;f<g;f++)d=this.vertices[f],d=Math.round(d.x*e)+"_"+Math.round(d.y*e)+"_"+Math.round(d.z*e),void 0===a[d]?(a[d]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[d]];a=[];f=0;for(g=this.faces.length;f<g;f++)for(e=this.faces[f],e.a=c[e.a],e.b=c[e.b],e.c=c[e.c],e=[e.a,e.b,e.c],d=0;3>d;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,
1),c=0,g=this.faceVertexUvs.length;c<g;c++)this.faceVertexUvs[c].splice(e,1);f=this.vertices.length-b.length;this.vertices=b;return f},sortFacesByMaterialIndex:function(){for(var a=this.faces,b=a.length,c=0;c<b;c++)a[c]._id=c;a.sort(function(a,b){return a.materialIndex-b.materialIndex});var d=this.faceVertexUvs[0],e=this.faceVertexUvs[1],f,g;d&&d.length===b&&(f=[]);e&&e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);g&&(this.faceVertexUvs[1]=
g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==p[b])return p[b];p[b]=l.length;l.push(a.getHex());return p[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=n.length/2;n.push(a.x,a.y);return r[b]}var e={metadata:{version:4.4,type:"Geometry",
generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],m={},l=[],p={},n=[],r={};for(g=0;g<this.faces.length;g++){var q=this.faces[g],t=void 0!==this.faceVertexUvs[0][g],z=0<q.normal.length(),w=0<q.vertexNormals.length,y=1!==q.color.r||1!==q.color.g||1!==q.color.b,
M=0<q.vertexColors.length,v=0,v=a(v,0,0),v=a(v,1,!0),v=a(v,2,!1),v=a(v,3,t),v=a(v,4,z),v=a(v,5,w),v=a(v,6,y),v=a(v,7,M);h.push(v);h.push(q.a,q.b,q.c);h.push(q.materialIndex);t&&(t=this.faceVertexUvs[0][g],h.push(d(t[0]),d(t[1]),d(t[2])));z&&h.push(b(q.normal));w&&(z=q.vertexNormals,h.push(b(z[0]),b(z[1]),b(z[2])));y&&h.push(c(q.color));M&&(q=q.vertexColors,h.push(c(q[0]),c(q[1]),c(q[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<l.length&&(e.data.colors=l);0<n.length&&(e.data.uvs=[n]);e.data.faces=
h;return e},clone:function(){return(new R).copy(this)},copy:function(a){var b,c,d,e,f,g;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;d=a.vertices;b=0;for(c=d.length;b<c;b++)this.vertices.push(d[b].clone());d=a.colors;b=0;for(c=d.length;b<c;b++)this.colors.push(d[b].clone());d=a.faces;b=0;for(c=d.length;b<c;b++)this.faces.push(d[b].clone());
b=0;for(c=a.faceVertexUvs.length;b<c;b++){var h=a.faceVertexUvs[b];void 0===this.faceVertexUvs[b]&&(this.faceVertexUvs[b]=[]);d=0;for(e=h.length;d<e;d++){var k=h[d],m=[];f=0;for(g=k.length;f<g;f++)m.push(k[f].clone());this.faceVertexUvs[b].push(m)}}f=a.morphTargets;b=0;for(c=f.length;b<c;b++){g={};g.name=f[b].name;if(void 0!==f[b].vertices)for(g.vertices=[],d=0,e=f[b].vertices.length;d<e;d++)g.vertices.push(f[b].vertices[d].clone());if(void 0!==f[b].normals)for(g.normals=[],d=0,e=f[b].normals.length;d<
e;d++)g.normals.push(f[b].normals[d].clone());this.morphTargets.push(g)}f=a.morphNormals;b=0;for(c=f.length;b<c;b++){g={};if(void 0!==f[b].vertexNormals)for(g.vertexNormals=[],d=0,e=f[b].vertexNormals.length;d<e;d++)h=f[b].vertexNormals[d],k={},k.a=h.a.clone(),k.b=h.b.clone(),k.c=h.c.clone(),g.vertexNormals.push(k);if(void 0!==f[b].faceNormals)for(g.faceNormals=[],d=0,e=f[b].faceNormals.length;d<e;d++)g.faceNormals.push(f[b].faceNormals[d].clone());this.morphNormals.push(g)}d=a.skinWeights;b=0;for(c=
d.length;b<c;b++)this.skinWeights.push(d[b].clone());d=a.skinIndices;b=0;for(c=d.length;b<c;b++)this.skinIndices.push(d[b].clone());d=a.lineDistances;b=0;for(c=d.length;b<c;b++)this.lineDistances.push(d[b]);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=
a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});I.MaxIndex=65535;Object.assign(I.prototype,za.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Rd(a)?gb:fb)(a,1):this.index=a},addAttribute:function(a,b,c){if(!1===(b&&b.isBufferAttribute)&&!1===(b&&b.isInterleavedBufferAttribute))console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),
this.addAttribute(a,new W(b,c));else if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=
b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new Ba).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new Q;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new Q;return function(b){a.makeRotationY(b);
this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new Q;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new Q;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new Q;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new E;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();
var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new B(3*b.vertices.length,3);var c=new B(3*b.colors.length,3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new B(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&
(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;
c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),
c.needsUpdate=!0),b.colorsNeedUpdate=!1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new Ee).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},
fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new W(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new W(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new W(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new W(b,2)).copyVector2sArray(a.uvs)));
0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new W(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Rd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new W(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new B(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new B(4*
a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new B(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Ua);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new Ua,b=new q;return function(){null===this.boundingSphere&&(this.boundingSphere=new Aa);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;
if(void 0===b.normal)this.addAttribute("normal",new W(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h,k,m,l=new q,p=new q,n=new q,r=new q,x=new q;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,z=c.length;t<z;++t)for(f=c[t],g=f.start,h=f.count,f=g,g+=h;f<g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],l.fromArray(d,h),p.fromArray(d,k),n.fromArray(d,m),r.subVectors(n,p),x.subVectors(l,p),r.cross(x),e[h]+=r.x,e[h+1]+=r.y,
e[h+2]+=r.z,e[k]+=r.x,e[k+1]+=r.y,e[k+2]+=r.z,e[m]+=r.x,e[m+1]+=r.y,e[m+2]+=r.z}else for(f=0,g=d.length;f<g;f+=9)l.fromArray(d,f),p.fromArray(d,f+3),n.fromArray(d,f+6),r.subVectors(n,p),x.subVectors(l,p),r.cross(x),e[f]=r.x,e[f+1]=r.y,e[f+2]=r.z,e[f+3]=r.x,e[f+4]=r.y,e[f+5]=r.z,e[f+6]=r.x,e[f+7]=r.y,e[f+8]=r.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(!1===(a&&a.isBufferGeometry))console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",
a);else{void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}},normalizeNormals:function(){for(var a=this.attributes.normal.array,b,c,d,e=0,f=a.length;e<f;e+=3)b=a[e],c=a[e+1],d=a[e+2],b=1/Math.sqrt(b*b+c*c+d*d),a[e]*=b,a[e+1]*=b,a[e+2]*=b},toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
this;var a=new I,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,m=0,l=b.length;m<l;m++){h=b[m]*e;for(var p=0;p<e;p++)g[k++]=f[h++]}a.addAttribute(d,new W(g,e))}return a},toJSON:function(){var a={metadata:{version:4.4,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);if(void 0!==this.parameters){var b=this.parameters,c;for(c in b)void 0!==b[c]&&
(a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c],b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),
radius:c.radius});return a},clone:function(){return(new I).copy(this)},copy:function(a){var b,c,d;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(b in c)this.addAttribute(b,c[b].clone());var e=a.morphAttributes;for(b in e){var f=[],g=e[b];c=0;for(d=g.length;c<d;c++)f.push(g[c].clone());this.morphAttributes[b]=f}b=a.groups;c=0;for(d=b.length;c<d;c++)e=
b[c],this.addGroup(e.start,e.count,e.materialIndex);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});wa.prototype=Object.assign(Object.create(E.prototype),{constructor:wa,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){E.prototype.copy.call(this,a);this.drawMode=a.drawMode;
return this},updateMorphTargets:function(){var a=this.geometry.morphTargets;if(void 0!==a&&0<a.length){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var b=0,c=a.length;b<c;b++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[a[b].name]=b}},raycast:function(){function a(a,b,c,d,e,f,g){Ka.barycoordFromPoint(a,b,c,d,t);e.multiplyScalar(t.x);f.multiplyScalar(t.y);g.multiplyScalar(t.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===
(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;w.copy(g);w.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(w);return c<b.near||c>b.far?null:{distance:c,point:w.clone(),object:a}}function c(c,d,e,f,m,l,u,p){g.fromBufferAttribute(f,l);h.fromBufferAttribute(f,u);k.fromBufferAttribute(f,p);if(c=b(c,d,e,g,h,k,z))m&&(n.fromBufferAttribute(m,l),r.fromBufferAttribute(m,u),x.fromBufferAttribute(m,p),c.uv=a(z,g,h,k,n,r,x)),c.face=new ua(l,u,p,Ka.normal(g,
h,k)),c.faceIndex=l;return c}var d=new Q,e=new eb,f=new Aa,g=new q,h=new q,k=new q,m=new q,l=new q,p=new q,n=new C,r=new C,x=new C,t=new q,z=new q,w=new q;return function(q,t){var v=this.geometry,w=this.material,G=this.matrixWorld;if(void 0!==w&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(G),!1!==q.ray.intersectsSphere(f)&&(d.getInverse(G),e.copy(q.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox)))){var A;if(v.isBufferGeometry){var H,
C,w=v.index,E=v.attributes.position,G=v.attributes.uv,B,I;if(null!==w)for(B=0,I=w.count;B<I;B+=3){if(v=w.getX(B),H=w.getX(B+1),C=w.getX(B+2),A=c(this,q,e,E,G,v,H,C))A.faceIndex=Math.floor(B/3),t.push(A)}else for(B=0,I=E.count;B<I;B+=3)if(v=B,H=B+1,C=B+2,A=c(this,q,e,E,G,v,H,C))A.index=v,t.push(A)}else if(v.isGeometry){var J,G=Array.isArray(w);B=v.vertices;I=v.faces;H=v.faceVertexUvs[0];0<H.length&&(E=H);for(var R=0,P=I.length;R<P;R++){var K=I[R];A=G?w[K.materialIndex]:w;if(void 0!==A){H=B[K.a];C=
B[K.b];J=B[K.c];if(!0===A.morphTargets){A=v.morphTargets;var L=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var S=0,N=A.length;S<N;S++){var V=L[S];if(0!==V){var Q=A[S].vertices;g.addScaledVector(m.subVectors(Q[K.a],H),V);h.addScaledVector(l.subVectors(Q[K.b],C),V);k.addScaledVector(p.subVectors(Q[K.c],J),V)}}g.add(H);h.add(C);k.add(J);H=g;C=h;J=k}if(A=b(this,q,e,H,C,J,z))E&&E[R]&&(L=E[R],n.copy(L[0]),r.copy(L[1]),x.copy(L[2]),A.uv=a(z,H,C,J,n,r,x)),A.face=K,A.faceIndex=R,
t.push(A)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Fb.prototype=Object.create(R.prototype);Fb.prototype.constructor=Fb;hb.prototype=Object.create(I.prototype);hb.prototype.constructor=hb;wc.prototype=Object.create(R.prototype);wc.prototype.constructor=wc;ib.prototype=Object.create(I.prototype);ib.prototype.constructor=ib;da.prototype=Object.create(E.prototype);da.prototype.constructor=da;da.prototype.isCamera=!0;da.prototype.getWorldDirection=
function(){var a=new ca;return function(b){b=b||new q;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}();da.prototype.clone=function(){return(new this.constructor).copy(this)};da.prototype.copy=function(a){E.prototype.copy.call(this,a);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this};Ea.prototype=Object.assign(Object.create(da.prototype),{constructor:Ea,isPerspectiveCamera:!0,copy:function(a){da.prototype.copy.call(this,
a);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;this.view=null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*T.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*T.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*T.RAD2DEG*Math.atan(Math.tan(.5*
T.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*T.DEG2RAD*this.fov)/this.zoom,
c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==f)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=E.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=
Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});Gb.prototype=Object.assign(Object.create(da.prototype),{constructor:Gb,isOrthographicCamera:!0,copy:function(a){da.prototype.copy.call(this,a);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){this.view={fullWidth:a,
fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,
d=(this.top-this.bottom)/this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=E.prototype.toJSON.call(this,a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});
var Pf=0;Hb.prototype.isFogExp2=!0;Hb.prototype.clone=function(){return new Hb(this.color.getHex(),this.density)};Hb.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Ib.prototype.isFog=!0;Ib.prototype.clone=function(){return new Ib(this.color.getHex(),this.near,this.far)};Ib.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};ld.prototype=Object.assign(Object.create(E.prototype),{constructor:ld,copy:function(a,
b){E.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=E.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Wd.prototype=Object.assign(Object.create(E.prototype),
{constructor:Wd,isLensFlare:!0,copy:function(a){E.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new J(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,
opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;a<b;a++)c=this.lensFlares[a],c.x=this.positionScreen.x+d*c.distance,c.y=this.positionScreen.y+e*c.distance,c.wantedRotation=c.x*Math.PI*.25,c.rotation+=.25*(c.wantedRotation-c.rotation)}});bb.prototype=Object.create(X.prototype);bb.prototype.constructor=bb;bb.prototype.isSpriteMaterial=!0;bb.prototype.copy=function(a){X.prototype.copy.call(this,
a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};Ac.prototype=Object.assign(Object.create(E.prototype),{constructor:Ac,isSprite:!0,raycast:function(){var a=new q,b=new q,c=new q;return function(d,e){b.setFromMatrixPosition(this.matrixWorld);d.ray.closestPointToPoint(b,a);c.setFromMatrixScale(this.matrixWorld);var f=c.x*c.y/4;b.distanceToSquared(a)>f||(f=d.ray.origin.distanceTo(a),f<d.near||f>d.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});
Bc.prototype=Object.assign(Object.create(E.prototype),{constructor:Bc,copy:function(a){E.prototype.copy.call(this,a,!1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-
1].object},raycast:function(){var a=new q;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new q,b=new q;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;
for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=E.prototype.toJSON.call(this,a);a.object.levels=[];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(Cc.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new Q;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){for(var a,b=0,c=this.bones.length;b<
c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<c;b++)if(a=this.bones[b])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new Q;return function(){for(var b=this.bones,c=this.boneInverses,d=this.boneMatrices,e=this.boneTexture,f=0,g=b.length;f<g;f++)a.multiplyMatrices(b[f]?b[f].matrixWorld:
this.identityMatrix,c[f]),a.toArray(d,16*f);void 0!==e&&(e.needsUpdate=!0)}}(),clone:function(){return new Cc(this.bones,this.boneInverses)}});md.prototype=Object.assign(Object.create(E.prototype),{constructor:md,isBone:!0});nd.prototype=Object.assign(Object.create(wa.prototype),{constructor:nd,isSkinnedMesh:!0,bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},
pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){if(this.geometry&&this.geometry.isGeometry)for(var a=0;a<this.geometry.skinWeights.length;a++){var b=this.geometry.skinWeights[a],c=1/b.lengthManhattan();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry)for(var b=new ga,d=this.geometry.attributes.skinWeight,a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.lengthManhattan(),Infinity!==c?b.multiplyScalar(c):
b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)},updateMatrixWorld:function(){wa.prototype.updateMatrixWorld.call(this,!0);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):"detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});ka.prototype=Object.create(X.prototype);ka.prototype.constructor=
ka;ka.prototype.isLineBasicMaterial=!0;ka.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};Ca.prototype=Object.assign(Object.create(E.prototype),{constructor:Ca,isLine:!0,raycast:function(){var a=new Q,b=new eb,c=new Aa;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);
c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new q,m=new q,h=new q,l=new q,p=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var n=g.index,r=g.attributes.position.array;if(null!==n)for(var n=n.array,g=0,x=n.length-1;g<x;g+=p){var t=n[g+1];k.fromArray(r,3*n[g]);m.fromArray(r,3*t);t=b.distanceSqToSegment(k,m,l,h);t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),
index:g,face:null,faceIndex:null,object:this}))}else for(g=0,x=r.length/3-1;g<x;g+=p)k.fromArray(r,3*g),m.fromArray(r,3*g+3),t=b.distanceSqToSegment(k,m,l,h),t>f||(l.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=p)t=b.distanceSqToSegment(k[g],k[g+1],l,h),t>f||(l.applyMatrix4(this.matrixWorld),
t=d.ray.origin.distanceTo(l),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});ha.prototype=Object.assign(Object.create(Ca.prototype),{constructor:ha,isLineSegments:!0});od.prototype=Object.assign(Object.create(Ca.prototype),{constructor:od,isLineLoop:!0});Oa.prototype=Object.create(X.prototype);Oa.prototype.constructor=Oa;
Oa.prototype.isPointsMaterial=!0;Oa.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Jb.prototype=Object.assign(Object.create(E.prototype),{constructor:Jb,isPoints:!0,raycast:function(){var a=new Q,b=new eb,c=new Aa;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<l){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>
d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),l=m*m,m=new q;if(h.isBufferGeometry){var p=h.index,h=h.attributes.position.array;if(null!==
p)for(var n=p.array,p=0,r=n.length;p<r;p++){var x=n[p];m.fromArray(h,3*x);f(m,x)}else for(p=0,n=h.length/3;p<n;p++)m.fromArray(h,3*p),f(m,p)}else for(m=h.vertices,p=0,n=m.length;p<n;p++)f(m[p],p)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Dc.prototype=Object.assign(Object.create(E.prototype),{constructor:Dc});pd.prototype=Object.create(ea.prototype);pd.prototype.constructor=pd;Kb.prototype=Object.create(ea.prototype);Kb.prototype.constructor=Kb;Kb.prototype.isCompressedTexture=
!0;qd.prototype=Object.create(ea.prototype);qd.prototype.constructor=qd;Ec.prototype=Object.create(ea.prototype);Ec.prototype.constructor=Ec;Ec.prototype.isDepthTexture=!0;Lb.prototype=Object.create(I.prototype);Lb.prototype.constructor=Lb;Fc.prototype=Object.create(R.prototype);Fc.prototype.constructor=Fc;Mb.prototype=Object.create(I.prototype);Mb.prototype.constructor=Mb;Gc.prototype=Object.create(R.prototype);Gc.prototype.constructor=Gc;xa.prototype=Object.create(I.prototype);xa.prototype.constructor=
xa;Hc.prototype=Object.create(R.prototype);Hc.prototype.constructor=Hc;Nb.prototype=Object.create(xa.prototype);Nb.prototype.constructor=Nb;Ic.prototype=Object.create(R.prototype);Ic.prototype.constructor=Ic;kb.prototype=Object.create(xa.prototype);kb.prototype.constructor=kb;Jc.prototype=Object.create(R.prototype);Jc.prototype.constructor=Jc;Ob.prototype=Object.create(xa.prototype);Ob.prototype.constructor=Ob;Kc.prototype=Object.create(R.prototype);Kc.prototype.constructor=Kc;Pb.prototype=Object.create(xa.prototype);
Pb.prototype.constructor=Pb;Lc.prototype=Object.create(R.prototype);Lc.prototype.constructor=Lc;Qb.prototype=Object.create(I.prototype);Qb.prototype.constructor=Qb;Mc.prototype=Object.create(R.prototype);Mc.prototype.constructor=Mc;Rb.prototype=Object.create(I.prototype);Rb.prototype.constructor=Rb;Nc.prototype=Object.create(R.prototype);Nc.prototype.constructor=Nc;Sb.prototype=Object.create(I.prototype);Sb.prototype.constructor=Sb;var Pa={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=
a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g,h,k;if(0<Pa.area(a))for(h=0;h<c;h++)e[h]=h;else for(h=0;h<c;h++)e[h]=c-1-h;var m=2*c;for(h=c-1;2<c;){if(0>=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var l;a:{var p,n,r,q,t,z,w,y;p=a[e[g]].x;n=a[e[g]].y;r=a[e[h]].x;q=a[e[h]].y;t=a[e[k]].x;z=a[e[k]].y;if(0>=(r-
p)*(z-n)-(q-n)*(t-p))l=!1;else{var M,v,F,G,A,H,C,B,E,I;M=t-r;v=z-q;F=p-t;G=n-z;A=r-p;H=q-n;for(l=0;l<c;l++)if(w=a[e[l]].x,y=a[e[l]].y,!(w===p&&y===n||w===r&&y===q||w===t&&y===z)&&(C=w-p,B=y-n,E=w-r,I=y-q,w-=t,y-=z,E=M*I-v*E,C=A*B-H*C,B=F*y-G*w,E>=-Number.EPSILON&&B>=-Number.EPSILON&&C>=-Number.EPSILON)){l=!1;break a}l=!0}}if(l){d.push([a[e[g]],a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;k<c;g++,k++)e[g]=e[k];c--;m=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=
a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,m=e.y-c.y,l=a.x-c.x,n=a.y-c.y,p=h*k-g*m,u=h*l-g*n;if(Math.abs(p)>Number.EPSILON){if(0<p){if(0>u||u>p)return[];k=m*l-k*n;if(0>k||k>p)return[]}else{if(0<u||u<p)return[];k=m*l-k*n;if(0<k||k<p)return[]}if(0===k)return!f||0!==u&&u!==p?[a]:[];if(k===p)return!f||0!==u&&u!==p?[b]:[];
if(0===u)return[c];if(u===p)return[e];f=k/p;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==u||m*l!==k*n)return[];h=0===g&&0===h;k=0===k&&0===m;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,p=c.x,m=e,c=e.x):(b=e,p=e.x,m=c,c=c.x)):(a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,p=c.y,m=e,c=e.y):(b=e,p=e.y,m=c,c=c.y));return k<=p?a<p?[]:a===p?f?[]:[b]:a<=c?[b,h]:[b,m]:
k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h,k,m,l,p={};k=a.concat();g=0;for(h=b.length;g<h;g++)Array.prototype.push.apply(k,b[g]);g=0;for(h=k.length;g<h;g++)l=k[g].x+":"+k[g].y,void 0!==p[l]&&console.warn("THREE.ShapeUtils: Duplicate point",l,g),p[l]=g;g=function(a,b){function c(a,b){var d=h.length-
1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;c<h.length;c++)if(f=c+1,f%=h.length,f=e(a,b,h[c],h[f],!0),0<f.length)return!0;return!1}function g(a,c){var d,f,h,k;for(d=0;d<m.length;d++)for(f=b[m[d]],h=0;h<f.length;h++)if(k=h+1,k%=f.length,k=e(a,c,f[h],f[k],!0),0<k.length)return!0;return!1}var h=a.concat(),k,m=[],l,n,p,u,q,C=[],B,E,I,J=0;for(l=b.length;J<
l;J++)m.push(J);B=0;for(var P=2*m.length;0<m.length;){P--;if(0>P){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(n=B;n<h.length;n++){p=h[n];l=-1;for(J=0;J<m.length;J++)if(u=m[J],q=p.x+":"+p.y+":"+u,void 0===C[q]){k=b[u];for(E=0;E<k.length;E++)if(u=k[E],c(n,E)&&!d(p,u)&&!g(p,u)){l=E;m.splice(J,1);B=h.slice(0,n+1);u=h.slice(n);E=k.slice(l);I=k.slice(0,l+1);h=B.concat(E).concat(I).concat(u);B=n;break}if(0<=l)break;C[q]=!0}if(0<=l)break}}return h}(a,b);var n=
Pa.triangulate(g,!1);g=0;for(h=n.length;g<h;g++)for(m=n[g],k=0;3>k;k++)l=m[k].x+":"+m[k].y,l=p[l],void 0!==l&&(m[k]=l);return n.concat()},isClockWise:function(a){return 0>Pa.area(a)}};Da.prototype=Object.create(R.prototype);Da.prototype.constructor=Da;Da.prototype.addShapeList=function(a,b){for(var c=a.length,d=0;d<c;d++)this.addShape(a[d],b)};Da.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}
function d(a,b,c){var d,e,f;e=a.x-b.x;f=a.y-b.y;d=c.x-a.x;var g=c.y-a.y,h=e*e+f*f;if(Math.abs(e*g-f*d)>Number.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&(a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new C(d/f,e/f)}
function e(a,b){var c,d;for(O=a.length;0<=--O;){c=O;d=O-1;0>d&&(d=a.length-1);var e,f=r+2*l;for(e=0;e<f;e++){var g=T*e,h=T*(e+1),k=b+c+g,g=b+d+g,m=b+d+h,h=b+c+h,k=k+J,g=g+J,m=m+J,h=h+J;I.faces.push(new ua(k,g,h,null,null,1));I.faces.push(new ua(g,m,h,null,null,1));k=w.generateSideWallUV(I,k,g,m,h);I.faceVertexUvs[0].push([k[0],k[1],k[3]]);I.faceVertexUvs[0].push([k[1],k[2],k[3]])}}}function f(a,b,c){I.vertices.push(new q(a,b,c))}function g(a,b,c){a+=J;b+=J;c+=J;I.faces.push(new ua(a,b,c,null,null,
0));a=w.generateTopUV(I,a,b,c);I.faceVertexUvs[0].push(a)}var h=void 0!==b.amount?b.amount:100,k=void 0!==b.bevelThickness?b.bevelThickness:6,m=void 0!==b.bevelSize?b.bevelSize:k-2,l=void 0!==b.bevelSegments?b.bevelSegments:3,p=void 0!==b.bevelEnabled?b.bevelEnabled:!0,n=void 0!==b.curveSegments?b.curveSegments:12,r=void 0!==b.steps?b.steps:1,x=b.extrudePath,t,z=!1,w=void 0!==b.UVGenerator?b.UVGenerator:Da.WorldUVGenerator,y,E,v,F;x&&(t=x.getSpacedPoints(r),z=!0,p=!1,y=void 0!==b.frames?b.frames:
x.computeFrenetFrames(r,!1),E=new q,v=new q,F=new q);p||(m=k=l=0);var G,A,B,I=this,J=this.vertices.length,x=a.extractPoints(n),n=x.shape,U=x.holes;if(x=!Pa.isClockWise(n)){n=n.reverse();A=0;for(B=U.length;A<B;A++)G=U[A],Pa.isClockWise(G)&&(U[A]=G.reverse());x=!1}var R=Pa.triangulateShape(n,U),Q=n;A=0;for(B=U.length;A<B;A++)G=U[A],n=n.concat(G);var N,P,K,L,S,T=n.length,V,W=R.length,x=[],O=0;K=Q.length;N=K-1;for(P=O+1;O<K;O++,N++,P++)N===K&&(N=0),P===K&&(P=0),x[O]=d(Q[O],Q[N],Q[P]);var X=[],Y,ca=x.concat();
A=0;for(B=U.length;A<B;A++){G=U[A];Y=[];O=0;K=G.length;N=K-1;for(P=O+1;O<K;O++,N++,P++)N===K&&(N=0),P===K&&(P=0),Y[O]=d(G[O],G[N],G[P]);X.push(Y);ca=ca.concat(Y)}for(N=0;N<l;N++){K=N/l;L=k*Math.cos(K*Math.PI/2);P=m*Math.sin(K*Math.PI/2);O=0;for(K=Q.length;O<K;O++)S=c(Q[O],x[O],P),f(S.x,S.y,-L);A=0;for(B=U.length;A<B;A++)for(G=U[A],Y=X[A],O=0,K=G.length;O<K;O++)S=c(G[O],Y[O],P),f(S.x,S.y,-L)}P=m;for(O=0;O<T;O++)S=p?c(n[O],ca[O],P):n[O],z?(v.copy(y.normals[0]).multiplyScalar(S.x),E.copy(y.binormals[0]).multiplyScalar(S.y),
F.copy(t[0]).add(v).add(E),f(F.x,F.y,F.z)):f(S.x,S.y,0);for(K=1;K<=r;K++)for(O=0;O<T;O++)S=p?c(n[O],ca[O],P):n[O],z?(v.copy(y.normals[K]).multiplyScalar(S.x),E.copy(y.binormals[K]).multiplyScalar(S.y),F.copy(t[K]).add(v).add(E),f(F.x,F.y,F.z)):f(S.x,S.y,h/r*K);for(N=l-1;0<=N;N--){K=N/l;L=k*Math.cos(K*Math.PI/2);P=m*Math.sin(K*Math.PI/2);O=0;for(K=Q.length;O<K;O++)S=c(Q[O],x[O],P),f(S.x,S.y,h+L);A=0;for(B=U.length;A<B;A++)for(G=U[A],Y=X[A],O=0,K=G.length;O<K;O++)S=c(G[O],Y[O],P),z?f(S.x,S.y+t[r-1].y,
t[r-1].x+L):f(S.x,S.y,h+L)}(function(){if(p){var a=0*T;for(O=0;O<W;O++)V=R[O],g(V[2]+a,V[1]+a,V[0]+a);a=T*(r+2*l);for(O=0;O<W;O++)V=R[O],g(V[0]+a,V[1]+a,V[2]+a)}else{for(O=0;O<W;O++)V=R[O],g(V[2],V[1],V[0]);for(O=0;O<W;O++)V=R[O],g(V[0]+T*r,V[1]+T*r,V[2]+T*r)}})();(function(){var a=0;e(Q,a);a+=Q.length;A=0;for(B=U.length;A<B;A++)G=U[A],e(G,a),a+=G.length})()};Da.WorldUVGenerator={generateTopUV:function(a,b,c,d){a=a.vertices;b=a[b];c=a[c];d=a[d];return[new C(b.x,b.y),new C(c.x,c.y),new C(d.x,d.y)]},
generateSideWallUV:function(a,b,c,d,e){a=a.vertices;b=a[b];c=a[c];d=a[d];e=a[e];return.01>Math.abs(b.y-c.y)?[new C(b.x,1-b.z),new C(c.x,1-c.z),new C(d.x,1-d.z),new C(e.x,1-e.z)]:[new C(b.y,1-b.z),new C(c.y,1-c.z),new C(d.y,1-d.z),new C(e.y,1-e.z)]}};Oc.prototype=Object.create(Da.prototype);Oc.prototype.constructor=Oc;Pc.prototype=Object.create(R.prototype);Pc.prototype.constructor=Pc;lb.prototype=Object.create(I.prototype);lb.prototype.constructor=lb;Qc.prototype=Object.create(R.prototype);Qc.prototype.constructor=
Qc;Tb.prototype=Object.create(I.prototype);Tb.prototype.constructor=Tb;Rc.prototype=Object.create(R.prototype);Rc.prototype.constructor=Rc;Ub.prototype=Object.create(I.prototype);Ub.prototype.constructor=Ub;Vb.prototype=Object.create(R.prototype);Vb.prototype.constructor=Vb;Wb.prototype=Object.create(I.prototype);Wb.prototype.constructor=Wb;Xb.prototype=Object.create(I.prototype);Xb.prototype.constructor=Xb;mb.prototype=Object.create(R.prototype);mb.prototype.constructor=mb;Qa.prototype=Object.create(I.prototype);
Qa.prototype.constructor=Qa;Sc.prototype=Object.create(mb.prototype);Sc.prototype.constructor=Sc;Tc.prototype=Object.create(Qa.prototype);Tc.prototype.constructor=Tc;Uc.prototype=Object.create(R.prototype);Uc.prototype.constructor=Uc;Yb.prototype=Object.create(I.prototype);Yb.prototype.constructor=Yb;var ta=Object.freeze({WireframeGeometry:Lb,ParametricGeometry:Fc,ParametricBufferGeometry:Mb,TetrahedronGeometry:Hc,TetrahedronBufferGeometry:Nb,OctahedronGeometry:Ic,OctahedronBufferGeometry:kb,IcosahedronGeometry:Jc,
IcosahedronBufferGeometry:Ob,DodecahedronGeometry:Kc,DodecahedronBufferGeometry:Pb,PolyhedronGeometry:Gc,PolyhedronBufferGeometry:xa,TubeGeometry:Lc,TubeBufferGeometry:Qb,TorusKnotGeometry:Mc,TorusKnotBufferGeometry:Rb,TorusGeometry:Nc,TorusBufferGeometry:Sb,TextGeometry:Oc,SphereGeometry:Pc,SphereBufferGeometry:lb,RingGeometry:Qc,RingBufferGeometry:Tb,PlaneGeometry:wc,PlaneBufferGeometry:ib,LatheGeometry:Rc,LatheBufferGeometry:Ub,ShapeGeometry:Vb,ShapeBufferGeometry:Wb,ExtrudeGeometry:Da,EdgesGeometry:Xb,
ConeGeometry:Sc,ConeBufferGeometry:Tc,CylinderGeometry:mb,CylinderBufferGeometry:Qa,CircleGeometry:Uc,CircleBufferGeometry:Yb,BoxGeometry:Fb,BoxBufferGeometry:hb});Zb.prototype=Object.create(Ga.prototype);Zb.prototype.constructor=Zb;Zb.prototype.isShadowMaterial=!0;$b.prototype=Object.create(Ga.prototype);$b.prototype.constructor=$b;$b.prototype.isRawShaderMaterial=!0;Ra.prototype=Object.create(X.prototype);Ra.prototype.constructor=Ra;Ra.prototype.isMeshStandardMaterial=!0;Ra.prototype.copy=function(a){X.prototype.copy.call(this,
a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;
this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};
nb.prototype=Object.create(Ra.prototype);nb.prototype.constructor=nb;nb.prototype.isMeshPhysicalMaterial=!0;nb.prototype.copy=function(a){Ra.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ha.prototype=Object.create(X.prototype);Ha.prototype.constructor=Ha;Ha.prototype.isMeshPhongMaterial=!0;Ha.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);
this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=
a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ob.prototype=Object.create(Ha.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshToonMaterial=
!0;ob.prototype.copy=function(a){Ha.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};pb.prototype=Object.create(X.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshNormalMaterial=!0;pb.prototype.copy=function(a){X.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;
this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};qb.prototype=Object.create(X.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshLambertMaterial=!0;qb.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);
this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};rb.prototype=Object.create(X.prototype);
rb.prototype.constructor=rb;rb.prototype.isLineDashedMaterial=!0;rb.prototype.copy=function(a){X.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var Zf=Object.freeze({ShadowMaterial:Zb,SpriteMaterial:bb,RawShaderMaterial:$b,ShaderMaterial:Ga,PointsMaterial:Oa,MeshPhysicalMaterial:nb,MeshStandardMaterial:Ra,MeshPhongMaterial:Ha,MeshToonMaterial:ob,MeshNormalMaterial:pb,MeshLambertMaterial:qb,
MeshDepthMaterial:Za,MeshBasicMaterial:La,LineDashedMaterial:rb,LineBasicMaterial:ka,Material:X}),hd={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},ma=new Xd;Object.assign(ya.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=hd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&
b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g=g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var p=new Uint8Array(m),k=0;k<g.length;k++)p[k]=g.charCodeAt(k);"blob"===l&&(m=new Blob([m],{type:h}));break;case "document":m=(new DOMParser).parseFromString(g,h);break;case "json":m=JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&
b(m);e.manager.itemEnd(a)},0)}catch(q){window.setTimeout(function(){d&&d(q);e.manager.itemError(a)},0)}}else{var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(c){var f=c.target.response;hd.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemError(a))},!1);void 0!==c&&n.addEventListener("progress",function(a){c(a)},!1);n.addEventListener("error",
function(b){d&&d(b);e.manager.itemError(a)},!1);void 0!==this.responseType&&(n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)n.setRequestHeader(h,this.requestHeader[h]);n.send(null)}e.manager.itemStart(a);return n},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=a;return this},setWithCredentials:function(a){this.withCredentials=
a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Je.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Kb;h.image=g;var k=new ya(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");
if(Array.isArray(a))for(var m=0,l=0,p=a.length;l<p;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=
a;return this}});Object.assign(Yd.prototype,{load:function(a,b,c,d){var e=this,f=new cb,g=new ya(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Vc.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=hd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;c=document.createElementNS("http://www.w3.org/1999/xhtml","img");
c.addEventListener("load",function(){hd.add(a,this);b&&b(this);e.manager.itemEnd(a)},!1);c.addEventListener("error",function(b){d&&d(b);e.manager.itemError(a)},!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(Zd.prototype,{load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=a;h++;
6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Xa,g=new Vc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(rd.prototype,{load:function(a,b,c,d){var e=new Vc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ea;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||0===
a.search(/^data\:image\/jpeg/);f.format=c?1022:1023;f.needsUpdate=!0;void 0!==b&&b(f)},c,d);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});fa.prototype=Object.assign(Object.create(E.prototype),{constructor:fa,isLight:!0,copy:function(a){E.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=E.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=
this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});sd.prototype=Object.assign(Object.create(fa.prototype),{constructor:sd,isHemisphereLight:!0,copy:function(a){fa.prototype.copy.call(this,
a);this.groundColor.copy(a.groundColor);return this}});Object.assign(sb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;
return a}});td.prototype=Object.assign(Object.create(sb.prototype),{constructor:td,isSpotLightShadow:!0,update:function(a){var b=2*T.RAD2DEG*a.angle,c=this.mapSize.width/this.mapSize.height;a=a.distance||500;var d=this.camera;if(b!==d.fov||c!==d.aspect||a!==d.far)d.fov=b,d.aspect=c,d.far=a,d.updateProjectionMatrix()}});ud.prototype=Object.assign(Object.create(fa.prototype),{constructor:ud,isSpotLight:!0,copy:function(a){fa.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});vd.prototype=Object.assign(Object.create(fa.prototype),{constructor:vd,isPointLight:!0,copy:function(a){fa.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});wd.prototype=Object.assign(Object.create(sb.prototype),{constructor:wd});xd.prototype=Object.assign(Object.create(fa.prototype),{constructor:xd,isDirectionalLight:!0,copy:function(a){fa.prototype.copy.call(this,
a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});yd.prototype=Object.assign(Object.create(fa.prototype),{constructor:yd,isAmbientLight:!0});zd.prototype=Object.assign(Object.create(fa.prototype),{constructor:zd,isRectAreaLight:!0,copy:function(a){fa.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=fa.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var ra={arraySlice:function(a,
b,c){return ra.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=
new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==f)}else if(void 0!==g.toArray){do g=f[d],void 0!==g&&(b.push(f.time),g.toArray(c,c.length)),f=a[e++];while(void 0!==f)}else{do g=f[d],void 0!==g&&(b.push(f.time),c.push(g)),f=a[e++];
while(void 0!==f)}}}};Object.assign(la.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=
0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=
c[a+e];return b},interpolate_:function(a,b,c,d){throw Error("call to abstract method");},intervalChanged_:function(a,b,c){}});Object.assign(la.prototype,{beforeStart_:la.prototype.copySampleValue_,afterEnd_:la.prototype.copySampleValue_});Ad.prototype=Object.assign(Object.create(la.prototype),{constructor:Ad,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=
a;g=2*b-c;break;case 2402:e=d.length-2;g=b+d[e]-d[e+1];break;default:e=a,g=c}if(void 0===h)switch(this.getSettings_().endingEnd){case 2401:f=a;h=2*c-b;break;case 2402:f=1;h=c+d[1]-d[0];break;default:f=a-1,h=b}a=.5*(c-b);d=this.valueSize;this._weightPrev=a/(b-g);this._weightNext=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,p=this._weightNext,
n=(c-b)/(d-b);c=n*n;d=c*n;b=-l*d+2*l*c-l*n;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*n+1;n=(-1-p)*d+(1.5+p)*c+.5*n;p=p*d-p*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+n*f[a+c]+p*f[m+c];return e}});Wc.prototype=Object.assign(Object.create(la.prototype),{constructor:Wc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Bd.prototype=Object.assign(Object.create(la.prototype),{constructor:Bd,
interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Wa;Wa={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Bd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Wc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Ad(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){var b;
switch(a){case 2300:b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn(b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;
case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302}},getValueSize:function(){return this.values.length/this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,
1),e=f-1),d=this.getValueSize(),this.times=ra.arraySlice(c,e,f),this.values=ra.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("invalid value size in track",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("track is empty",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("time is not a valid number",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("out of order keys",
this,f,g,e);a=!1;break}e=g}if(void 0!==b&&ra.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("value is not a valid number",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==k[0]))if(d)h=!0;else for(var m=g*c,l=m-c,p=m+c,k=0;k!==c;++k){var n=b[m+k];if(n!==b[l+k]||n!==b[p+k]){h=!0;break}}if(h){if(g!==e)for(a[e]=
a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=ra.arraySlice(a,0,e),this.values=ra.arraySlice(b,0,e*c));return this}};ac.prototype=Object.assign(Object.create(Wa),{constructor:ac,ValueTypeName:"vector"});Cd.prototype=Object.assign(Object.create(la.prototype),{constructor:Cd,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)ca.slerpFlat(e,
0,f,a-g,f,a,b);return e}});Xc.prototype=Object.assign(Object.create(Wa),{constructor:Xc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Cd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});bc.prototype=Object.assign(Object.create(Wa),{constructor:bc,ValueTypeName:"number"});Dd.prototype=Object.assign(Object.create(Wa),{constructor:Dd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,
InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Ed.prototype=Object.assign(Object.create(Wa),{constructor:Ed,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Fd.prototype=Object.assign(Object.create(Wa),{constructor:Fd,ValueTypeName:"color"});ub.prototype=Wa;Wa.constructor=ub;Object.assign(ub,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");
var b=ub._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];ra.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:ra.convertArray(a.times,Array),values:ra.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return bc;
case "vector":case "vector2":case "vector3":case "vector4":return ac;case "color":return Fd;case "quaternion":return Xc;case "bool":case "boolean":return Ed;case "string":return Dd}throw Error("Unsupported typeName: "+a);}});Object.assign(Ia,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(ub.parse(c[e]).scale(d));return new Ia(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==
e;++d)b.push(ub.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var m=ra.getKeyframeOrder(h),h=ra.sortedArray(h,1,m),k=ra.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new bc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new Ia(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(var d=
0;d<c.length;d++)if(c[d].name===b)return c[d];return null},CreateClipsFromMorphTargetSequences:function(a,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];for(m in d)a.push(Ia.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error(" no animation in JSONLoader data"),null;for(var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];ra.flattenJSON(c,
f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30,h=a.hierarchy||[],k=0;k<h.length;k++){var m=h[k].keys;if(m&&0!==m.length)if(m[0].morphTargets){for(var f={},l=0;l<m.length;l++)if(m[l].morphTargets)for(var p=0;p<m[l].morphTargets.length;p++)f[m[l].morphTargets[p]]=-1;for(var n in f){for(var q=[],x=[],p=0;p!==m[l].morphTargets.length;++p){var t=m[l];q.push(t.time);x.push(t.morphTarget===n?1:0)}d.push(new bc(".morphTargetInfluence["+n+"]",q,x))}f=f.length*
(g||1)}else l=".bones["+b[k].name+"]",c(ac,l+".position",m,"pos",d),c(Xc,l+".quaternion",m,"rot",d),c(ac,l+".scale",m,"scl",d)}return 0===d.length?null:new Ia(e,f,d)}});Object.assign(Ia.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();
return this}});Object.assign(Gd.prototype,{load:function(a,b,c,d){var e=this;(new ya(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new Zf[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==
a.metalness&&(d.metalness=a.metalness);void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&
(d.vertexColors=a.vertexColors);void 0!==a.fog&&(d.fog=a.fog);void 0!==a.shading&&(d.shading=a.shading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=
a.wireframe);void 0!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.morphTargets&&(d.morphTargets=a.morphTargets);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&
(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));
void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));
void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));if(void 0!==a.materials)for(var e=0,f=a.materials.length;e<f;e++)d.materials.push(this.parse(a.materials[e]));return d}});Object.assign($d.prototype,{load:function(a,b,c,d){var e=this;(new ya(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new I,c=a.data.index,d={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,
Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};void 0!==c&&(c=new d[c.type](c.array),b.setIndex(new W(c,1)));var e=a.data.attributes,f;for(f in e){var g=e[f],c=new d[g.type](g.array);b.addAttribute(f,new W(c,g.itemSize,g.normalized))}d=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==d)for(f=0,c=d.length;f!==c;++f)e=d[f],b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==
a&&(d=new q,void 0!==a.center&&d.fromArray(a.center),b.boundingSphere=new Aa(d,a.radius));return b}});cc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(cc.prototype,{crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=
this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},b=new J,c=new rd,d=new Gd;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var m=cc.Handlers.get(a);null!==m?a=m.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===
e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==h&&(a.anisotropy=h);b=T.generateUUID();k[b]=a;return b}var k={},m={uuid:T.generateUUID(),type:"MeshLambertMaterial"},l;for(l in e){var p=e[l];switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=p;break;case "blending":m.blending=a[p];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");
break;case "colorDiffuse":m.color=b.fromArray(p).getHex();break;case "colorSpecular":m.specular=b.fromArray(p).getHex();break;case "colorEmissive":m.emissive=b.fromArray(p).getHex();break;case "specularCoef":m.shininess=p;break;case "shading":"basic"===p.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===p.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===p.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(p,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,
e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":m.emissiveMap=h(p,e.mapEmissiveRepeat,e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(p,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;
case "mapAO":m.aoMap=h(p,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":m.bumpMap=h(p,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=p;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(p,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);
break;case "mapNormalFactor":m.normalScale=[p,p];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=h(p,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(p,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);
break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":m.roughnessMap=h(p,e.mapRoughnessRepeat,e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(p,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;
case "flipSided":m.side=1;break;case "doubleSided":m.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");m.opacity=p;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=p;break;case "vertexColors":!0===p&&(m.vertexColors=2);"face"===p&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,p)}}"MeshBasicMaterial"===
m.type&&delete m.emissive;"MeshPhongMaterial"!==m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});Object.assign(ae.prototype,{load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:cc.prototype.extractUrlBase(a),g=new ya(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+
a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(a,b){var c=new R,d=void 0!==a.scale?1/a.scale:1;(function(b){var d,g,h,k,m,l,p,n,r,x,t,z,w,y=a.faces;l=a.vertices;var B=a.normals,v=a.colors,F=0;if(void 0!==a.uvs){for(d=0;d<a.uvs.length;d++)a.uvs[d].length&&
F++;for(d=0;d<F;d++)c.faceVertexUvs[d]=[]}k=0;for(m=l.length;k<m;)d=new q,d.x=l[k++]*b,d.y=l[k++]*b,d.z=l[k++]*b,c.vertices.push(d);k=0;for(m=y.length;k<m;)if(b=y[k++],r=b&1,h=b&2,d=b&8,p=b&16,x=b&32,l=b&64,b&=128,r){r=new ua;r.a=y[k];r.b=y[k+1];r.c=y[k+3];t=new ua;t.a=y[k+1];t.b=y[k+2];t.c=y[k+3];k+=4;h&&(h=y[k++],r.materialIndex=h,t.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<F;d++)for(z=a.uvs[d],c.faceVertexUvs[d][h]=[],c.faceVertexUvs[d][h+1]=[],g=0;4>g;g++)n=y[k++],w=z[2*n],n=z[2*n+1],w=
new C(w,n),2!==g&&c.faceVertexUvs[d][h].push(w),0!==g&&c.faceVertexUvs[d][h+1].push(w);p&&(p=3*y[k++],r.normal.set(B[p++],B[p++],B[p]),t.normal.copy(r.normal));if(x)for(d=0;4>d;d++)p=3*y[k++],x=new q(B[p++],B[p++],B[p]),2!==d&&r.vertexNormals.push(x),0!==d&&t.vertexNormals.push(x);l&&(l=y[k++],l=v[l],r.color.setHex(l),t.color.setHex(l));if(b)for(d=0;4>d;d++)l=y[k++],l=v[l],2!==d&&r.vertexColors.push(new J(l)),0!==d&&t.vertexColors.push(new J(l));c.faces.push(r);c.faces.push(t)}else{r=new ua;r.a=y[k++];
r.b=y[k++];r.c=y[k++];h&&(h=y[k++],r.materialIndex=h);h=c.faces.length;if(d)for(d=0;d<F;d++)for(z=a.uvs[d],c.faceVertexUvs[d][h]=[],g=0;3>g;g++)n=y[k++],w=z[2*n],n=z[2*n+1],w=new C(w,n),c.faceVertexUvs[d][h].push(w);p&&(p=3*y[k++],r.normal.set(B[p++],B[p++],B[p]));if(x)for(d=0;3>d;d++)p=3*y[k++],x=new q(B[p++],B[p++],B[p]),r.vertexNormals.push(x);l&&(l=y[k++],r.color.setHex(v[l]));if(b)for(d=0;3>d;d++)l=y[k++],r.vertexColors.push(new J(v[l]));c.faces.push(r)}})(d);(function(){var b=void 0!==a.influencesPerVertex?
a.influencesPerVertex:2;if(a.skinWeights)for(var d=0,g=a.skinWeights.length;d<g;d+=b)c.skinWeights.push(new ga(a.skinWeights[d],1<b?a.skinWeights[d+1]:0,2<b?a.skinWeights[d+2]:0,3<b?a.skinWeights[d+3]:0));if(a.skinIndices)for(d=0,g=a.skinIndices.length;d<g;d+=b)c.skinIndices.push(new ga(a.skinIndices[d],1<b?a.skinIndices[d+1]:0,2<b?a.skinIndices[d+2]:0,3<b?a.skinIndices[d+3]:0));c.bones=a.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&
console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+c.skinWeights.length+") should match.")})();(function(b){if(void 0!==a.morphTargets)for(var d=0,g=a.morphTargets.length;d<g;d++){c.morphTargets[d]={};c.morphTargets[d].name=a.morphTargets[d].name;c.morphTargets[d].vertices=[];for(var h=c.morphTargets[d].vertices,k=a.morphTargets[d].vertices,m=0,l=k.length;m<l;m+=3){var p=new q;p.x=k[m]*b;p.y=k[m+1]*b;p.z=k[m+2]*b;h.push(p)}}if(void 0!==
a.morphColors&&0<a.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),b=c.faces,h=a.morphColors[0].colors,d=0,g=b.length;d<g;d++)b[d].color.fromArray(h,3*d)})(d);(function(){var b=[],d=[];void 0!==a.animation&&d.push(a.animation);void 0!==a.animations&&(a.animations.length?d=d.concat(a.animations):d.push(a.animations));for(var g=0;g<d.length;g++){var h=Ia.parseAnimation(d[g],c.bones);h&&b.push(h)}c.morphTargets&&(d=Ia.CreateClipsFromMorphTargetSequences(c.morphTargets,
10),b=b.concat(d));0<b.length&&(c.animations=b)})();c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};d=cc.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}});Object.assign(Ke.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new ya(e.manager)).load(a,function(c){var g=null;try{g=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+
a+".",h.message);return}c=g.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(g,b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,
c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new ae,d=new $d,e=0,f=a.length;e<f;e++){var g,h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new ta[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new ta[h.type](h.width,h.height,h.depth,h.widthSegments,
h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new ta[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new ta[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new ta[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);
break;case "SphereGeometry":case "SphereBufferGeometry":g=new ta[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=new ta[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new ta[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=
new ta[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=new ta[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=new ta[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h.data,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+
h.type+'"');continue}g.uuid=h.uuid;void 0!==h.name&&(g.name=h.name);b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Gd;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=d.parse(a[e]);c[g.uuid]=g}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=Ia.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return g.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemError(a)})}
var d=this,e={};if(void 0!==a&&0<a.length){var f=new Xd(b),g=new Vc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],m=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(m)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,
EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},e={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},f={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008},g={};if(void 0!==a)for(var h=0,k=a.length;h<k;h++){var m=a[h];void 0===m.image&&console.warn('THREE.ObjectLoader: No "image" specified for',
m.uuid);void 0===b[m.image]&&console.warn("THREE.ObjectLoader: Undefined image",m.image);var l=new ea(b[m.image]);l.needsUpdate=!0;l.uuid=m.uuid;void 0!==m.name&&(l.name=m.name);void 0!==m.mapping&&(l.mapping=c(m.mapping,d));void 0!==m.offset&&l.offset.fromArray(m.offset);void 0!==m.repeat&&l.repeat.fromArray(m.repeat);void 0!==m.wrap&&(l.wrapS=c(m.wrap[0],e),l.wrapT=c(m.wrap[1],e));void 0!==m.minFilter&&(l.minFilter=c(m.minFilter,f));void 0!==m.magFilter&&(l.magFilter=c(m.magFilter,f));void 0!==
m.anisotropy&&(l.anisotropy=m.anisotropy);void 0!==m.flipY&&(l.flipY=m.flipY);g[m.uuid]=l}return g},parseObject:function(){var a=new Q;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a)return void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a),d[a]}var g;switch(b.type){case "Scene":g=new ld;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new J(b.background));
void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Ib(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Hb(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new Ea(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=new Gb(b.left,b.right,b.top,b.bottom,
b.near,b.far);break;case "AmbientLight":g=new yd(b.color,b.intensity);break;case "DirectionalLight":g=new xd(b.color,b.intensity);break;case "PointLight":g=new vd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new zd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=new ud(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new sd(b.color,b.groundColor,b.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");
case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new nd(g,h):new wa(g,h);break;case "LOD":g=new Bc;break;case "Line":g=new Ca(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new od(e(b.geometry),f(b.material));break;case "LineSegments":g=new ha(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Jb(e(b.geometry),f(b.material));break;case "Sprite":g=new Ac(f(b.material));break;case "Group":g=new Dc;break;default:g=new E}g.uuid=b.uuid;void 0!==
b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),
void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var m=b[h];k=g.getObjectByProperty("uuid",m.object);void 0!==
k&&g.addLevel(k,m.distance)}return g}}()});Object.assign(va.prototype,{getPoint:function(){console.warn("THREE.Curve: Warning, getPoint() not implemented!");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/a));return b},getLength:function(){var a=this.getLengths();
return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.__arcLengthDivisions?this.__arcLengthDivisions:200);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),
d,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e-1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0<k)h=d-1;else{h=d;break}d=h;if(c[d]===f)return d/(e-1);g=c[d];return(d+(f-g)/(c[d+1]-g))/(e-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new q,d=[],e=[],f=[],g=new q,h=new Q,k,m;
for(k=0;k<=a;k++)m=k/a,d[k]=this.getTangentAt(m),d[k].normalize();e[0]=new q;f[0]=new q;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),p=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));p<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(T.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,
c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(T.clamp(e[0].dot(e[a]),-1,1)),c/=a,0<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}}});Sa.prototype=Object.create(va.prototype);Sa.prototype.constructor=Sa;Sa.prototype.isLineCurve=!0;Sa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);
return b};Sa.prototype.getPointAt=function(a){return this.getPoint(a)};Sa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Yc.prototype=Object.assign(Object.create(va.prototype),{constructor:Yc,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Sa(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=
b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){void 0===
a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},createPointsGeometry:function(a){a=this.getPoints(a);return this.createGeometry(a)},
createSpacedPointsGeometry:function(a){a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){for(var b=new R,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new q(e.x,e.y,e.z||0))}return b}});Na.prototype=Object.create(va.prototype);Na.prototype.constructor=Na;Na.prototype.isEllipseCurve=!0;Na.prototype.getPoint=function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)<Number.EPSILON;0>c;)c+=b;for(;c>b;)c-=b;c<Number.EPSILON&&(c=d?0:b);!0!==this.aClockwise||
d||(c=c===b?-b:c-b);b=this.aStartAngle+a*c;a=this.aX+this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new C(a,e)};xb.prototype=Object.create(va.prototype);xb.prototype.constructor=xb;xb.prototype.isSplineCurve=!0;xb.prototype.getPoint=function(a){var b=this.points,c=(b.length-1)*a;a=Math.floor(c);var c=c-a,d=b[0===a?a:a-1],e=b[a],f=b[a>b.length-
2?b.length-1:a+1],b=b[a>b.length-3?b.length-1:a+2];return new C(Le(c,d.x,e.x,f.x,b.x),Le(c,d.y,e.y,f.y,b.y))};dc.prototype=Object.create(va.prototype);dc.prototype.constructor=dc;dc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new C(wb(a,b.x,c.x,d.x,e.x),wb(a,b.y,c.y,d.y,e.y))};ec.prototype=Object.create(va.prototype);ec.prototype.constructor=ec;ec.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new C(vb(a,b.x,c.x,d.x),vb(a,b.y,c.y,d.y))};
var oe=Object.assign(Object.create(Yc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Sa(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new ec(this.currentPoint.clone(),new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,
f){a=new dc(this.currentPoint.clone(),new C(a,b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new xb(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,
c,d,e,f,g,h)},absellipse:function(a,b,c,d,e,f,g,h){a=new Na(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)}});Zc.prototype=oe;oe.constructor=Zc;yb.prototype=Object.assign(Object.create(oe),{constructor:yb,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractAllPoints:function(a){return{shape:this.getPoints(a),
holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Object.assign(be.prototype,{moveTo:function(a,b){this.currentPath=new Zc;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,
b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new yb;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,m=h.y-g.y;if(Math.abs(m)>Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Pa.isClockWise,f=this.subPaths;
if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new yb,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var p=[],n=[],q=0,x;p[q]=void 0;n[q]=[];for(var t=0,z=f.length;t<z;t++)h=f[t],x=h.getPoints(),g=e(x),(g=a?!g:g)?(!l&&p[q]&&q++,p[q]={s:new yb,p:x},p[q].s.curves=h.curves,l&&q++,n[q]=[]):n[q].push({h:h,p:x[0]});if(!p[0])return c(f);if(1<p.length){t=!1;h=[];e=0;for(f=p.length;e<f;e++)k[e]=[];e=0;for(f=p.length;e<f;e++)for(g=n[e],
l=0;l<g.length;l++){q=g[l];x=!0;for(z=0;z<p.length;z++)d(q.p,p[z].p)&&(e!==z&&h.push({froms:e,tos:z,hole:l}),x?(x=!1,k[z].push(q)):t=!0);x&&k[e].push(q)}0<h.length&&(t||(n=k))}t=0;for(e=p.length;t<e;t++)for(k=p[t].s,m.push(k),h=n[t],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return m}});Object.assign(ce.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;a=String(a).split("");var e=b/d.resolution,f=(d.boundingBox.yMax-d.boundingBox.yMin+d.underlineThickness)*
e,g=0,h=0;b=[];for(var k=0;k<a.length;k++){var m=a[k];if("\n"===m)g=0,h-=f;else{var l;l=e;var p=g,n=h;if(m=d.glyphs[m]||d.glyphs["?"]){var q=new be,x=[],t,z,w,y,B,v,C,E;if(m.o)for(var A=m._cachedOutline||(m._cachedOutline=m.o.split(" ")),H=0,I=A.length;H<I;)switch(A[H++]){case "m":t=A[H++]*l+p;z=A[H++]*l+n;q.moveTo(t,z);break;case "l":t=A[H++]*l+p;z=A[H++]*l+n;q.lineTo(t,z);break;case "q":t=A[H++]*l+p;z=A[H++]*l+n;B=A[H++]*l+p;v=A[H++]*l+n;q.quadraticCurveTo(B,v,t,z);if(y=x[x.length-1]){w=y.x;y=y.y;
for(var J=1;J<=c;J++){var N=J/c;vb(N,w,B,t);vb(N,y,v,z)}}break;case "b":if(t=A[H++]*l+p,z=A[H++]*l+n,B=A[H++]*l+p,v=A[H++]*l+n,C=A[H++]*l+p,E=A[H++]*l+n,q.bezierCurveTo(B,v,C,E,t,z),y=x[x.length-1])for(w=y.x,y=y.y,J=1;J<=c;J++)N=J/c,wb(N,w,B,C,t),wb(N,y,v,E,z)}l={offsetX:m.ha*l,path:q}}else l=void 0;g+=l.offsetX;b.push(l.path)}}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Me.prototype,{load:function(a,b,c,d){var e=this;(new ya(this.manager)).load(a,
function(a){var c;try{c=JSON.parse(a)}catch(d){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new ce(a)}});var Nd,fe={getContext:function(){void 0===Nd&&(Nd=new (window.AudioContext||window.webkitAudioContext));return Nd},setContext:function(a){Nd=a}};Object.assign(de.prototype,{load:function(a,b,c,d){var e=new ya(this.manager);e.setResponseType("arraybuffer");
e.load(a,function(a){fe.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Ne.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new Q,l=new Q;return function(q){if(a!==this||b!==q.focus||c!==q.fov||d!==q.aspect*this.aspect||e!==q.near||f!==q.far||g!==q.zoom||h!==this.eyeSep){a=this;b=q.focus;c=q.fov;d=q.aspect*this.aspect;e=q.near;f=q.far;g=q.zoom;var p=q.projectionMatrix.clone();h=this.eyeSep/2;var n=h*e/b,r=e*Math.tan(T.DEG2RAD*c*.5)/g,x,t;l.elements[12]=-h;k.elements[12]=
h;x=-r*d+n;t=r*d+n;p.elements[0]=2*e/(t-x);p.elements[8]=(t+x)/(t-x);this.cameraL.projectionMatrix.copy(p);x=-r*d-n;t=r*d-n;p.elements[0]=2*e/(t-x);p.elements[8]=(t+x)/(t-x);this.cameraR.projectionMatrix.copy(p)}this.cameraL.matrixWorld.copy(q.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(q.matrixWorld).multiply(k)}}()});Hd.prototype=Object.create(E.prototype);Hd.prototype.constructor=Hd;ee.prototype=Object.assign(Object.create(E.prototype),{constructor:ee,getInput:function(){return this.gain},
removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},
setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new q,b=new ca,c=new q,d=new q;return function(e){E.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,this.context.currentTime),e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),
e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,f.z))}}()});fc.prototype=Object.assign(Object.create(E.prototype),{constructor:fc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=
!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,
this.startTime);a.start(0,this.startTime);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.startTime=0,this.isPlaying=!1,this},connect:function(){if(0<
this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());
return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,
this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},
setVolume:function(a){this.gain.gain.value=a;return this}});ge.prototype=Object.assign(Object.create(fc.prototype),{constructor:ge,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=
a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new q;return function(b){E.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(he.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=
b[c];return a/b.length}});Object.assign(ie.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize,e=a*d+d,f=this.cumulativeWeight;if(0===f){for(f=0;f!==d;++f)c[e+f]=c[f];f=b}else f+=b,this._mixBufferRegion(c,e,0,b/f,d);this.cumulativeWeight=f},apply:function(a){var b=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=
this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){ca.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Oe.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];
void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(pa,{Composite:Oe,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new pa.Composite(a,b,c):new pa(a,
b,c)},parseTrackName:function(a){var b=/^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/.exec(a);if(!b)throw Error("cannot parse trackName at all: "+a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};if(null===b.propertyName||0===b.propertyName.length)throw Error("can not parse propertyName from trackName: "+a);return b},findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=
function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};if(c=d(a.children))return c}return null}});Object.assign(pa.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,
MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.node[this.propertyName]=
a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=
a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=
this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=pa.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error(" can not bind to material as node does not have a material",this);return}if(!a.material.materials){console.error(" can not bind to material.materials as node.material does not have a materials array",
this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error(" can not bind to bones as node does not have a skeleton",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error(" can not bind to objectName of node, undefined",this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error(" trying to bind to objectIndex of objectName, but is undefined:",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error(" trying to update property for track: "+
b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error(" can not bind to morphTargetInfluences becasuse node does not have a geometry",this);return}if(!a.geometry.morphTargets){console.error(" can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets",
this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error(" trying to update node for track: "+
this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(pa.prototype,{_getValue_unbound:pa.prototype.getValue,_setValue_unbound:pa.prototype.setValue});Object.assign(Pe.prototype,{isAnimationObjectGroup:!0,add:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._paths,g=this._parsedPaths,h=this._bindings,k=h.length,l=0,q=arguments.length;l!==q;++l){var p=
arguments[l],n=p.uuid,r=e[n];if(void 0===r){r=c++;e[n]=r;b.push(p);for(var n=0,x=k;n!==x;++n)h[n].push(new pa(p,f[n],g[n]))}else if(r<d){var t=--d,x=b[t];e[x.uuid]=r;b[r]=x;e[n]=t;b[t]=p;n=0;for(x=k;n!==x;++n){var z=h[n],w=z[r];z[r]=z[t];void 0===w&&(w=new pa(p,f[n],g[n]));z[t]=w}}else void 0!==b[r]&&console.error("Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes...")}this.nCachedObjects_=d},remove:function(a){for(var b=this._objects,
c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=arguments[g],l=k.uuid,q=d[l];if(void 0!==q&&q>=c){var p=c++,n=b[p];d[n.uuid]=q;b[q]=n;d[l]=p;b[p]=k;k=0;for(l=f;k!==l;++k){var n=e[k],r=n[q];n[q]=n[p];n[p]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,q=e[l];if(void 0!==
q)if(delete e[l],q<d){var l=--d,p=b[l],n=--c,r=b[n];e[p.uuid]=q;b[q]=p;e[r.uuid]=l;b[l]=r;b.pop();p=0;for(r=g;p!==r;++p){var x=f[p],t=x[n];x[q]=x[l];x[l]=t;x.pop()}}else for(n=--c,r=b[n],e[r.uuid]=q,b[q]=r,b.pop(),p=0,r=g;p!==r;++p)x=f[p],x[q]=x[n],x.pop()}this.nCachedObjects_=d},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;c[a]=
d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new pa(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(Qe.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=
!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?
a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=
null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,
b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||
this._mixer._root},_update:function(a,b,c,d){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;for(var e=this._propertyBindings,f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&
(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=
0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",
action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,
f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(Re.prototype,za.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var q=d[k],p=q.name,n=l[p];if(void 0===n){n=f[k];if(void 0!==n){null===
n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,h,p));continue}n=new ie(pa.create(c,p,b&&b._propertyBindings[k].binding.parsedPath),q.ValueTypeName,q.getValueSize());++n.referenceCount;this._addInactiveBinding(n,h,p)}f[k]=n;g[k].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=
a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;
this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},
_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var b=a._clip.uuid,c=this._actionsByClip,d=c[b],e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;
f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=
this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;
delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=--this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Wc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),
c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Ia.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===
e&&(e=g._clip)}if(null===e)return null;e=new Qe(this,e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?Ia.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=
0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g){var h=b[g];h.enabled&&h._update(d,a,e,f)}a=this._bindings;b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);
var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,
b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Id.prototype.clone=function(){return new Id(void 0===this.value.clone?this.value:this.value.clone())};zb.prototype=Object.create(I.prototype);zb.prototype.constructor=zb;zb.prototype.isInstancedBufferGeometry=!0;zb.prototype.addGroup=function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})};zb.prototype.copy=function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,
b[c].clone());a=a.groups;c=0;for(b=a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this};Object.defineProperties(je.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(je.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*
this.data.stride+this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+
0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});Object.defineProperty(gc.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(gc.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=
a;return this}});hc.prototype=Object.create(gc.prototype);hc.prototype.constructor=hc;hc.prototype.isInstancedInterleavedBuffer=!0;hc.prototype.copy=function(a){gc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};ic.prototype=Object.create(W.prototype);ic.prototype.constructor=ic;ic.prototype.isInstancedBufferAttribute=!0;ic.prototype.copy=function(a){W.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this};Object.assign(Se.prototype,{linePrecision:1,
set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];ke(a,this,c,
b);c.sort(Te);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)ke(a[d],this,c,b);c.sort(Te);return c}});Object.assign(Ue.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.running=!1},getElapsedTime:function(){this.getDelta();
return this.elapsedTime},getDelta:function(){var a=0;this.autoStart&&!this.running&&this.start();if(this.running){var b=("undefined"===typeof performance?Date:performance).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign(Ve.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=
Math.max(1E-6,Math.min(Math.PI-1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(T.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(We.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=
Math.sqrt(a.x*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});oa.prototype=Object.create(wa.prototype);oa.prototype.constructor=oa;oa.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};oa.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,
f=0,g=e.morphTargets.length;f<g;f++){var h=e.morphTargets[f].name.match(b);if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};oa.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};oa.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=
-1,a.directionBackwards=!0};oa.prototype.setAnimationFPS=function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};oa.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};oa.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};oa.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};oa.prototype.getAnimationTime=function(a){var b=0;
if(a=this.animationsMap[a])b=a.time;return b};oa.prototype.getAnimationDuration=function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};oa.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};oa.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};oa.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b<c;b++){var d=this.animationsList[b];
if(d.active){var e=d.duration/d.length;d.time+=d.direction*a;if(d.mirroredLoop){if(d.time>d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+T.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=
d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};$c.prototype=Object.create(E.prototype);$c.prototype.constructor=$c;$c.prototype.isImmediateRenderObject=!0;ad.prototype=Object.create(ha.prototype);ad.prototype.constructor=ad;ad.prototype.update=function(){var a=new q,b=new q,c=new Ba;return function(){var d=
["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,q=k.length;l<q;l++)for(var p=k[l],n=0,r=p.vertexNormals.length;n<r;n++){var x=p.vertexNormals[n];a.copy(h[p[d[n]]]).applyMatrix4(e);b.copy(x).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&
g.isBufferGeometry)for(d=g.attributes.position,h=g.attributes.normal,n=g=0,r=d.count;n<r;n++)a.set(d.getX(n),d.getY(n),d.getZ(n)).applyMatrix4(e),b.set(h.getX(n),h.getY(n),h.getZ(n)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0;return this}}();jc.prototype=Object.create(E.prototype);jc.prototype.constructor=jc;jc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};jc.prototype.update=
function(){var a=new q,b=new q;return function(){var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));this.cone.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)}}();kc.prototype=Object.create(ha.prototype);kc.prototype.constructor=kc;kc.prototype.getBoneList=function(a){var b=[];a&&a.isBone&&
b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,this.getBoneList(a.children[c]));return b};kc.prototype.update=function(){var a=new q,b=new Q,c=new Q;return function(){var d=this.geometry,e=d.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var f=0,g=0;f<this.bones.length;f++){var h=this.bones[f];h.parent&&h.parent.isBone&&(b.multiplyMatrices(c,h.matrixWorld),a.setFromMatrixPosition(b),e.setXYZ(g,a.x,a.y,a.z),b.multiplyMatrices(c,h.parent.matrixWorld),a.setFromMatrixPosition(b),
e.setXYZ(g+1,a.x,a.y,a.z),g+=2)}d.getAttribute("position").needsUpdate=!0}}();lc.prototype=Object.create(wa.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};lc.prototype.update=function(){this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity)};mc.prototype=Object.create(E.prototype);mc.prototype.constructor=mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose();
this.children[1].geometry.dispose();this.children[1].material.dispose()};mc.prototype.update=function(){var a=new q,b=new q;return function(){var c=this.children[0],d=this.children[1];if(this.light.target){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);var e=b.clone().sub(a);c.lookAt(e);d.lookAt(e)}c.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);d.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);
var d=.5*this.light.width,e=.5*this.light.height,c=c.geometry.getAttribute("position"),f=c.array;f[0]=d;f[1]=-e;f[2]=0;f[3]=d;f[4]=e;f[5]=0;f[6]=-d;f[7]=e;f[8]=0;f[9]=-d;f[10]=e;f[11]=0;f[12]=-d;f[13]=-e;f[14]=0;f[15]=d;f[16]=-e;f[17]=0;c.needsUpdate=!0}}();nc.prototype=Object.create(E.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};nc.prototype.update=function(){var a=new q,b=new J,c=new J;return function(){var d=
this.children[0],e=d.geometry.getAttribute("color");b.copy(this.light.color).multiplyScalar(this.light.intensity);c.copy(this.light.groundColor).multiplyScalar(this.light.intensity);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());e.needsUpdate=!0}}();bd.prototype=Object.create(ha.prototype);bd.prototype.constructor=bd;Jd.prototype=Object.create(ha.prototype);Jd.prototype.constructor=Jd;cd.prototype=Object.create(ha.prototype);
cd.prototype.constructor=cd;cd.prototype.update=function(){var a=new q,b=new q,c=new Ba;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<l;k++){var q=f[k],p=q.normal;a.copy(g[q.a]).add(g[q.b]).add(g[q.c]).divideScalar(3).applyMatrix4(d);b.copy(p).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,
a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0;return this}}();oc.prototype=Object.create(E.prototype);oc.prototype.constructor=oc;oc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};oc.prototype.update=function(){var a=new q,b=new q,c=new q;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,
a);var d=this.children[0],e=this.children[1];d.lookAt(c);d.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);e.lookAt(c);e.scale.z=c.length()}}();dd.prototype=Object.create(ha.prototype);dd.prototype.constructor=dd;dd.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new q,e=new da;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);
a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",0,1,-1);b.getAttribute("position").needsUpdate=!0}}();pc.prototype=Object.create(ha.prototype);pc.prototype.constructor=pc;pc.prototype.update=function(){var a=new Ua;return function(b){b&&
b.isBox3?a.copy(b):a.setFromObject(b);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();var Kd,le;Ab.prototype=Object.create(E.prototype);Ab.prototype.constructor=Ab;Ab.prototype.setDirection=
function(){var a=new q,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Ab.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Ab.prototype.setColor=function(a){this.line.material.color.copy(a);
this.cone.material.color.copy(a)};Ld.prototype=Object.create(ha.prototype);Ld.prototype.constructor=Ld;var Od=new q,pe=new me,qe=new me,re=new me;sa.prototype=Object.create(va.prototype);sa.prototype.constructor=sa;sa.prototype.getPoint=function(a){var b=this.points,c=b.length;2>c&&console.log("duh, you need at least 2 points");a*=c-(this.closed?0:1);var d=Math.floor(a);a-=d;this.closed?d+=0<d?0:(Math.floor(Math.abs(d)/b.length)+1)*b.length:0===a&&d===c-1&&(d=c-2,a=1);var e,f,g;this.closed||0<d?e=
b[(d-1)%c]:(Od.subVectors(b[0],b[1]).add(b[0]),e=Od);f=b[d%c];g=b[(d+1)%c];this.closed||d+2<c?b=b[(d+2)%c]:(Od.subVectors(b[c-1],b[c-2]).add(b[c-1]),b=Od);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var h="chordal"===this.type?.5:.25,c=Math.pow(e.distanceToSquared(f),h),d=Math.pow(f.distanceToSquared(g),h),h=Math.pow(g.distanceToSquared(b),h);1E-4>d&&(d=1);1E-4>c&&(c=d);1E-4>h&&(h=d);pe.initNonuniformCatmullRom(e.x,f.x,g.x,b.x,c,d,h);qe.initNonuniformCatmullRom(e.y,f.y,
g.y,b.y,c,d,h);re.initNonuniformCatmullRom(e.z,f.z,g.z,b.z,c,d,h)}else"catmullrom"===this.type&&(c=void 0!==this.tension?this.tension:.5,pe.initCatmullRom(e.x,f.x,g.x,b.x,c),qe.initCatmullRom(e.y,f.y,g.y,b.y,c),re.initCatmullRom(e.z,f.z,g.z,b.z,c));return new q(pe.calc(a),qe.calc(a),re.calc(a))};ed.prototype=Object.create(va.prototype);ed.prototype.constructor=ed;ed.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new q(wb(a,b.x,c.x,d.x,e.x),wb(a,b.y,c.y,d.y,e.y),
wb(a,b.z,c.z,d.z,e.z))};fd.prototype=Object.create(va.prototype);fd.prototype.constructor=fd;fd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new q(vb(a,b.x,c.x,d.x),vb(a,b.y,c.y,d.y),vb(a,b.z,c.z,d.z))};gd.prototype=Object.create(va.prototype);gd.prototype.constructor=gd;gd.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=new q;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b};Md.prototype=Object.create(Na.prototype);Md.prototype.constructor=
Md;va.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(va.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Xe.prototype=Object.create(sa.prototype);Ye.prototype=Object.create(sa.prototype);ne.prototype=Object.create(sa.prototype);Object.assign(ne.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(a){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},
reparametrizeByArcLength:function(a){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});bd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};Object.assign(id.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},
isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Ua.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},
isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});Eb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");
return this.getCenter(a)};T.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(Ba.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},
multiplyVector3Array:function(a){console.warn("THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");return this.applyToVector3Array(a)},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,b,c){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(Q.prototype,
{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;return function(){void 0===a&&(a=new q);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,
3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");
return a.applyMatrix4(this)},multiplyVector3Array:function(a){console.warn("THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.");return this.applyToVector3Array(a)},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");
return a.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.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,b,c){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});ia.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
ca.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(eb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},
isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(yb.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new Da(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Vb(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,
b,c){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(q.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(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");
return this.setFromMatrixPosition(a)},getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},
fromAttribute:function(a,b,c){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(ga.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});R.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(E.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(E.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");
this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Bc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Cc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Ea.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(fa.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");
this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");
this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");
this.shadow.bias=a}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.");this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(W.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");
return this.array.length}}});Object.assign(I.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},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.")}});Object.defineProperties(I.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(Id.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(X.prototype,{skinning:{get:function(){console.warn("THREE.Material: .skinning has been removed.")},set:function(){console.warn("THREE.Material: .skinning has been removed.")}},wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},
set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new J}}});Object.defineProperties(Ha.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(Ga.prototype,
{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Vd.prototype,{supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},
supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");
return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},
addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Vd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");
this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(De.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Bb.prototype,
{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");
return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");
return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},
set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");
this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});fc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new de).load(a,function(a){b.setBuffer(a)});return this};
he.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Cb;l.WebGLRenderTarget=Bb;l.WebGLRenderer=Vd;l.ShaderLib=$a;l.UniformsLib=N;l.UniformsUtils=Ja;l.ShaderChunk=Y;l.FogExp2=Hb;l.Fog=Ib;l.Scene=ld;l.LensFlare=Wd;l.Sprite=Ac;l.LOD=Bc;l.SkinnedMesh=nd;l.Skeleton=Cc;l.Bone=md;l.Mesh=wa;l.LineSegments=ha;l.LineLoop=od;l.Line=Ca;l.Points=Jb;l.Group=Dc;l.VideoTexture=pd;l.DataTexture=cb;l.CompressedTexture=
Kb;l.CubeTexture=Xa;l.CanvasTexture=qd;l.DepthTexture=Ec;l.Texture=ea;l.CompressedTextureLoader=Je;l.DataTextureLoader=Yd;l.CubeTextureLoader=Zd;l.TextureLoader=rd;l.ObjectLoader=Ke;l.MaterialLoader=Gd;l.BufferGeometryLoader=$d;l.DefaultLoadingManager=ma;l.LoadingManager=Xd;l.JSONLoader=ae;l.ImageLoader=Vc;l.FontLoader=Me;l.FileLoader=ya;l.Loader=cc;l.Cache=hd;l.AudioLoader=de;l.SpotLightShadow=td;l.SpotLight=ud;l.PointLight=vd;l.RectAreaLight=zd;l.HemisphereLight=sd;l.DirectionalLightShadow=wd;l.DirectionalLight=
xd;l.AmbientLight=yd;l.LightShadow=sb;l.Light=fa;l.StereoCamera=Ne;l.PerspectiveCamera=Ea;l.OrthographicCamera=Gb;l.CubeCamera=Hd;l.Camera=da;l.AudioListener=ee;l.PositionalAudio=ge;l.AudioContext=fe;l.AudioAnalyser=he;l.Audio=fc;l.VectorKeyframeTrack=ac;l.StringKeyframeTrack=Dd;l.QuaternionKeyframeTrack=Xc;l.NumberKeyframeTrack=bc;l.ColorKeyframeTrack=Fd;l.BooleanKeyframeTrack=Ed;l.PropertyMixer=ie;l.PropertyBinding=pa;l.KeyframeTrack=ub;l.AnimationUtils=ra;l.AnimationObjectGroup=Pe;l.AnimationMixer=
Re;l.AnimationClip=Ia;l.Uniform=Id;l.InstancedBufferGeometry=zb;l.BufferGeometry=I;l.GeometryIdCount=function(){return Sd++};l.Geometry=R;l.InterleavedBufferAttribute=je;l.InstancedInterleavedBuffer=hc;l.InterleavedBuffer=gc;l.InstancedBufferAttribute=ic;l.Face3=ua;l.Object3D=E;l.Raycaster=Se;l.Layers=Qd;l.EventDispatcher=za;l.Clock=Ue;l.QuaternionLinearInterpolant=Cd;l.LinearInterpolant=Wc;l.DiscreteInterpolant=Bd;l.CubicInterpolant=Ad;l.Interpolant=la;l.Triangle=Ka;l.Math=T;l.Spherical=Ve;l.Cylindrical=
We;l.Plane=ia;l.Frustum=jd;l.Sphere=Aa;l.Ray=eb;l.Matrix4=Q;l.Matrix3=Ba;l.Box3=Ua;l.Box2=id;l.Line3=Eb;l.Euler=ab;l.Vector4=ga;l.Vector3=q;l.Vector2=C;l.Quaternion=ca;l.Color=J;l.MorphBlendMesh=oa;l.ImmediateRenderObject=$c;l.VertexNormalsHelper=ad;l.SpotLightHelper=jc;l.SkeletonHelper=kc;l.PointLightHelper=lc;l.RectAreaLightHelper=mc;l.HemisphereLightHelper=nc;l.GridHelper=bd;l.PolarGridHelper=Jd;l.FaceNormalsHelper=cd;l.DirectionalLightHelper=oc;l.CameraHelper=dd;l.BoxHelper=pc;l.ArrowHelper=Ab;
l.AxisHelper=Ld;l.CatmullRomCurve3=sa;l.CubicBezierCurve3=ed;l.QuadraticBezierCurve3=fd;l.LineCurve3=gd;l.ArcCurve=Md;l.EllipseCurve=Na;l.SplineCurve=xb;l.CubicBezierCurve=dc;l.QuadraticBezierCurve=ec;l.LineCurve=Sa;l.Shape=yb;l.Path=Zc;l.ShapePath=be;l.Font=ce;l.CurvePath=Yc;l.Curve=va;l.ShapeUtils=Pa;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Dc,d=0,e=b.length;d<e;d++)c.add(new wa(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},
attach:function(a,b,c){var d=new Q;d.getInverse(c.matrixWorld);a.applyMatrix(d);b.remove(a);c.add(a)}};l.WireframeGeometry=Lb;l.ParametricGeometry=Fc;l.ParametricBufferGeometry=Mb;l.TetrahedronGeometry=Hc;l.TetrahedronBufferGeometry=Nb;l.OctahedronGeometry=Ic;l.OctahedronBufferGeometry=kb;l.IcosahedronGeometry=Jc;l.IcosahedronBufferGeometry=Ob;l.DodecahedronGeometry=Kc;l.DodecahedronBufferGeometry=Pb;l.PolyhedronGeometry=Gc;l.PolyhedronBufferGeometry=xa;l.TubeGeometry=Lc;l.TubeBufferGeometry=Qb;l.TorusKnotGeometry=
Mc;l.TorusKnotBufferGeometry=Rb;l.TorusGeometry=Nc;l.TorusBufferGeometry=Sb;l.TextGeometry=Oc;l.SphereGeometry=Pc;l.SphereBufferGeometry=lb;l.RingGeometry=Qc;l.RingBufferGeometry=Tb;l.PlaneGeometry=wc;l.PlaneBufferGeometry=ib;l.LatheGeometry=Rc;l.LatheBufferGeometry=Ub;l.ShapeGeometry=Vb;l.ShapeBufferGeometry=Wb;l.ExtrudeGeometry=Da;l.EdgesGeometry=Xb;l.ConeGeometry=Sc;l.ConeBufferGeometry=Tc;l.CylinderGeometry=mb;l.CylinderBufferGeometry=Qa;l.CircleGeometry=Uc;l.CircleBufferGeometry=Yb;l.BoxGeometry=
Fb;l.BoxBufferGeometry=hb;l.ShadowMaterial=Zb;l.SpriteMaterial=bb;l.RawShaderMaterial=$b;l.ShaderMaterial=Ga;l.PointsMaterial=Oa;l.MeshPhysicalMaterial=nb;l.MeshStandardMaterial=Ra;l.MeshPhongMaterial=Ha;l.MeshToonMaterial=ob;l.MeshNormalMaterial=pb;l.MeshLambertMaterial=qb;l.MeshDepthMaterial=Za;l.MeshBasicMaterial=La;l.LineDashedMaterial=rb;l.LineBasicMaterial=ka;l.Material=X;l.Float64BufferAttribute=vc;l.Float32BufferAttribute=B;l.Uint32BufferAttribute=gb;l.Int32BufferAttribute=uc;l.Uint16BufferAttribute=
fb;l.Int16BufferAttribute=tc;l.Uint8ClampedBufferAttribute=sc;l.Uint8BufferAttribute=rc;l.Int8BufferAttribute=qc;l.BufferAttribute=W;l.REVISION="85dev";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=
0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=
1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=
307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=
1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=2001;l.RGBA_S3TC_DXT1_Format=2002;l.RGBA_S3TC_DXT3_Format=2003;l.RGBA_S3TC_DXT5_Format=2004;l.RGB_PVRTC_4BPPV1_Format=2100;l.RGB_PVRTC_2BPPV1_Format=2101;l.RGBA_PVRTC_4BPPV1_Format=2102;l.RGBA_PVRTC_2BPPV1_Format=2103;l.RGB_ETC1_Format=2151;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=
2300;l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=Fb;l.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");
return new ua(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Jb(a,b)};l.Particle=
function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Ac(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Jb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.ParticleSystemMaterial=
function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Oa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new q(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new W(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");
return new qc(a,b)};l.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new rc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new sc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new tc(a,b)};l.Uint16Attribute=
function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new fb(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new uc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new gb(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");
return new B(a,b)};l.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new vc(a,b)};l.ClosedSplineCurve3=Xe;l.SplineCurve3=Ye;l.Spline=ne;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new pc(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new ha(new Xb(a.geometry),
new ka({color:void 0!==b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new ha(new Lb(a.geometry),new ka({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new ya(a)};l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new Yd(a)};l.GeometryUtils=
{merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var d;b.isMesh&&(b.matrixAutoUpdate&&b.updateMatrix(),d=b.matrix,b=b.geometry);a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};l.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");
var e=new rd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");var e=new Zd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};
l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};l.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");
this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(l,"__esModule",{value:!0})});
|
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SHAPE_VECTOR_H_
#define _SHAPE_VECTOR_H_
#ifndef _SCENE_OBJECT_H_
#include "2d/sceneobject/SceneObject.h"
#endif
//-----------------------------------------------------------------------------
class ShapeVector : public SceneObject
{
typedef SceneObject Parent;
protected:
ColorF mLineColor;
ColorF mFillColor;
bool mFillMode;
Vector2 mPolygonScale; ///< Polygon Scale.
Vector<Vector2> mPolygonBasisList; ///< Polygon Basis List.
Vector<Vector2> mPolygonLocalList; ///< Polygon Local List.
bool mIsCircle;
F32 mCircleRadius;
bool mFlipX;
bool mFlipY;
public:
ShapeVector();
~ShapeVector();
static void initPersistFields();
/// Polygon Configuration.
void setPolyScale( const Vector2& scale );
void setPolyPrimitive( const U32 polyVertexCount );
void setPolyCustom( const U32 polyVertexCount, const char* pCustomPolygon );
U32 getPolyVertexCount( void ) { return U32(mPolygonBasisList.size()); };
inline const Vector2* getPolyBasis( void ) const { return &(mPolygonBasisList[0]); };
const char* getPoly( void );
const char* getWorldPoly( void );
inline void setLineColor( const ColorF& linecolor ) { mLineColor = linecolor; }
inline const ColorF& getLineColor( void ) const { return mLineColor; }
inline void setLineAlpha( const F32 alpha ) { mLineColor.alpha = alpha; }
inline void setFillColor( const ColorF& fillcolor ) { mFillColor = fillcolor; }
inline const ColorF& getFillColor( void ) const { return mFillColor; }
inline void setFillAlpha( const F32 alpha ) { mFillColor.alpha = alpha; }
inline void setFillMode( const bool fillMode ) { mFillMode = fillMode; }
inline bool getFillMode( void ) const { return mFillMode; }
inline void setIsCircle( const bool isCircle ) { mIsCircle = isCircle; }
inline bool getIsCircle( void ) const { return mIsCircle; }
inline void setCircleRadius( const F32 circleRadius ) { mCircleRadius = circleRadius; }
inline F32 getCircleRadius ( void ) const { return mCircleRadius; }
Vector2 getBoxFromPoints( void );
/// Internal Crunchers.
void generateLocalPoly( void );
void renderCircleShape(Vector2 position, F32 radius);
void renderPolygonShape(U32 vertexCount);
/// Render flipping.
inline void setFlip( const bool flipX, const bool flipY ) { mFlipX = flipX; mFlipY = flipY; generateLocalPoly(); }
inline void setFlipX( const bool flipX ) { setFlip( flipX, mFlipY ); }
inline void setFlipY( const bool flipY ) { setFlip( mFlipX, flipY ); }
inline bool getFlipX(void) const { return mFlipX; }
inline bool getFlipY(void) const { return mFlipY; }
virtual void setSize( const Vector2& size );
/// Core.
virtual bool onAdd();
virtual void onRemove();
virtual void sceneRender( const SceneRenderState* pSceneRenderState, const SceneRenderRequest* pSceneRenderRequest, BatchRender* pBatchRenderer );
virtual bool validRender( void ) const { return (mPolygonLocalList.size() > 0 || mIsCircle); }
virtual bool shouldRender( void ) const { return true; }
/// Render batching.
virtual bool isBatchRendered( void ) { return false; }
/// Clone support
void copyTo(SimObject* obj);
/// Declare Console Object.
DECLARE_CONOBJECT(ShapeVector);
protected:
static bool setPolyList(void* obj, const char* data)
{
const U32 count = Utility::mGetStringElementCount(data) >> 1;
static_cast<ShapeVector*>(obj)->setPolyCustom(count, data);
return false;
}
static bool writePolyList( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mPolygonBasisList.size() > 0; }
static bool writeLineColor( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mLineColor != ColorF(1.0f,1.0f,1.0f,1.0f); }
static bool writeFillColor( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mFillColor != ColorF(0.5f,0.5f,0.5f,1.0f); }
static bool writeFillMode( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mFillMode == true; }
static bool writeIsCircle( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mIsCircle == true; }
static bool writeCircleRadius( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mCircleRadius != 1; }
};
#endif // _SHAPE_VECTOR_H_
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare
class StockScrap(models.Model):
_name = 'stock.scrap'
_inherit = ['mail.thread']
_order = 'id desc'
_description = 'Scrap'
def _get_default_scrap_location_id(self):
company_id = self.env.context.get('default_company_id') or self.env.company.id
return self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [company_id, False])], limit=1).id
def _get_default_location_id(self):
company_id = self.env.context.get('default_company_id') or self.env.company.id
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1)
if warehouse:
return warehouse.lot_stock_id.id
return None
name = fields.Char(
'Reference', default=lambda self: _('New'),
copy=False, readonly=True, required=True,
states={'done': [('readonly', True)]})
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company, required=True, states={'done': [('readonly', True)]})
origin = fields.Char(string='Source Document')
product_id = fields.Many2one(
'product.product', 'Product', domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
required=True, states={'done': [('readonly', True)]}, check_company=True)
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
required=True, states={'done': [('readonly', True)]}, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
tracking = fields.Selection('Product Tracking', readonly=True, related="product_id.tracking")
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial',
states={'done': [('readonly', True)]}, domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True)
package_id = fields.Many2one(
'stock.quant.package', 'Package',
states={'done': [('readonly', True)]}, check_company=True)
owner_id = fields.Many2one('res.partner', 'Owner', states={'done': [('readonly', True)]}, check_company=True)
move_id = fields.Many2one('stock.move', 'Scrap Move', readonly=True, check_company=True)
picking_id = fields.Many2one('stock.picking', 'Picking', states={'done': [('readonly', True)]}, check_company=True)
location_id = fields.Many2one(
'stock.location', 'Source Location', domain="[('usage', '=', 'internal'), ('company_id', 'in', [company_id, False])]",
required=True, states={'done': [('readonly', True)]}, default=_get_default_location_id, check_company=True)
scrap_location_id = fields.Many2one(
'stock.location', 'Scrap Location', default=_get_default_scrap_location_id,
domain="[('scrap_location', '=', True), ('company_id', 'in', [company_id, False])]", required=True, states={'done': [('readonly', True)]}, check_company=True)
scrap_qty = fields.Float('Quantity', default=1.0, required=True, states={'done': [('readonly', True)]})
state = fields.Selection([
('draft', 'Draft'),
('done', 'Done')],
string='Status', default="draft", readonly=True, tracking=True)
date_done = fields.Datetime('Date', readonly=True)
@api.onchange('picking_id')
def _onchange_picking_id(self):
if self.picking_id:
self.location_id = (self.picking_id.state == 'done') and self.picking_id.location_dest_id.id or self.picking_id.location_id.id
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
if self.tracking == 'serial':
self.scrap_qty = 1
self.product_uom_id = self.product_id.uom_id.id
# Check if we can get a more precise location instead of
# the default location (a location corresponding to where the
# reserved product is stored)
if self.picking_id:
for move_line in self.picking_id.move_line_ids:
if move_line.product_id == self.product_id:
self.location_id = move_line.location_id if move_line.state != 'done' else move_line.location_dest_id
break
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
# Change the locations only if their company doesn't match the company set, otherwise
# user defaults are overridden.
if self.location_id.company_id != self.company_id:
self.location_id = warehouse.lot_stock_id
if self.scrap_location_id.company_id != self.company_id:
self.scrap_location_id = self.env['stock.location'].search([
('scrap_location', '=', True),
('company_id', 'in', [self.company_id.id, False]),
], limit=1)
else:
self.location_id = False
self.scrap_location_id = False
def unlink(self):
if 'done' in self.mapped('state'):
raise UserError(_('You cannot delete a scrap which is done.'))
return super(StockScrap, self).unlink()
def _get_origin_moves(self):
return self.picking_id and self.picking_id.move_lines.filtered(lambda x: x.product_id == self.product_id)
def _prepare_move_values(self):
self.ensure_one()
location_id = self.location_id.id
if self.picking_id and self.picking_id.picking_type_code == 'incoming':
location_id = self.picking_id.location_dest_id.id
return {
'name': self.name,
'origin': self.origin or self.picking_id.name or self.name,
'company_id': self.company_id.id,
'product_id': self.product_id.id,
'product_uom': self.product_uom_id.id,
'state': 'draft',
'product_uom_qty': self.scrap_qty,
'location_id': location_id,
'scrapped': True,
'location_dest_id': self.scrap_location_id.id,
'move_line_ids': [(0, 0, {'product_id': self.product_id.id,
'product_uom_id': self.product_uom_id.id,
'qty_done': self.scrap_qty,
'location_id': location_id,
'location_dest_id': self.scrap_location_id.id,
'package_id': self.package_id.id,
'owner_id': self.owner_id.id,
'lot_id': self.lot_id.id, })],
# 'restrict_partner_id': self.owner_id.id,
'picking_id': self.picking_id.id
}
def do_scrap(self):
self._check_company()
for scrap in self:
scrap.name = self.env['ir.sequence'].next_by_code('stock.scrap') or _('New')
move = self.env['stock.move'].create(scrap._prepare_move_values())
# master: replace context by cancel_backorder
move.with_context(is_scrap=True)._action_done()
scrap.write({'move_id': move.id, 'state': 'done'})
scrap.date_done = fields.Datetime.now()
return True
def action_get_stock_picking(self):
action = self.env.ref('stock.action_picking_tree_all').read([])[0]
action['domain'] = [('id', '=', self.picking_id.id)]
return action
def action_get_stock_move_lines(self):
action = self.env.ref('stock.stock_move_line_action').read([])[0]
action['domain'] = [('move_id', '=', self.move_id.id)]
return action
def action_validate(self):
self.ensure_one()
if self.product_id.type != 'product':
return self.do_scrap()
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
location_id = self.location_id
if self.picking_id and self.picking_id.picking_type_code == 'incoming':
location_id = self.picking_id.location_dest_id
available_qty = sum(self.env['stock.quant']._gather(self.product_id,
location_id,
self.lot_id,
self.package_id,
self.owner_id,
strict=True).mapped('quantity'))
scrap_qty = self.product_uom_id._compute_quantity(self.scrap_qty, self.product_id.uom_id)
if float_compare(available_qty, scrap_qty, precision_digits=precision) >= 0:
return self.do_scrap()
else:
ctx = dict(self.env.context)
ctx.update({
'default_product_id': self.product_id.id,
'default_location_id': self.location_id.id,
'default_scrap_id': self.id
})
return {
'name': _('Insufficient Quantity'),
'view_mode': 'form',
'res_model': 'stock.warn.insufficient.qty.scrap',
'view_id': self.env.ref('stock.stock_warn_insufficient_qty_scrap_form_view').id,
'type': 'ir.actions.act_window',
'context': ctx,
'target': 'new'
}
|
#pragma once
#include "Board.h"
#include "Marble.h"
#include "Deck.h"
#include "Player.h"
#include "CardList.h"
#include "Game.h"
#include "GameLog.h"
#include "Move.h"
#include "MoveList.h"
#include "PlayerColor.h"
#include "MarbleColor.h"
std::string ComputerPlayerDescription(TGMPlayer* player);
std::string MarbleDescription(TGMMarble *marble);
std::string BoardDescription(TGMBoard *board);
std::string BoardDescriptionWithCustomBreaker(TGMBoard *board, int8_t breaker);
std::string CardListDescription(TGMCardList *cardList, bool detailed);
std::string DeckDescription(TGMDeck *deck);
std::string GameFeedbackStats(TGMGame* game);
std::string ColoredString(PlayerColor color, const char* str);
std::string CardDescription(TGMCard *card, bool shortDescription);
std::string GameLogDescription(TGMGameLog* gameLog);
std::string MoveShortDescription(TGMMove* move, bool withCard);
std::string MoveDescription(TGMMove* move);
std::string MoveListDescription(TGMMoveList *moveList);
std::string PlayerDescription(TGMPlayer* player);
std::string CardSuitDescription(CardSuit suit);
std::string PlayerColorToShortString(PlayerColor color);
const char * PlayerColorToString(PlayerColor color);
std::string MarbleColorToShortString(MarbleColor color);
std::string CardNumberToString(CardNumber card);
std::string GameStateToString(GameState state);
std::string CardSuitToString(CardSuit suit);
std::string StrategyToString(Strategy strategy);
std::string GameStateToString(GameState state);
|
from electronics_abstract_parts import *
from .PassiveResistor import ESeriesResistor, ChipResistor, AxialResistor, AxialVerticalResistor
from .PassiveCapacitor import SmtCeramicCapacitor, SmtCeramicCapacitorGeneric
from .PassiveInductor import SmtInductor
from .Leds import SmtLed, ThtLed, IndicatorLed, VoltageIndicatorLed, SmtRgbLed, ThtRgbLed, IndicatorSinkRgbLed
from .Diodes import SmtDiode, SmtZenerDiode
from .Fets import SmtNFet, SmtPFet, SmtSwitchNFet, SmtSwitchPFet
from .Batteries import Cr2032, Li18650
from .Switches import SmtSwitch, SmtSwitchRa
from .Crystals import OscillatorCrystal, SmdCrystal
from .Speakers import Speaker, Lm4871
from .Opamp_Mcp6001 import Mcp6001
from .DebugHeaders import SwdCortexTargetHeader, SwdCortexTargetTc2050, SwdCortexTargetTc2050Nl
from .DebugHeaders import SwdCortexSourceHeaderHorizontal
from .SdCards import SdCard, SdSocket, MicroSdSocket
from .LinearRegulators import Ld1117, Ld1117_Device, Ldl1117, Ldl1117_Device, Ap2204k_Device, Ap2204k_Block, Ap2204k
from .DcDcConverters import Tps561201, Tps561201_Device, Tps54202h, Tps54202h_Device
from .DcDcConverters import Lmr33630, Lmr33630_Device
from .DcDcConverters import Ap3012, Ap3012_Device # TODO remove _Device blocks
from .PowerConditioning import BufferedSupply, Supercap, SingleDiodePowerMerge, DiodePowerMerge
from .Microcontroller_Lpc1549 import Lpc1549_48, Lpc1549_64
from .Microcontroller_Stm32f103 import Stm32f103_48_Device, Stm32f103_48
from .Microcontroller_Nucleo32 import Nucleo_F303k8
from .PowerConnectors import PowerBarrelJack, Pj_102a
from .UsbPorts import UsbConnector, UsbAReceptacle, UsbCReceptacle, UsbEsdDiode, UsbDeviceConnector, UsbMicroBReceptacle, UsbDeviceCReceptacle
from .Rtc_Pcf2129 import Pcf2129
from .RfModules import Xbee_S3b, BlueSmirf
from .Lcd_Qt096t_if09 import Qt096t_if09
from .Oled_Nhd_312_25664uc import Nhd_312_25664uc
from .EInk_E2154fs091 import E2154fs091
from .Iso1050 import Iso1050dub
from .CalSolBlocks import CalSolCanBlock, CalSolPowerConnector
from .CalSolBlocks import CalSolCanConnector, CalSolCanConnectorRa, M12CanConnector, CanEsdDiode
from .Labels import DuckLogo, LeadFreeIndicator, IdDots4
from .Mechanicals import Outline_Pn1332
from .Mechanicals import MountingHole, MountingHole_M2_5, MountingHole_M3, MountingHole_M4
from .Mechanicals import MountingHole_NoPad_M2_5
|
/**
*
* @copyright © 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der
* angewandten Forschung e.V. All rights reserved.
*
* BSD 3-Clause License
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* We kindly request you to use one or more of the following phrases to refer
* to foxBMS in your hardware, software, documentation or advertising
* materials:
*
* ″This product uses parts of foxBMS®″
*
* ″This product includes parts of foxBMS®″
*
* ″This product is derived from foxBMS®″
*
*/
/**
* @file led_cfg.h
* @author foxBMS Team
* @date 12.09.2018 (date of creation)
* @ingroup X_INGROUP
* @prefix LED
*
* @brief Defines the used CPU
*
*/
#ifndef LED_CFG_H_
#define LED_CFG_H_
/*================== Includes ===============================================*/
#include "general.h"
#include "io_mcu_cfg.h"
/*================== Macros and Definitions =================================*/
#define LED_DEBUG_LED_0 IO_PIN_MCU_1_DEBUG_LED_0
#define LED_DEBUG_LED_1 IO_PIN_MCU_1_DEBUG_LED_1
/**
* Blinking time in milliseconds
*/
#define LED_BLINK_TASK_DURATION_MS 10
/**
* LED off time in milliseconds
*/
#define LED_OFF_TIME_MS 100
/*================== Extern Constant and Variable Declarations ==============*/
/*================== Extern Function Prototypes =============================*/
#endif /* LED_CFG_H_ */
|
const INITIAL_STATE = {
name: '',
image: '',
email: '',
password: '',
admin_id: null,
typeOfAccess: '',
isAuthenticate: false,
loading: false,
error: false,
success: false,
};
export default (state = INITIAL_STATE, action) => {
if (action.type === 'POST_USER_AUTH_REQUEST') {
return {
isAuthenticate: false,
loading: true,
success: false,
error: false,
};
}
if (action.type === 'POST_USER_AUTH_SUCCESS') {
return {
loading: false,
success: true,
error: false,
isAuthenticate: true,
name: action.data.name,
image: action.data.image,
email: action.data.email,
password: action.data.password,
admin_id: null,
typeOfAccess: action.data.typeOfAccess,
};
}
if (action.type === 'POST_USER_AUTH_FAILURE') {
return {
isAuthenticate: false,
loading: false,
success: false,
error: true,
};
}
return state;
};
|
'''
请实现一个函数用来匹配包括'.'和'*'的正则表达式。
模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。
在本题中,匹配是指字符串的所有字符匹配整个模式。
例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
'''
class Solution(object):
# s,pattern都是字符串
def match(self, s, pattern):
if not s or not pattern:
return False
# 如果s和pattern匹配, 直接True
if s==pattern:
return True
# 如果pattern为'', 因为s和pattern不相等, 直接False
elif pattern=='':
return False
# 当s为'', 如果pattern为'.', 则返回True
# 当s为'', 如果pattern长度为1且不为'.', 或者pattern第二个字符不是*, 则pattern不可能为空, 返回False
# 若pattern长度不为1, 且第二个字符为*, pattern还有空的可能, 从第三个字符开始迭代
elif s=="":
if pattern==".":
return True
elif len(pattern)==1 or pattern[1]!="*":
return False
else:
return self.match(s, pattern[2:])
# 如果pattern长度不小于二, 而且pattern的第二个字符不是*的情况下
# 当 pattern[0] 不等于s[0], 且不为 . 的时候, s和pattern必不相等
# 否则, s 和 pattern 都右移一位, 继续比较
if len(pattern)>=2 and pattern[1]!="*":
if s[0]!=pattern[0] and pattern[0]!=".":
return False
else:
return self.match(s[1:], pattern[1:])
# 如果pattern长度不小于2, 且pattern第二个字符为*的情况下
# 如果s[0]不等于pattern[0], 且pattern[0]不为 . , 那么第一位比较不成功, pattern必须后移两位继续比较后面是否能和s第一位匹配
# 如果s[0]等于pattern[0], 或者pattern[0]为 . , 第一位匹配, 那么会有
# 1. aaa 和 a*a 这种情况, 星号代表了多个a, 因此s需要不断右移一位继续比较
# 2. a 和 a*a 中这情况, 这时候星号代表0个a, 因此s不需要右移, pattern需要右移两位
# 3. abc 和 a*bc 这种情况, 星号代表了1个a, s右移一位, pattern右移两位继续比较
elif len(pattern)>=2 and pattern[1]=="*":
if s[0]!=pattern[0] and pattern[0]!=".":
return self.match(s, pattern[2:])
else:
return self.match(s[1:], pattern) or self.match(s, pattern[2:]) or self.match(s[1:], pattern[2:])
# 除去上述pattern不小于2情况, 只剩下pattern等于1的情况, 因此如果pattern为".", 而且s长度为1, 返回True
elif pattern=="." and len(s)==1:
return True
return False
def match(self, s, pattern):
pass
class Solution2(object):
def match(self, s, p):
s, p = '#'+s, '#'+p
m, n = len(s), len(p)
print(m, n, "*"*10)
dp = [[False]*n for _ in range(m)]
dp[0][0] = True
for i in range(m):
for j in range(1, n):
if i == 0:
dp[i][j] = j > 1 and p[j] == '*' and dp[i][j-2]
elif p[j] in [s[i], '.']:
dp[i][j] = dp[i-1][j-1]
elif p[j] == '*':
dp[i][j] = j > 1 and dp[i][j-2] or p[j-1] in [s[i], '.'] and dp[i-1][j]
else:
dp[i][j] = False
return dp[-1][-1]
def match1(self, s, p):
s, p='#'+s, "#"+p
m, n=len(s), len(p)
dp=[[False]*n for _ in range(m)]
dp[0][0]=True
for i in range(m):
for j in range(1, n):
if i==0:
dp[i][j]=j>1 and p[j]=="*" and dp[i][j-2]
elif p[j] in [s[i], '.']:
dp[i][j]=dp[i-1][j-1]
elif p[j]=="*":
dp[i][j]=j>1 and dp[i][j-2] or p[j-1] in [s[i], "."] and dp[i-1][j]
else:
dp[i][j]=False
return dp[-1][-1]
def match2(self, s, p):
s, p="#"+s, "#"+p
m, n=len(s), len(p)
dp=[[False]*n for _ in range(m)]
dp[0][0]=True
for i in range(m):
for j in range(1, n):
if i==0:
dp[i][j]=j>1 and p[j]=="*" and dp[i][j-2]
elif p[j] in [s[j], "."]:
dp[i][j]=dp[i-1][j-1]
elif p[j]=="*":
dp[i][j]=j>1 and dp[i][j-2] or p[j-1] in [s[i], '.'] and dp[i-1][j]
else:
dp[i][j]=False
return dp[-1][-1]
s = Solution2()
print(s.match1('', ""))
|
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
|
# coding: utf-8
"""
Cisco Intersight OpenAPI specification.
The Cisco Intersight OpenAPI specification.
OpenAPI spec version: 1.0.9-1461
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class TopSystem(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'account_moid': 'str',
'create_time': 'datetime',
'domain_group_moid': 'str',
'mod_time': 'datetime',
'moid': 'str',
'object_type': 'str',
'owners': 'list[str]',
'shared_scope': 'str',
'tags': 'list[MoTag]',
'version_context': 'MoVersionContext',
'ancestors': 'list[MoBaseMoRef]',
'parent': 'MoBaseMoRef',
'permission_resources': 'list[MoBaseMoRef]',
'device_mo_id': 'str',
'dn': 'str',
'rn': 'str',
'ipv4_address': 'str',
'ipv6_address': 'str',
'mode': 'str',
'name': 'str',
'time_zone': 'str',
'compute_blades': 'list[ComputeBladeRef]',
'compute_rack_units': 'list[ComputeRackUnitRef]',
'management_controller': 'ManagementControllerRef',
'network_elements': 'list[NetworkElementRef]',
'registered_device': 'AssetDeviceRegistrationRef'
}
attribute_map = {
'account_moid': 'AccountMoid',
'create_time': 'CreateTime',
'domain_group_moid': 'DomainGroupMoid',
'mod_time': 'ModTime',
'moid': 'Moid',
'object_type': 'ObjectType',
'owners': 'Owners',
'shared_scope': 'SharedScope',
'tags': 'Tags',
'version_context': 'VersionContext',
'ancestors': 'Ancestors',
'parent': 'Parent',
'permission_resources': 'PermissionResources',
'device_mo_id': 'DeviceMoId',
'dn': 'Dn',
'rn': 'Rn',
'ipv4_address': 'Ipv4Address',
'ipv6_address': 'Ipv6Address',
'mode': 'Mode',
'name': 'Name',
'time_zone': 'TimeZone',
'compute_blades': 'ComputeBlades',
'compute_rack_units': 'ComputeRackUnits',
'management_controller': 'ManagementController',
'network_elements': 'NetworkElements',
'registered_device': 'RegisteredDevice'
}
def __init__(self, account_moid=None, create_time=None, domain_group_moid=None, mod_time=None, moid=None, object_type=None, owners=None, shared_scope=None, tags=None, version_context=None, ancestors=None, parent=None, permission_resources=None, device_mo_id=None, dn=None, rn=None, ipv4_address=None, ipv6_address=None, mode=None, name=None, time_zone=None, compute_blades=None, compute_rack_units=None, management_controller=None, network_elements=None, registered_device=None):
"""
TopSystem - a model defined in Swagger
"""
self._account_moid = None
self._create_time = None
self._domain_group_moid = None
self._mod_time = None
self._moid = None
self._object_type = None
self._owners = None
self._shared_scope = None
self._tags = None
self._version_context = None
self._ancestors = None
self._parent = None
self._permission_resources = None
self._device_mo_id = None
self._dn = None
self._rn = None
self._ipv4_address = None
self._ipv6_address = None
self._mode = None
self._name = None
self._time_zone = None
self._compute_blades = None
self._compute_rack_units = None
self._management_controller = None
self._network_elements = None
self._registered_device = None
if account_moid is not None:
self.account_moid = account_moid
if create_time is not None:
self.create_time = create_time
if domain_group_moid is not None:
self.domain_group_moid = domain_group_moid
if mod_time is not None:
self.mod_time = mod_time
if moid is not None:
self.moid = moid
if object_type is not None:
self.object_type = object_type
if owners is not None:
self.owners = owners
if shared_scope is not None:
self.shared_scope = shared_scope
if tags is not None:
self.tags = tags
if version_context is not None:
self.version_context = version_context
if ancestors is not None:
self.ancestors = ancestors
if parent is not None:
self.parent = parent
if permission_resources is not None:
self.permission_resources = permission_resources
if device_mo_id is not None:
self.device_mo_id = device_mo_id
if dn is not None:
self.dn = dn
if rn is not None:
self.rn = rn
if ipv4_address is not None:
self.ipv4_address = ipv4_address
if ipv6_address is not None:
self.ipv6_address = ipv6_address
if mode is not None:
self.mode = mode
if name is not None:
self.name = name
if time_zone is not None:
self.time_zone = time_zone
if compute_blades is not None:
self.compute_blades = compute_blades
if compute_rack_units is not None:
self.compute_rack_units = compute_rack_units
if management_controller is not None:
self.management_controller = management_controller
if network_elements is not None:
self.network_elements = network_elements
if registered_device is not None:
self.registered_device = registered_device
@property
def account_moid(self):
"""
Gets the account_moid of this TopSystem.
The Account ID for this managed object.
:return: The account_moid of this TopSystem.
:rtype: str
"""
return self._account_moid
@account_moid.setter
def account_moid(self, account_moid):
"""
Sets the account_moid of this TopSystem.
The Account ID for this managed object.
:param account_moid: The account_moid of this TopSystem.
:type: str
"""
self._account_moid = account_moid
@property
def create_time(self):
"""
Gets the create_time of this TopSystem.
The time when this managed object was created.
:return: The create_time of this TopSystem.
:rtype: datetime
"""
return self._create_time
@create_time.setter
def create_time(self, create_time):
"""
Sets the create_time of this TopSystem.
The time when this managed object was created.
:param create_time: The create_time of this TopSystem.
:type: datetime
"""
self._create_time = create_time
@property
def domain_group_moid(self):
"""
Gets the domain_group_moid of this TopSystem.
The DomainGroup ID for this managed object.
:return: The domain_group_moid of this TopSystem.
:rtype: str
"""
return self._domain_group_moid
@domain_group_moid.setter
def domain_group_moid(self, domain_group_moid):
"""
Sets the domain_group_moid of this TopSystem.
The DomainGroup ID for this managed object.
:param domain_group_moid: The domain_group_moid of this TopSystem.
:type: str
"""
self._domain_group_moid = domain_group_moid
@property
def mod_time(self):
"""
Gets the mod_time of this TopSystem.
The time when this managed object was last modified.
:return: The mod_time of this TopSystem.
:rtype: datetime
"""
return self._mod_time
@mod_time.setter
def mod_time(self, mod_time):
"""
Sets the mod_time of this TopSystem.
The time when this managed object was last modified.
:param mod_time: The mod_time of this TopSystem.
:type: datetime
"""
self._mod_time = mod_time
@property
def moid(self):
"""
Gets the moid of this TopSystem.
The unique identifier of this Managed Object instance.
:return: The moid of this TopSystem.
:rtype: str
"""
return self._moid
@moid.setter
def moid(self, moid):
"""
Sets the moid of this TopSystem.
The unique identifier of this Managed Object instance.
:param moid: The moid of this TopSystem.
:type: str
"""
self._moid = moid
@property
def object_type(self):
"""
Gets the object_type of this TopSystem.
The fully-qualified type of this managed object, i.e. the class name. This property is optional. The ObjectType is implied from the URL path. If specified, the value of objectType must match the class name specified in the URL path.
:return: The object_type of this TopSystem.
:rtype: str
"""
return self._object_type
@object_type.setter
def object_type(self, object_type):
"""
Sets the object_type of this TopSystem.
The fully-qualified type of this managed object, i.e. the class name. This property is optional. The ObjectType is implied from the URL path. If specified, the value of objectType must match the class name specified in the URL path.
:param object_type: The object_type of this TopSystem.
:type: str
"""
self._object_type = object_type
@property
def owners(self):
"""
Gets the owners of this TopSystem.
The array of owners which represent effective ownership of this object.
:return: The owners of this TopSystem.
:rtype: list[str]
"""
return self._owners
@owners.setter
def owners(self, owners):
"""
Sets the owners of this TopSystem.
The array of owners which represent effective ownership of this object.
:param owners: The owners of this TopSystem.
:type: list[str]
"""
self._owners = owners
@property
def shared_scope(self):
"""
Gets the shared_scope of this TopSystem.
Intersight provides pre-built workflows, tasks and policies to end users through global catalogs. Objects that are made available through global catalogs are said to have a 'shared' ownership. Shared objects are either made globally available to all end users or restricted to end users based on their license entitlement. Users can use this property to differentiate the scope (global or a specific license tier) to which a shared MO belongs.
:return: The shared_scope of this TopSystem.
:rtype: str
"""
return self._shared_scope
@shared_scope.setter
def shared_scope(self, shared_scope):
"""
Sets the shared_scope of this TopSystem.
Intersight provides pre-built workflows, tasks and policies to end users through global catalogs. Objects that are made available through global catalogs are said to have a 'shared' ownership. Shared objects are either made globally available to all end users or restricted to end users based on their license entitlement. Users can use this property to differentiate the scope (global or a specific license tier) to which a shared MO belongs.
:param shared_scope: The shared_scope of this TopSystem.
:type: str
"""
self._shared_scope = shared_scope
@property
def tags(self):
"""
Gets the tags of this TopSystem.
The array of tags, which allow to add key, value meta-data to managed objects.
:return: The tags of this TopSystem.
:rtype: list[MoTag]
"""
return self._tags
@tags.setter
def tags(self, tags):
"""
Sets the tags of this TopSystem.
The array of tags, which allow to add key, value meta-data to managed objects.
:param tags: The tags of this TopSystem.
:type: list[MoTag]
"""
self._tags = tags
@property
def version_context(self):
"""
Gets the version_context of this TopSystem.
The versioning info for this managed object.
:return: The version_context of this TopSystem.
:rtype: MoVersionContext
"""
return self._version_context
@version_context.setter
def version_context(self, version_context):
"""
Sets the version_context of this TopSystem.
The versioning info for this managed object.
:param version_context: The version_context of this TopSystem.
:type: MoVersionContext
"""
self._version_context = version_context
@property
def ancestors(self):
"""
Gets the ancestors of this TopSystem.
The array containing the MO references of the ancestors in the object containment hierarchy.
:return: The ancestors of this TopSystem.
:rtype: list[MoBaseMoRef]
"""
return self._ancestors
@ancestors.setter
def ancestors(self, ancestors):
"""
Sets the ancestors of this TopSystem.
The array containing the MO references of the ancestors in the object containment hierarchy.
:param ancestors: The ancestors of this TopSystem.
:type: list[MoBaseMoRef]
"""
self._ancestors = ancestors
@property
def parent(self):
"""
Gets the parent of this TopSystem.
The direct ancestor of this managed object in the containment hierarchy.
:return: The parent of this TopSystem.
:rtype: MoBaseMoRef
"""
return self._parent
@parent.setter
def parent(self, parent):
"""
Sets the parent of this TopSystem.
The direct ancestor of this managed object in the containment hierarchy.
:param parent: The parent of this TopSystem.
:type: MoBaseMoRef
"""
self._parent = parent
@property
def permission_resources(self):
"""
Gets the permission_resources of this TopSystem.
A slice of all permission resources (organizations) associated with this object. Permission ties resources and its associated roles/privileges. These resources which can be specified in a permission is PermissionResource. Currently only organizations can be specified in permission. All logical and physical resources part of an organization will have organization in PermissionResources field. If DeviceRegistration contains another DeviceRegistration and if parent is in org1 and child is part of org2, then child objects will have PermissionResources as org1 and org2. Parent Objects will have PermissionResources as org1. All profiles/policies created with in an organization will have the organization as PermissionResources.
:return: The permission_resources of this TopSystem.
:rtype: list[MoBaseMoRef]
"""
return self._permission_resources
@permission_resources.setter
def permission_resources(self, permission_resources):
"""
Sets the permission_resources of this TopSystem.
A slice of all permission resources (organizations) associated with this object. Permission ties resources and its associated roles/privileges. These resources which can be specified in a permission is PermissionResource. Currently only organizations can be specified in permission. All logical and physical resources part of an organization will have organization in PermissionResources field. If DeviceRegistration contains another DeviceRegistration and if parent is in org1 and child is part of org2, then child objects will have PermissionResources as org1 and org2. Parent Objects will have PermissionResources as org1. All profiles/policies created with in an organization will have the organization as PermissionResources.
:param permission_resources: The permission_resources of this TopSystem.
:type: list[MoBaseMoRef]
"""
self._permission_resources = permission_resources
@property
def device_mo_id(self):
"""
Gets the device_mo_id of this TopSystem.
:return: The device_mo_id of this TopSystem.
:rtype: str
"""
return self._device_mo_id
@device_mo_id.setter
def device_mo_id(self, device_mo_id):
"""
Sets the device_mo_id of this TopSystem.
:param device_mo_id: The device_mo_id of this TopSystem.
:type: str
"""
self._device_mo_id = device_mo_id
@property
def dn(self):
"""
Gets the dn of this TopSystem.
The Distinguished Name unambiguously identifies an object in the system.
:return: The dn of this TopSystem.
:rtype: str
"""
return self._dn
@dn.setter
def dn(self, dn):
"""
Sets the dn of this TopSystem.
The Distinguished Name unambiguously identifies an object in the system.
:param dn: The dn of this TopSystem.
:type: str
"""
self._dn = dn
@property
def rn(self):
"""
Gets the rn of this TopSystem.
The Relative Name uniquely identifies an object within a given context.
:return: The rn of this TopSystem.
:rtype: str
"""
return self._rn
@rn.setter
def rn(self, rn):
"""
Sets the rn of this TopSystem.
The Relative Name uniquely identifies an object within a given context.
:param rn: The rn of this TopSystem.
:type: str
"""
self._rn = rn
@property
def ipv4_address(self):
"""
Gets the ipv4_address of this TopSystem.
The IPv4 address of system.
:return: The ipv4_address of this TopSystem.
:rtype: str
"""
return self._ipv4_address
@ipv4_address.setter
def ipv4_address(self, ipv4_address):
"""
Sets the ipv4_address of this TopSystem.
The IPv4 address of system.
:param ipv4_address: The ipv4_address of this TopSystem.
:type: str
"""
self._ipv4_address = ipv4_address
@property
def ipv6_address(self):
"""
Gets the ipv6_address of this TopSystem.
The IPv6 address of system.
:return: The ipv6_address of this TopSystem.
:rtype: str
"""
return self._ipv6_address
@ipv6_address.setter
def ipv6_address(self, ipv6_address):
"""
Sets the ipv6_address of this TopSystem.
The IPv6 address of system.
:param ipv6_address: The ipv6_address of this TopSystem.
:type: str
"""
self._ipv6_address = ipv6_address
@property
def mode(self):
"""
Gets the mode of this TopSystem.
:return: The mode of this TopSystem.
:rtype: str
"""
return self._mode
@mode.setter
def mode(self, mode):
"""
Sets the mode of this TopSystem.
:param mode: The mode of this TopSystem.
:type: str
"""
self._mode = mode
@property
def name(self):
"""
Gets the name of this TopSystem.
:return: The name of this TopSystem.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""
Sets the name of this TopSystem.
:param name: The name of this TopSystem.
:type: str
"""
self._name = name
@property
def time_zone(self):
"""
Gets the time_zone of this TopSystem.
The operational timezone of the system, empty indicates no timezone has been set specifically.
:return: The time_zone of this TopSystem.
:rtype: str
"""
return self._time_zone
@time_zone.setter
def time_zone(self, time_zone):
"""
Sets the time_zone of this TopSystem.
The operational timezone of the system, empty indicates no timezone has been set specifically.
:param time_zone: The time_zone of this TopSystem.
:type: str
"""
self._time_zone = time_zone
@property
def compute_blades(self):
"""
Gets the compute_blades of this TopSystem.
:return: The compute_blades of this TopSystem.
:rtype: list[ComputeBladeRef]
"""
return self._compute_blades
@compute_blades.setter
def compute_blades(self, compute_blades):
"""
Sets the compute_blades of this TopSystem.
:param compute_blades: The compute_blades of this TopSystem.
:type: list[ComputeBladeRef]
"""
self._compute_blades = compute_blades
@property
def compute_rack_units(self):
"""
Gets the compute_rack_units of this TopSystem.
:return: The compute_rack_units of this TopSystem.
:rtype: list[ComputeRackUnitRef]
"""
return self._compute_rack_units
@compute_rack_units.setter
def compute_rack_units(self, compute_rack_units):
"""
Sets the compute_rack_units of this TopSystem.
:param compute_rack_units: The compute_rack_units of this TopSystem.
:type: list[ComputeRackUnitRef]
"""
self._compute_rack_units = compute_rack_units
@property
def management_controller(self):
"""
Gets the management_controller of this TopSystem.
:return: The management_controller of this TopSystem.
:rtype: ManagementControllerRef
"""
return self._management_controller
@management_controller.setter
def management_controller(self, management_controller):
"""
Sets the management_controller of this TopSystem.
:param management_controller: The management_controller of this TopSystem.
:type: ManagementControllerRef
"""
self._management_controller = management_controller
@property
def network_elements(self):
"""
Gets the network_elements of this TopSystem.
:return: The network_elements of this TopSystem.
:rtype: list[NetworkElementRef]
"""
return self._network_elements
@network_elements.setter
def network_elements(self, network_elements):
"""
Sets the network_elements of this TopSystem.
:param network_elements: The network_elements of this TopSystem.
:type: list[NetworkElementRef]
"""
self._network_elements = network_elements
@property
def registered_device(self):
"""
Gets the registered_device of this TopSystem.
The Device to which this Managed Object is associated.
:return: The registered_device of this TopSystem.
:rtype: AssetDeviceRegistrationRef
"""
return self._registered_device
@registered_device.setter
def registered_device(self, registered_device):
"""
Sets the registered_device of this TopSystem.
The Device to which this Managed Object is associated.
:param registered_device: The registered_device of this TopSystem.
:type: AssetDeviceRegistrationRef
"""
self._registered_device = registered_device
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, TopSystem):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
import React from 'react';
import { IndexRoute, Route, Redirect } from 'react-router';
import ViewerQuery from './ViewerQuery';
import { AppContainer, MainContainer } from '../relay/containers';
import { SignupContainer, LoginContainer, ExportContainer } from '../ui/containers';
export default (
<Route path='/' component={AppContainer} queries={ViewerQuery}>
<IndexRoute component={MainContainer} queries={ViewerQuery} />
<Route path='/signup' component={SignupContainer} />
<Route path='/login' component={LoginContainer} />
<Redirect from='*' to='/' />
</Route>
);
|
# Generated by Django 3.2.4 on 2021-10-01 19:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Postinfo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('desc', models.TextField()),
],
),
]
|
#!/usr/bin/env python3
# Copyright (c) 2018-2019 The Talkcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the Partially Signed Transaction RPCs.
"""
from decimal import Decimal
from test_framework.test_framework import TalkcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes_bi,
disconnect_nodes,
find_output,
)
import json
import os
MAX_BIP125_RBF_SEQUENCE = 0xfffffffd
# Create one-input, one-output, no-fee transaction:
class PSBTTest(TalkcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = False
self.num_nodes = 3
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def test_utxo_conversion(self):
mining_node = self.nodes[2]
offline_node = self.nodes[0]
online_node = self.nodes[1]
# Disconnect offline node from others
disconnect_nodes(offline_node, 1)
disconnect_nodes(online_node, 0)
disconnect_nodes(offline_node, 2)
disconnect_nodes(mining_node, 0)
# Mine a transaction that credits the offline address
offline_addr = offline_node.getnewaddress(address_type="p2sh-segwit")
online_addr = online_node.getnewaddress(address_type="p2sh-segwit")
online_node.importaddress(offline_addr, "", False)
mining_node.sendtoaddress(address=offline_addr, amount=1.0)
mining_node.generate(nblocks=1)
self.sync_blocks([mining_node, online_node])
# Construct an unsigned PSBT on the online node (who doesn't know the output is Segwit, so will include a non-witness UTXO)
utxos = online_node.listunspent(addresses=[offline_addr])
raw = online_node.createrawtransaction([{"txid":utxos[0]["txid"], "vout":utxos[0]["vout"]}],[{online_addr:0.9999}])
psbt = online_node.walletprocesspsbt(online_node.converttopsbt(raw))["psbt"]
assert "non_witness_utxo" in mining_node.decodepsbt(psbt)["inputs"][0]
# Have the offline node sign the PSBT (which will update the UTXO to segwit)
signed_psbt = offline_node.walletprocesspsbt(psbt)["psbt"]
assert "witness_utxo" in mining_node.decodepsbt(signed_psbt)["inputs"][0]
# Make sure we can mine the resulting transaction
txid = mining_node.sendrawtransaction(mining_node.finalizepsbt(signed_psbt)["hex"])
mining_node.generate(1)
self.sync_blocks([mining_node, online_node])
assert_equal(online_node.gettxout(txid,0)["confirmations"], 1)
# Reconnect
connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 0, 2)
def run_test(self):
# Create and fund a raw tx for sending 10 TALK
psbtx1 = self.nodes[0].walletcreatefundedpsbt([], {self.nodes[2].getnewaddress():10})['psbt']
# Node 1 should not be able to add anything to it but still return the psbtx same as before
psbtx = self.nodes[1].walletprocesspsbt(psbtx1)['psbt']
assert_equal(psbtx1, psbtx)
# Sign the transaction and send
signed_tx = self.nodes[0].walletprocesspsbt(psbtx)['psbt']
final_tx = self.nodes[0].finalizepsbt(signed_tx)['hex']
self.nodes[0].sendrawtransaction(final_tx)
# Create p2sh, p2wpkh, and p2wsh addresses
pubkey0 = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())['pubkey']
pubkey1 = self.nodes[1].getaddressinfo(self.nodes[1].getnewaddress())['pubkey']
pubkey2 = self.nodes[2].getaddressinfo(self.nodes[2].getnewaddress())['pubkey']
p2sh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "legacy")['address']
p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "bech32")['address']
p2sh_p2wsh = self.nodes[1].addmultisigaddress(2, [pubkey0, pubkey1, pubkey2], "", "p2sh-segwit")['address']
p2wpkh = self.nodes[1].getnewaddress("", "bech32")
p2pkh = self.nodes[1].getnewaddress("", "legacy")
p2sh_p2wpkh = self.nodes[1].getnewaddress("", "p2sh-segwit")
# fund those addresses
rawtx = self.nodes[0].createrawtransaction([], {p2sh:10, p2wsh:10, p2wpkh:10, p2sh_p2wsh:10, p2sh_p2wpkh:10, p2pkh:10})
rawtx = self.nodes[0].fundrawtransaction(rawtx, {"changePosition":3})
signed_tx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])['hex']
txid = self.nodes[0].sendrawtransaction(signed_tx)
self.nodes[0].generate(6)
self.sync_all()
# Find the output pos
p2sh_pos = -1
p2wsh_pos = -1
p2wpkh_pos = -1
p2pkh_pos = -1
p2sh_p2wsh_pos = -1
p2sh_p2wpkh_pos = -1
decoded = self.nodes[0].decoderawtransaction(signed_tx)
for out in decoded['vout']:
if out['scriptPubKey']['addresses'][0] == p2sh:
p2sh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wsh:
p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2wpkh:
p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wsh:
p2sh_p2wsh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2sh_p2wpkh:
p2sh_p2wpkh_pos = out['n']
elif out['scriptPubKey']['addresses'][0] == p2pkh:
p2pkh_pos = out['n']
# spend single key from node 1
rawtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wpkh_pos},{"txid":txid,"vout":p2sh_p2wpkh_pos},{"txid":txid,"vout":p2pkh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(rawtx)
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[1].sendrawtransaction(self.nodes[1].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# partially sign multisig things with node 1
psbtx = self.nodes[1].walletcreatefundedpsbt([{"txid":txid,"vout":p2wsh_pos},{"txid":txid,"vout":p2sh_pos},{"txid":txid,"vout":p2sh_p2wsh_pos}], {self.nodes[1].getnewaddress():29.99})['psbt']
walletprocesspsbt_out = self.nodes[1].walletprocesspsbt(psbtx)
psbtx = walletprocesspsbt_out['psbt']
assert_equal(walletprocesspsbt_out['complete'], False)
# partially sign with node 2. This should be complete and sendable
walletprocesspsbt_out = self.nodes[2].walletprocesspsbt(psbtx)
assert_equal(walletprocesspsbt_out['complete'], True)
self.nodes[2].sendrawtransaction(self.nodes[2].finalizepsbt(walletprocesspsbt_out['psbt'])['hex'])
# check that walletprocesspsbt fails to decode a non-psbt
rawtx = self.nodes[1].createrawtransaction([{"txid":txid,"vout":p2wpkh_pos}], {self.nodes[1].getnewaddress():9.99})
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[1].walletprocesspsbt, rawtx)
# Convert a non-psbt to psbt and make sure we can decode it
rawtx = self.nodes[0].createrawtransaction([], {self.nodes[1].getnewaddress():10})
rawtx = self.nodes[0].fundrawtransaction(rawtx)
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Make sure that a non-psbt with signatures cannot be converted
# Error could be either "TX decode failed" (segwit inputs causes parsing to fail) or "Inputs must not have scriptSigs and scriptWitnesses"
# We must set iswitness=True because the serialized transaction has inputs and is therefore a witness transaction
signedtx = self.nodes[0].signrawtransactionwithwallet(rawtx['hex'])
assert_raises_rpc_error(-22, "", self.nodes[0].converttopsbt, hexstring=signedtx['hex'], iswitness=True)
assert_raises_rpc_error(-22, "", self.nodes[0].converttopsbt, hexstring=signedtx['hex'], permitsigdata=False, iswitness=True)
# Unless we allow it to convert and strip signatures
self.nodes[0].converttopsbt(signedtx['hex'], True)
# Explicitly allow converting non-empty txs
new_psbt = self.nodes[0].converttopsbt(rawtx['hex'])
self.nodes[0].decodepsbt(new_psbt)
# Create outputs to nodes 1 and 2
node1_addr = self.nodes[1].getnewaddress()
node2_addr = self.nodes[2].getnewaddress()
txid1 = self.nodes[0].sendtoaddress(node1_addr, 13)
txid2 = self.nodes[0].sendtoaddress(node2_addr, 13)
blockhash = self.nodes[0].generate(6)[0]
self.sync_all()
vout1 = find_output(self.nodes[1], txid1, 13, blockhash=blockhash)
vout2 = find_output(self.nodes[2], txid2, 13, blockhash=blockhash)
# Create a psbt spending outputs from nodes 1 and 2
psbt_orig = self.nodes[0].createpsbt([{"txid":txid1, "vout":vout1}, {"txid":txid2, "vout":vout2}], {self.nodes[0].getnewaddress():25.999})
# Update psbts, should only have data for one input and not the other
psbt1 = self.nodes[1].walletprocesspsbt(psbt_orig)['psbt']
psbt1_decoded = self.nodes[0].decodepsbt(psbt1)
assert psbt1_decoded['inputs'][0] and not psbt1_decoded['inputs'][1]
psbt2 = self.nodes[2].walletprocesspsbt(psbt_orig)['psbt']
psbt2_decoded = self.nodes[0].decodepsbt(psbt2)
assert not psbt2_decoded['inputs'][0] and psbt2_decoded['inputs'][1]
# Combine, finalize, and send the psbts
combined = self.nodes[0].combinepsbt([psbt1, psbt2])
finalized = self.nodes[0].finalizepsbt(combined)['hex']
self.nodes[0].sendrawtransaction(finalized)
self.nodes[0].generate(6)
self.sync_all()
# Test additional args in walletcreatepsbt
# Make sure both pre-included and funded inputs
# have the correct sequence numbers based on
# replaceable arg
block_height = self.nodes[0].getblockcount()
unspent = self.nodes[0].listunspent()[0]
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height+2, {"replaceable":True}, False)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert_equal(tx_in["sequence"], MAX_BIP125_RBF_SEQUENCE)
assert "bip32_derivs" not in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height+2)
# Same construction with only locktime set
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height, {}, True)
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in, psbt_in in zip(decoded_psbt["tx"]["vin"], decoded_psbt["inputs"]):
assert tx_in["sequence"] > MAX_BIP125_RBF_SEQUENCE
assert "bip32_derivs" in psbt_in
assert_equal(decoded_psbt["tx"]["locktime"], block_height)
# Same construction without optional arguments
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}])
decoded_psbt = self.nodes[0].decodepsbt(psbtx_info["psbt"])
for tx_in in decoded_psbt["tx"]["vin"]:
assert tx_in["sequence"] > MAX_BIP125_RBF_SEQUENCE
assert_equal(decoded_psbt["tx"]["locktime"], 0)
# Make sure change address wallet does not have P2SH innerscript access to results in success
# when attempting BnB coin selection
self.nodes[0].walletcreatefundedpsbt([], [{self.nodes[2].getnewaddress():unspent["amount"]+1}], block_height+2, {"changeAddress":self.nodes[1].getnewaddress()}, False)
# Regression test for 14473 (mishandling of already-signed witness transaction):
psbtx_info = self.nodes[0].walletcreatefundedpsbt([{"txid":unspent["txid"], "vout":unspent["vout"]}], [{self.nodes[2].getnewaddress():unspent["amount"]+1}])
complete_psbt = self.nodes[0].walletprocesspsbt(psbtx_info["psbt"])
double_processed_psbt = self.nodes[0].walletprocesspsbt(complete_psbt["psbt"])
assert_equal(complete_psbt, double_processed_psbt)
# We don't care about the decode result, but decoding must succeed.
self.nodes[0].decodepsbt(double_processed_psbt["psbt"])
# BIP 174 Test Vectors
# Check that unknown values are just passed through
unknown_psbt = "cHNidP8BAD8CAAAAAf//////////////////////////////////////////AAAAAAD/////AQAAAAAAAAAAA2oBAAAAAAAACg8BAgMEBQYHCAkPAQIDBAUGBwgJCgsMDQ4PAAA="
unknown_out = self.nodes[0].walletprocesspsbt(unknown_psbt)['psbt']
assert_equal(unknown_psbt, unknown_out)
# Open the data file
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_psbt.json'), encoding='utf-8') as f:
d = json.load(f)
invalids = d['invalid']
valids = d['valid']
creators = d['creator']
signers = d['signer']
combiners = d['combiner']
finalizers = d['finalizer']
extractors = d['extractor']
# Invalid PSBTs
for invalid in invalids:
assert_raises_rpc_error(-22, "TX decode failed", self.nodes[0].decodepsbt, invalid)
# Valid PSBTs
for valid in valids:
self.nodes[0].decodepsbt(valid)
# Creator Tests
for creator in creators:
created_tx = self.nodes[0].createpsbt(creator['inputs'], creator['outputs'])
assert_equal(created_tx, creator['result'])
# Signer tests
for i, signer in enumerate(signers):
self.nodes[2].createwallet("wallet{}".format(i))
wrpc = self.nodes[2].get_wallet_rpc("wallet{}".format(i))
for key in signer['privkeys']:
wrpc.importprivkey(key)
signed_tx = wrpc.walletprocesspsbt(signer['psbt'])['psbt']
assert_equal(signed_tx, signer['result'])
# Combiner test
for combiner in combiners:
combined = self.nodes[2].combinepsbt(combiner['combine'])
assert_equal(combined, combiner['result'])
# Empty combiner test
assert_raises_rpc_error(-8, "Parameter 'txs' cannot be empty", self.nodes[0].combinepsbt, [])
# Finalizer test
for finalizer in finalizers:
finalized = self.nodes[2].finalizepsbt(finalizer['finalize'], False)['psbt']
assert_equal(finalized, finalizer['result'])
# Extractor test
for extractor in extractors:
extracted = self.nodes[2].finalizepsbt(extractor['extract'], True)['hex']
assert_equal(extracted, extractor['result'])
# Unload extra wallets
for i, signer in enumerate(signers):
self.nodes[2].unloadwallet("wallet{}".format(i))
self.test_utxo_conversion()
# Test that psbts with p2pkh outputs are created properly
p2pkh = self.nodes[0].getnewaddress(address_type='legacy')
psbt = self.nodes[1].walletcreatefundedpsbt([], [{p2pkh : 1}], 0, {"includeWatching" : True}, True)
self.nodes[0].decodepsbt(psbt['psbt'])
# Test decoding error: invalid base64
assert_raises_rpc_error(-22, "TX decode failed invalid base64", self.nodes[0].decodepsbt, ";definitely not base64;")
# Send to all types of addresses
addr1 = self.nodes[1].getnewaddress("", "bech32")
txid1 = self.nodes[0].sendtoaddress(addr1, 11)
vout1 = find_output(self.nodes[0], txid1, 11)
addr2 = self.nodes[1].getnewaddress("", "legacy")
txid2 = self.nodes[0].sendtoaddress(addr2, 11)
vout2 = find_output(self.nodes[0], txid2, 11)
addr3 = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid3 = self.nodes[0].sendtoaddress(addr3, 11)
vout3 = find_output(self.nodes[0], txid3, 11)
self.sync_all()
# Update a PSBT with UTXOs from the node
# Bech32 inputs should be filled with witness UTXO. Other inputs should not be filled because they are non-witness
psbt = self.nodes[1].createpsbt([{"txid":txid1, "vout":vout1},{"txid":txid2, "vout":vout2},{"txid":txid3, "vout":vout3}], {self.nodes[0].getnewaddress():32.999})
decoded = self.nodes[1].decodepsbt(psbt)
assert "witness_utxo" not in decoded['inputs'][0] and "non_witness_utxo" not in decoded['inputs'][0]
assert "witness_utxo" not in decoded['inputs'][1] and "non_witness_utxo" not in decoded['inputs'][1]
assert "witness_utxo" not in decoded['inputs'][2] and "non_witness_utxo" not in decoded['inputs'][2]
updated = self.nodes[1].utxoupdatepsbt(psbt)
decoded = self.nodes[1].decodepsbt(updated)
assert "witness_utxo" in decoded['inputs'][0] and "non_witness_utxo" not in decoded['inputs'][0]
assert "witness_utxo" not in decoded['inputs'][1] and "non_witness_utxo" not in decoded['inputs'][1]
assert "witness_utxo" not in decoded['inputs'][2] and "non_witness_utxo" not in decoded['inputs'][2]
# Two PSBTs with a common input should not be joinable
psbt1 = self.nodes[1].createpsbt([{"txid":txid1, "vout":vout1}], {self.nodes[0].getnewaddress():Decimal('10.999')})
assert_raises_rpc_error(-8, "exists in multiple PSBTs", self.nodes[1].joinpsbts, [psbt1, updated])
# Join two distinct PSBTs
addr4 = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid4 = self.nodes[0].sendtoaddress(addr4, 5)
vout4 = find_output(self.nodes[0], txid4, 5)
self.nodes[0].generate(6)
self.sync_all()
psbt2 = self.nodes[1].createpsbt([{"txid":txid4, "vout":vout4}], {self.nodes[0].getnewaddress():Decimal('4.999')})
psbt2 = self.nodes[1].walletprocesspsbt(psbt2)['psbt']
psbt2_decoded = self.nodes[0].decodepsbt(psbt2)
assert "final_scriptwitness" in psbt2_decoded['inputs'][0] and "final_scriptSig" in psbt2_decoded['inputs'][0]
joined = self.nodes[0].joinpsbts([psbt, psbt2])
joined_decoded = self.nodes[0].decodepsbt(joined)
assert len(joined_decoded['inputs']) == 4 and len(joined_decoded['outputs']) == 2 and "final_scriptwitness" not in joined_decoded['inputs'][3] and "final_scriptSig" not in joined_decoded['inputs'][3]
# Newly created PSBT needs UTXOs and updating
addr = self.nodes[1].getnewaddress("", "p2sh-segwit")
txid = self.nodes[0].sendtoaddress(addr, 7)
addrinfo = self.nodes[1].getaddressinfo(addr)
blockhash = self.nodes[0].generate(6)[0]
self.sync_all()
vout = find_output(self.nodes[0], txid, 7, blockhash=blockhash)
psbt = self.nodes[1].createpsbt([{"txid":txid, "vout":vout}], {self.nodes[0].getnewaddress("", "p2sh-segwit"):Decimal('6.999')})
analyzed = self.nodes[0].analyzepsbt(psbt)
assert not analyzed['inputs'][0]['has_utxo'] and not analyzed['inputs'][0]['is_final'] and analyzed['inputs'][0]['next'] == 'updater' and analyzed['next'] == 'updater'
# After update with wallet, only needs signing
updated = self.nodes[1].walletprocesspsbt(psbt, False, 'ALL', True)['psbt']
analyzed = self.nodes[0].analyzepsbt(updated)
assert analyzed['inputs'][0]['has_utxo'] and not analyzed['inputs'][0]['is_final'] and analyzed['inputs'][0]['next'] == 'signer' and analyzed['next'] == 'signer' and analyzed['inputs'][0]['missing']['signatures'][0] == addrinfo['embedded']['witness_program']
# Check fee and size things
assert analyzed['fee'] == Decimal('0.001') and analyzed['estimated_vsize'] == 134 and analyzed['estimated_feerate'] == Decimal('0.00746268')
# After signing and finalizing, needs extracting
signed = self.nodes[1].walletprocesspsbt(updated)['psbt']
analyzed = self.nodes[0].analyzepsbt(signed)
assert analyzed['inputs'][0]['has_utxo'] and analyzed['inputs'][0]['is_final'] and analyzed['next'] == 'extractor'
if __name__ == '__main__':
PSBTTest().main()
|
import * as React from "react"
import { chakra, Icon, Stack, Link } from "@chakra-ui/core"
import { MdEdit } from "react-icons/md"
import { graphql, useStaticQuery } from "gatsby"
export function GithubLink({ path }) {
const data = useStaticQuery(query)
const { repository } = data.site.siteMetadata
if (!repository || !path) return null
const href = `${repository}/blob/master${path}`
return (
<Link href={href} isExternal>
<Stack
direction="row"
spacing={1}
alignItems="center"
fontSize="sm"
opacity={0.7}
>
<Icon as={MdEdit} fontSize="1em" mr="1" />
<chakra.span>Edit this page on GitHub</chakra.span>
</Stack>
</Link>
)
}
const query = graphql`
query Repo {
site {
siteMetadata {
repository
}
}
}
`
|
/**
******************************************************************************
* @file stm32f429i_discovery_gyroscope.h
* @author MCD Application Team
* @brief This file contains definitions for stm32f429i_discovery_gyroscope.c
* firmware driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F429I_DISCOVERY_GYROSCOPE_H
#define __STM32F429I_DISCOVERY_GYROSCOPE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f429i_discovery.h"
/* Include Gyroscope component driver */
#include "../Components/l3gd20/l3gd20.h"
/** @addtogroup BSP
* @{
*/
/** @addtogroup STM32F429I_DISCOVERY
* @{
*/
/** @addtogroup STM32F429I_DISCOVERY_GYROSCOPE
* @{
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Types STM32F429I DISCOVERY GYROSCOPE Exported Types
* @{
*/
typedef enum
{
GYRO_OK = 0,
GYRO_ERROR = 1,
GYRO_TIMEOUT = 2
}GYRO_StatusTypeDef;
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Constants STM32F429I DISCOVERY GYROSCOPE Exported Constants
* @{
*/
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Macros STM32F429I DISCOVERY GYROSCOPE Exported Macros
* @{
*/
/**
* @}
*/
/** @defgroup STM32F429I_DISCOVERY_GYROSCOPE_Exported_Functions STM32F429I DISCOVERY GYROSCOPE Exported Functions
* @{
*/
/* Gyroscope Functions */
uint8_t BSP_GYRO_Init(void);
void BSP_GYRO_Reset(void);
uint8_t BSP_GYRO_ReadID(void);
void BSP_GYRO_ITConfig(GYRO_InterruptConfigTypeDef *pIntConfigStruct);
void BSP_GYRO_EnableIT(uint8_t IntPin);
void BSP_GYRO_DisableIT(uint8_t IntPin);
void BSP_GYRO_GetXYZ(float* pfData);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F429I_DISCOVERY_GYROSCOPE_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
import { graphql, handleMutation } from '../gateway/graphql'; import * as _ from "lodash";
const getAll = () => graphql`
query getAllPatientTypes {
patientTypes {
id
name
immunizations(order: "reverse:createdAt") {
createdAt
description
id
name
periods {
id
month
}
}
}
}
`();
const save = (patientType) => handleMutation(graphql`
mutation addPatientType($patientType: PatientTypeInput!){
createPatientType(patientType: $patientType) {
errors {
message
}
patientType {
id
name
immunizations {
createdAt
description
id
name
periods {
id
month
}
}
}
}
}
`({ patientType }), 'createPatientType');
const update = (patientType, patientTypeId) => handleMutation(graphql`
mutation editPatientType($patientType: PatientTypeInput!, $patientTypeId: String!){
updatePatientType(patientType: $patientType, patientTypeId: $patientTypeId) {
errors {
message
}
patientType {
id
name
immunizations {
createdAt
description
id
name
periods {
id
month
}
}
}
}
}
`({ patientType: _.pick(patientType, ['name']), patientTypeId}), 'updatePatientType');
export const PatientTypeApi = {
getAll,
save,
update
};
|
import { createSelector } from 'reselect';
import { initialState } from './reducer';
/**
* Direct selector to the checkout state domain
*/
const selectCheckoutDomain = state => state.get('checkout', initialState);
/**
* Other specific selectors
*/
/**
* Default selector used by Checkout
*/
const makeSelectCheckout = () =>
createSelector(selectCheckoutDomain, substate => substate.toJS());
export default makeSelectCheckout;
export { selectCheckoutDomain };
|
// Libs
import React, { useState } from "react";
// Components
import { CheckboxGroup } from "../CheckboxGroup";
export default {
title: "Design System/Molecules/Inputs/CheckboxGroup",
component: CheckboxGroup,
parameters: {
docs: {
description: {
component: `
\`\`\`js
import { CheckboxGroup, CheckboxGroupField } from "@thc-tools/design-system/molecules/inputs"
\`\`\`
`,
},
},
},
};
function Template({ value: valueProp, options, ...args }) {
const [value, setValue] = useState(valueProp && valueProp?.length > 0 ? valueProp : [options[0]?.value]);
const onChange = (event) => {
setValue(event.target.value);
};
return (
<>
<div style={{ marginBottom: "10px" }}>
Currently selected value: <span className="thc-u-text--bold">[{value.join(", ")}]</span>
</div>
<CheckboxGroup {...args} options={options} value={value} onChange={onChange} />
</>
);
}
export const Primary = Template.bind({});
Primary.args = {
id: Math.random(),
name: Math.random().toString(),
hasSelectAll: true,
options: [
{
label: "Yes, send me IMMEDIATELY a unicorn through the mail",
value: "#YesPlease",
},
{
label: "No, I am a boring person and I don't want a unicorn",
value: "#SorryNotSorry",
},
{
label: "Who do you think I am, I already have a unicorn",
value: "#IAmAwesome",
},
{
label: "I am so grumpy ! I would never want a f*cking unicorn...",
value: "#GrumpyEverywhere",
// disabled: true,
},
],
};
|
/*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/
/*global define: false Mustache: true*/
(function defineMustache (global, factory) {
if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
factory(exports); // CommonJS
} else if (typeof define === 'function' && define.amd) {
define(['exports'], factory); // AMD
} else {
global.Mustache = {};
factory(Mustache); // script, wsh, asp
}
}(this, function mustacheFactory (mustache) {
var objectToString = Object.prototype.toString;
var isArray = Array.isArray || function isArrayPolyfill (object) {
return objectToString.call(object) === '[object Array]';
};
function isFunction (object) {
return typeof object === 'function';
}
/**
* More correct typeof string handling array
* which normally returns typeof 'object'
*/
function typeStr (obj) {
return isArray(obj) ? 'array' : typeof obj;
}
function escapeRegExp (string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}
/**
* Null safe way of checking whether or not an object,
* including its prototype, has a given property
*/
function hasProperty (obj, propName) {
return obj != null && typeof obj === 'object' &&
Object.prototype.hasOwnProperty.call(obj, propName);
}
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
var regExpTest = RegExp.prototype.test;
function testRegExp (re, string) {
return regExpTest.call(re, string);
}
var nonSpaceRe = /\S/;
function isWhitespace (string) {
return !testRegExp(nonSpaceRe, string);
}
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
return entityMap[s];
});
}
var whiteRe = /\s*/;
var spaceRe = /\s+/;
var equalsRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*/
function parseTemplate (template, tags) {
if (!template)
return [];
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
var hasTag = false; // Is there a {{tag}} on the current line?
var nonSpace = false; // Is there a non-space char on the current line?
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
function stripSpace () {
if (hasTag && !nonSpace) {
while (spaces.length)
delete tokens[spaces.pop()];
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
}
var openingTagRe, closingTagRe, closingCurlyRe;
function compileTags (tagsToCompile) {
if (typeof tagsToCompile === 'string')
tagsToCompile = tagsToCompile.split(spaceRe, 2);
if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
throw new Error('Invalid tags: ' + tagsToCompile);
openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
}
compileTags(tags || mustache.tags);
var scanner = new Scanner(template);
var start, type, value, chr, token, openSection;
while (!scanner.eos()) {
start = scanner.pos;
// Match any text between tags.
value = scanner.scanUntil(openingTagRe);
if (value) {
for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
} else {
nonSpace = true;
}
tokens.push([ 'text', chr, start, start + 1 ]);
start += 1;
// Check for whitespace on the current line.
if (chr === '\n')
stripSpace();
}
}
// Match the opening tag.
if (!scanner.scan(openingTagRe))
break;
hasTag = true;
// Get the tag type.
type = scanner.scan(tagRe) || 'name';
scanner.scan(whiteRe);
// Get the tag value.
if (type === '=') {
value = scanner.scanUntil(equalsRe);
scanner.scan(equalsRe);
scanner.scanUntil(closingTagRe);
} else if (type === '{') {
value = scanner.scanUntil(closingCurlyRe);
scanner.scan(curlyRe);
scanner.scanUntil(closingTagRe);
type = '&';
} else {
value = scanner.scanUntil(closingTagRe);
}
// Match the closing tag.
if (!scanner.scan(closingTagRe))
throw new Error('Unclosed tag at ' + scanner.pos);
token = [ type, value, start, scanner.pos ];
tokens.push(token);
if (type === '#' || type === '^') {
sections.push(token);
} else if (type === '/') {
// Check section nesting.
openSection = sections.pop();
if (!openSection)
throw new Error('Unopened section "' + value + '" at ' + start);
if (openSection[1] !== value)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
} else if (type === 'name' || type === '{' || type === '&') {
nonSpace = true;
} else if (type === '=') {
// Set the tags for the next time around.
// ORIGINAL CODE: compileTags(value);
// Fail quitely but do not allow delimiter substitutions. This is
// important from the security point of view so that our validators
// do not have to parse and interprete all of the mustache's syntax.
}
}
// Make sure there are no open sections when we're done.
openSection = sections.pop();
if (openSection)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
return nestTokens(squashTokens(tokens));
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/
function squashTokens (tokens) {
var squashedTokens = [];
var token, lastToken;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
if (token) {
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
lastToken[1] += token[1];
lastToken[3] = token[3];
} else {
squashedTokens.push(token);
lastToken = token;
}
}
}
return squashedTokens;
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/
function nestTokens (tokens) {
var nestedTokens = [];
var collector = nestedTokens;
var sections = [];
var token, section;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
switch (token[0]) {
case '#':
case '^':
collector.push(token);
sections.push(token);
collector = token[4] = [];
break;
case '/':
section = sections.pop();
section[5] = token[2];
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
break;
default:
collector.push(token);
}
}
return nestedTokens;
}
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
*/
function Scanner (string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
*/
Scanner.prototype.eos = function eos () {
return this.tail === '';
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/
Scanner.prototype.scan = function scan (re) {
var match = this.tail.match(re);
if (!match || match.index !== 0)
return '';
var string = match[0];
this.tail = this.tail.substring(string.length);
this.pos += string.length;
return string;
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function scanUntil (re) {
var index = this.tail.search(re), match;
switch (index) {
case -1:
match = this.tail;
this.tail = '';
break;
case 0:
match = '';
break;
default:
match = this.tail.substring(0, index);
this.tail = this.tail.substring(index);
}
this.pos += match.length;
return match;
};
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
*/
function Context (view, parentContext) {
this.view = view;
this.cache = { '.': this.view };
this.parent = parentContext;
}
/**
* Creates a new context using the given view with this context
* as the parent.
*/
Context.prototype.push = function push (view) {
return new Context(view, this);
};
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
*/
Context.prototype.lookup = function lookup (name) {
var cache = this.cache;
var value;
if (cache.hasOwnProperty(name)) {
value = cache[name];
} else {
var context = this, names, index, lookupHit = false;
while (context) {
if (name.indexOf('.') > 0) {
value = context.view;
names = name.split('.');
index = 0;
/**
* Using the dot notion path in `name`, we descend through the
* nested objects.
*
* To be certain that the lookup has been successful, we have to
* check if the last object in the path actually has the property
* we are looking for. We store the result in `lookupHit`.
*
* This is specially necessary for when the value has been set to
* `undefined` and we want to avoid looking up parent contexts.
**/
while (value != null && index < names.length) {
if (!hasProperty(value, names[index])) {
value = null;
break;
}
if (index === names.length - 1)
lookupHit = true;
value = value[names[index++]];
}
} else {
if (!hasProperty(context.view, name)) {
value = null;
} else {
value = context.view[name];
lookupHit = true;
}
}
if (lookupHit)
break;
context = context.parent;
}
cache[name] = value;
}
if (isFunction(value))
value = value.call(this.view);
return value;
};
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
*/
function Writer () {
this.cache = {};
}
/**
* Clears all cached templates in this writer.
*/
Writer.prototype.clearCache = function clearCache () {
this.cache = {};
};
/**
* Parses and caches the given `template` and returns the array of tokens
* that is generated from the parse.
*/
Writer.prototype.parse = function parse (template, tags) {
var cache = this.cache;
var tokens = cache[template];
if (tokens == null)
tokens = cache[template] = parseTemplate(template, tags);
return tokens;
};
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
*/
Writer.prototype.render = function render (template, view, partials) {
var tokens = this.parse(template);
var context = (view instanceof Context) ? view : new Context(view);
return this.renderTokens(tokens, context, partials, template);
};
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
*/
Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
var buffer = '';
var token, symbol, value;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
value = undefined;
token = tokens[i];
symbol = token[0];
if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
else if (symbol === '&') value = this.unescapedValue(token, context);
else if (symbol === 'name') value = this.escapedValue(token, context);
else if (symbol === 'text') value = this.rawValue(token);
if (value !== undefined)
buffer += value;
}
return buffer;
};
Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
var self = this;
var buffer = '';
var value = context.lookup(token[1]);
// This function is used to render an arbitrary template
// in the current context by higher-order sections.
function subRender (template) {
return self.render(template, context, partials);
}
if (!value) return;
if (isArray(value)) {
for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
}
} else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
} else if (isFunction(value)) {
if (typeof originalTemplate !== 'string')
throw new Error('Cannot use higher-order sections without the original template');
// Extract the portion of the original template that the section contains.
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
if (value != null)
buffer += value;
} else {
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
}
return buffer;
};
Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
var value = context.lookup(token[1]);
// Use JavaScript's definition of falsy. Include empty arrays.
// See https://github.com/janl/mustache.js/issues/186
if (!value || (isArray(value) && value.length === 0))
return this.renderTokens(token[4], context, partials, originalTemplate);
};
Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
if (!partials) return;
var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
if (value != null)
return this.renderTokens(this.parse(value), context, partials, value);
};
Writer.prototype.unescapedValue = function unescapedValue (token, context) {
var value = context.lookup(token[1]);
if (value != null) {
if (mustache.sanitizeUnescaped) {
return mustache.sanitizeUnescaped(value);
}
return value;
}
};
Writer.prototype.escapedValue = function escapedValue (token, context) {
var value = context.lookup(token[1]);
if (value != null)
return mustache.escape(value);
};
Writer.prototype.rawValue = function rawValue (token) {
return token[1];
};
mustache.name = 'mustache.js';
mustache.version = '2.2.0';
mustache.tags = [ '{{', '}}' ];
// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();
/**
* Clears all cached templates in the default writer.
*/
mustache.clearCache = function clearCache () {
return defaultWriter.clearCache();
};
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
*/
mustache.parse = function parse (template, tags) {
return defaultWriter.parse(template, tags);
};
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer.
*/
mustache.render = function render (template, view, partials) {
if (typeof template !== 'string') {
throw new TypeError('Invalid template! Template should be a "string" ' +
'but "' + typeStr(template) + '" was given as the first ' +
'argument for mustache#render(template, view, partials)');
}
return defaultWriter.render(template, view, partials);
};
// This is here for backwards compatibility with 0.4.x.,
/*eslint-disable */ // eslint wants camel cased function name
mustache.to_html = function to_html (template, view, partials, send) {
/*eslint-enable*/
var result = mustache.render(template, view, partials);
if (isFunction(send)) {
send(result);
} else {
return result;
}
};
// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
mustache.escape = escapeHtml;
// Export the sanitizing function for unescaped values.
mustache.sanitizeUnescaped = null;
mustache.setUnescapedSanitizier = function setUnescapedSanitizier (sanitizeUnescaped) {
mustache.sanitizeUnescaped = sanitizeUnescaped;
};
// Export these mainly for testing, but also for advanced usage.
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;
}));
|
/**
@file
@author Nicholas Gillian <ngillian@media.mit.edu>
@version 1.0
@brief
*/
/**
GRT MIT License
Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef GRT_ENVELOPE_EXTRACTOR_HEADER
#define GRT_ENVELOPE_EXTRACTOR_HEADER
//Include the main GRT header to get access to the FeatureExtraction base class
#include "../../CoreModules/FeatureExtraction.h"
GRT_BEGIN_NAMESPACE
class GRT_API EnvelopeExtractor : public FeatureExtraction{
public:
/**
Default constructor. Initalizes the EnvelopeExtractor, setting the number of input dimensions and the number of clusters to use in the quantization model.
@param numDimensions: the number of dimensions in the input data
@param numClusters: the number of quantization clusters
*/
EnvelopeExtractor(const UINT bufferSize = 100,const UINT numDimensions = 1);
/**
Copy constructor, copies the KMeansQuantizer from the rhs instance to this instance.
@param rhs: another instance of this class from which the data will be copied to this instance
*/
EnvelopeExtractor(const EnvelopeExtractor &rhs);
/**
Default Destructor
*/
virtual ~EnvelopeExtractor();
/**
Sets the equals operator, copies the data from the rhs instance to this instance.
@param rhs: another instance of this class from which the data will be copied to this instance
@return a reference to this instance
*/
EnvelopeExtractor& operator=(const EnvelopeExtractor &rhs);
/**
Sets the FeatureExtraction deepCopyFrom function, overwriting the base FeatureExtraction function.
This function is used to deep copy the values from the input pointer to this instance of the FeatureExtraction module.
This function is called by the GestureRecognitionPipeline when the user adds a new FeatureExtraction module to the pipeleine.
@param featureExtraction: a pointer to another instance of this class, the values of that instance will be cloned to this instance
@return returns true if the deep copy was successful, false otherwise
*/
virtual bool deepCopyFrom(const FeatureExtraction *featureExtraction);
/**
Sets the FeatureExtraction computeFeatures function, overwriting the base FeatureExtraction function.
This function is called by the GestureRecognitionPipeline when any new input data needs to be processed (during the prediction phase for example).
This is where you should add your main feature extraction code.
@param inputVector: the inputVector that should be processed. Must have the same dimensionality as the FeatureExtraction module
@return returns true if the data was processed, false otherwise
*/
virtual bool computeFeatures(const VectorFloat &inputVector);
/**
Sets the FeatureExtraction reset function, overwriting the base FeatureExtraction function.
This function is called by the GestureRecognitionPipeline when the pipelines main reset() function is called.
You should add any custom reset code to this function to define how your feature extraction module should be reset.
@return true if the instance was reset, false otherwise
*/
virtual bool reset();
/**
This saves the feature extraction settings to a file.
This overrides the save function in the FeatureExtraction base class.
You should add your own custom code to this function to define how your feature extraction module is saved to a file.
@param file: a reference to the file to save the settings to
@return returns true if the settings were saved successfully, false otherwise
*/
virtual bool save( std::fstream &file ) const;
/**
This loads the feature extraction settings from a file.
This overrides the load function in the FeatureExtraction base class.
@param file: a reference to the file to load the settings from
@return returns true if the settings were loaded successfully, false otherwise
*/
virtual bool load( std::fstream &file );
/**
Initialize the envelope extractor. This will setup the internal buffers required for using the module.
This function is automatically called by the envelope extractor constructor.
@param bufferSize: the size of the internal buffer used to compute the envelope, a larger buffer size will result in a smoother envelope
@param numDimensions: the expected number of dimensions in the input signal
@return returns true if the module was initialized successfully, false otherwise
*/
bool init( const UINT bufferSize = 100,const UINT numDimensions = 1 );
//Tell the compiler we are using the following functions from the MLBase class to stop hidden virtual function warnings
using MLBase::save;
using MLBase::load;
/**
Gets a string that represents the EnvelopeExtractor class.
@return returns a string containing the ID of this class
*/
static std::string getId();
protected:
UINT bufferSize;
CircularBuffer< VectorFloat > buffer;
private:
static RegisterFeatureExtractionModule< EnvelopeExtractor > registerModule;
static std::string id;
};
GRT_END_NAMESPACE
#endif //HEADER GUARD
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
URI utilities.
"""
import os
import urlparse
_IS_WINDOWS = (os.name == 'nt')
def as_file(uri):
"""
If the URI is a file (either the ``file`` scheme or no scheme), then returns the normalized
path. Otherwise, returns ``None``.
"""
if _IS_WINDOWS:
# We need this extra check in Windows before urlparse because paths might have a drive
# prefix, e.g. "C:" which will be considered a scheme for urlparse below
path = uri.replace('/', '\\')
if os.path.exists(path):
return os.path.normpath(path)
url = urlparse.urlparse(uri)
scheme = url.scheme
if (not scheme) or (scheme == 'file'):
path = url.path
if _IS_WINDOWS:
path = path.replace('/', '\\')
return os.path.realpath(path)
return None
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from django.test import SimpleTestCase
class WelcomePageTests(SimpleTestCase):
def test_welcome_page_status_code(self):
response = self.client.get('/')
assert response.status_code == 200
|
# coding=utf-8
from __future__ import unicode_literals
from .base import Base
from .generator import generator_of
from .normal import normal_attr
from zhihu_oauth.zhcls.urls import (
COMMENT_CONVERSION_URL,
COMMENT_REPLIES_URL,
)
__all__ = ['Comment']
class Comment(Base):
def __init__(self, cid, cache, session):
super(Comment, self).__init__(cid, cache, session)
def _get_data(self):
self._data = None
def _build_url(self):
return ''
# ----- simple info -----
@property
@normal_attr()
def allow_delete(self):
return None
@property
@normal_attr()
def allow_like(self):
return None
@property
@normal_attr()
def allow_reply(self):
return None
@property
@normal_attr()
def ancestor(self):
"""
不知道是啥,貌似永远都是 False。
"""
return None
@property
def author(self):
from .people import People
if self._cache and 'author' in self._cache:
cache = self._cache['author']
else:
self._get_data()
if self._data and 'author' in self._data:
cache = self._data['author']
else:
cache = None
if cache:
if 'member' in cache:
cache = cache['member']
return People(cache['id'], cache, self._session)
else:
return None
@property
@normal_attr()
def content(self):
return None
@property
@normal_attr()
def created_time(self):
return None
@property
@normal_attr()
def id(self):
return None
@property
@normal_attr()
def is_author(self):
"""
是否是 答案/文章/etc 的作者的评论。
"""
return None
@property
@normal_attr()
def is_delete(self):
"""
是否被删除?话说被删除了还能获取到?我没测试……
"""
return None
@property
@normal_attr()
def is_parent_author(self):
"""
也没搞懂这个属性,貌似永远和 :meth:`is_author` 保持一致。
"""
return None
@property
def reply_to(self):
"""
获取这条评论的父评论的作者,如果并没有回复谁则返回 None
:rtype: People
"""
from .people import People
if self._cache and 'reply_to_author' in self._cache:
cache = self._cache['reply_to_author']
else:
self._get_data()
if self._data and 'reply_to_author' in self._data:
cache = self._data['reply_to_author']
else:
cache = None
if cache:
if 'member' in cache:
cache = cache['member']
return People(cache['id'], cache, self._session)
else:
return None
@property
@normal_attr()
def resource_type(self):
"""
是对什么东西的评论。
======== ==========
值(str) 说明
======== ==========
answer 答案
article 文章
question 问题
favlist 收藏夹
======== ==========
"""
return None
@property
@normal_attr()
def vote_count(self):
return None
@property
@normal_attr()
def voting(self):
"""
是否对这条评论点了赞。
"""
return None
# ----- generators -----
@property
@generator_of(COMMENT_REPLIES_URL, 'comment')
def replies(self):
"""
应该是用于实现「对话列表」的。
:return: 回复本条评论的所有评论的列表(生成器)。
:rtype: collections.Iterable[Comment]
"""
return None
@property
@generator_of(COMMENT_CONVERSION_URL, 'comment')
def conversation(self):
"""
应该是用于实现「查看对话」的。
有的评论有这个属性,有个没有,我也没搞清楚规律。
:return: 包含此条评论的对话,体现为评论列表(生成器)
:rtype: collections.Iterable[Comment]
"""
return None
|