blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0148f7934401a837a240abac41f7199a6315b96 | 52146e6a28701dbe41f70035832e23a787598684 | /thirdparty/Kinetis-SDK/middleware/multicore/erpc/erpc_c/infra/erpc_message_loggers.h | 86b528a3fd8b20cbba93c2764307d160e1d6d866 | [
"BSD-3-Clause",
"BSD-3-Clause-Clear"
] | permissive | hiteshrai/redurchin | 0a47a589957f95385e1657960b5475f7b78494bd | 4cfd6f93d4c9ee0b0166b6ea25b7f266695cb32d | refs/heads/master | 2021-06-09T15:43:56.299547 | 2019-10-23T02:21:45 | 2019-10-23T02:21:45 | 146,197,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,364 | h | /*
* The Clear BSD License
* Copyright 2017 NXP
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided
* that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _EMBEDDED_RPC__LOGEVENTLISTENERS_H_
#define _EMBEDDED_RPC__LOGEVENTLISTENERS_H_
#include "erpc_transport.h"
/*!
* @addtogroup infra_transport
* @{
* @file
*/
////////////////////////////////////////////////////////////////////////////////
// Classes
////////////////////////////////////////////////////////////////////////////////
namespace erpc {
/*!
* @brief Logging messages objects used for logging sent/received messages.
*
* @ingroup infra_utility
*/
class MessageLogger
{
public:
/*!
* @brief MessageLogger constructor.
*/
MessageLogger(Transport *transport)
: m_next(NULL)
, m_transport(transport){};
/*!
* @brief MessageLogger destructor
*/
~MessageLogger(void){};
/*!
* @brief Return next logger.
*
* @return Pointer to next logger.
*/
MessageLogger *getNext(void) { return m_next; }
/*!
* @brief Set next logger.
*
* @param[in] next Pointer to next logger.
*/
void setNext(MessageLogger *next) { m_next = next; }
/*!
* @brief Returns next transport object used for logging messages.
*
* @return Transport object used for logging messages.
*/
Transport *getLogger(void) { return m_transport; }
protected:
MessageLogger *m_next; /*!< Pointer to next logger. */
Transport *m_transport; /*!< Pointer to transport object used for logging messages. */
};
/*!
* @brief Logging messages functionality.
*
* @ingroup infra_utility
*/
class MessageLoggers
{
public:
/*!
* @brief Constructor.
*/
MessageLoggers(void)
: m_logger(NULL){};
/*!
* @brief Transport destructor
*/
virtual ~MessageLoggers(void);
/*!
* @brief This function add given transport to newly created MessageLogger object.
*
* @param[in] transport Transport used for logging messages
*
* @retval True When transport was successfully added.
* @retval False When transport wasn't added.
*/
bool addMessageLogger(Transport *transport);
protected:
MessageLogger *m_logger; /*!< Pointer to first logger. */
/*!
* @brief This function add given transport to newly created MessageLogger object.
*
* @param[in] msg Buffer which will be logged.
*
* @return The eRPC status based on transport type.
*/
erpc_status_t logMessage(MessageBuffer *msg);
};
} // namespace erpc
/*! @} */
#endif // _EMBEDDED_RPC__LOGEVENTLISTENERS_H_
| [
"hiteshrai1013@gmail.com"
] | hiteshrai1013@gmail.com |
c5ebaa8be90584a4b402085b4ff0cd0050724255 | 904539f4fe3c381314b53b48d0d7126df60454f0 | /amd_sdk/src/Timer.cpp | a6e996cf3a6789692773aa0f396e5218b5c1bdb0 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | vr3d/ShadowFX | 09c6e501f3543117cf410d800d38ffcde10188fe | ee3dcce8744a6d11b7c8bb6a7dc46c072cf3b0c7 | refs/heads/master | 2021-01-19T07:23:57.658500 | 2016-03-03T01:53:59 | 2016-03-03T01:53:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,024 | cpp | //
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 "..\\..\\DXUT\\Core\\DXUT.h"
#include "Timer.h"
//using namespace AMD;
#if USE_RDTSC
__declspec(naked) LONGLONG __cdecl rdtsc_time(void)
{
__asm rdtsc
__asm ret
}
#endif
//-----------------------------------------------------------------------------
Timer::Timer() :
m_LastTime(0.0),
m_SumTime(0.0),
m_NumFrames(0)
{
}
Timer::~Timer()
{
}
double Timer::GetTime()
{
FinishCollection();
return m_LastTime;
}
double Timer::GetSumTime()
{
return m_SumTime;
}
double Timer::GetTimeNumFrames()
{
return m_NumFrames;
}
//-----------------------------------------------------------------------------
CpuTimer::CpuTimer() :
Timer()
{
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
m_freq = static_cast<double>(freq.QuadPart);
#if USE_RDTSC
const double calibrationTime = 0.1;
LONGLONG start, stop;
start = rdtsc_time();
Delay(calibrationTime);
stop = rdtsc_time();
m_freqRdtsc = static_cast<double>(stop - start) / calibrationTime;
#endif
}
CpuTimer::~CpuTimer()
{
}
void CpuTimer::Reset( bool bResetSum )
{
m_LastTime = 0.0;
if( bResetSum )
{
m_SumTime = 0.0;
m_NumFrames = 0;
}
else
{
++m_NumFrames;
}
}
void CpuTimer::Start()
{
#if USE_RDTSC
m_startTime.QuadPart = rdtsc_time();
#else
QueryPerformanceCounter(&m_startTime);
#endif
}
void CpuTimer::Stop()
{
LARGE_INTEGER t;
double freq;
#if USE_RDTSC
t.QuadPart = rdtsc_time();
freq = m_freqRdtsc;
#else
QueryPerformanceCounter(&t);
freq = m_freq;
#endif
m_LastTime += static_cast<double>(t.QuadPart - m_startTime.QuadPart) / freq;
m_SumTime += static_cast<double>(t.QuadPart - m_startTime.QuadPart) / freq;
}
void CpuTimer::Delay(double sec)
{
LARGE_INTEGER start, stop;
double t;
QueryPerformanceCounter(&start);
do
{
QueryPerformanceCounter(&stop);
t = static_cast<double>(stop.QuadPart - start.QuadPart) / m_freq;
} while (t < sec);
}
//-----------------------------------------------------------------------------
GpuTimer::GpuTimer(ID3D11Device* pDev, UINT64 freq, UINT numTimeStamps ) :
Timer(),
m_pDevCtx(NULL),
m_numTimeStamps(numTimeStamps),
m_curIssueTs(m_numTimeStamps-1),
m_nextRetrTs(0),
m_FrameID(0),
m_CurTime(0.0)
{
HRESULT hr;
_ASSERT(pDev != NULL);
_ASSERT(numTimeStamps>0);
pDev->GetImmediateContext(&m_pDevCtx);
_ASSERT(m_pDevCtx != NULL);
D3D11_QUERY_DESC qd;
qd.MiscFlags = 0;
m_ts = new TsRecord[m_numTimeStamps];
for (UINT i = 0; i < m_numTimeStamps; i++)
{
qd.Query = D3D11_QUERY_TIMESTAMP_DISJOINT;
hr = pDev->CreateQuery(&qd, &m_ts[i].pDisjointTS);
_ASSERT((hr == S_OK) && (m_ts[i].pDisjointTS != NULL));
qd.Query = D3D11_QUERY_TIMESTAMP;
hr = pDev->CreateQuery(&qd, &m_ts[i].pStart);
_ASSERT((hr == S_OK) && (m_ts[i].pStart != NULL));
hr = pDev->CreateQuery(&qd, &m_ts[i].pStop);
_ASSERT((hr == S_OK) && (m_ts[i].pStop != NULL));
m_ts[i].state = 0;
}
m_CurTimeFrame.id = 0;
m_CurTimeFrame.invalid = 1;
freq = 0;//prevent warning
}
GpuTimer::~GpuTimer()
{
for (UINT i = 0; i < m_numTimeStamps; i++)
{
SAFE_RELEASE(m_ts[i].pDisjointTS);
SAFE_RELEASE(m_ts[i].pStart);
SAFE_RELEASE(m_ts[i].pStop);
}
SAFE_DELETE_ARRAY(m_ts);
SAFE_RELEASE(m_pDevCtx);
}
void GpuTimer::Reset( bool bResetSum )
{
FinishCollection();
m_FrameID = (m_FrameID+1) & 0x3FFFFFFF;
if( bResetSum )
{
WaitIdle();
m_CurTimeFrame.invalid = 1;
m_CurTime = 0.0;
m_LastTime = 0.0;
m_SumTime = 0.0;
m_NumFrames = 0;
}
}
void GpuTimer::Start()
{
if( ++m_curIssueTs == m_numTimeStamps )
m_curIssueTs = 0;
if( 0 != m_ts[m_curIssueTs].data.startIssued )
{
_ASSERT( false && "CPU stall required! This should never happen. Please increase GpuTimer::NumTimeStamps in Timer.h" );
CollectData( m_curIssueTs, TRUE );
}
m_ts[m_curIssueTs].data.frameID = m_FrameID;
m_ts[m_curIssueTs].data.startIssued = 1;
m_ts[m_curIssueTs].data.stopIssued = 0;
m_pDevCtx->Begin(m_ts[m_curIssueTs].pDisjointTS);
m_pDevCtx->End(m_ts[m_curIssueTs].pStart);
}
void GpuTimer::Stop()
{
// check if timestamp start has been issued but no stop yet
_ASSERT( (m_ts[m_curIssueTs].data.startIssued == 1) && (m_ts[m_curIssueTs].data.stopIssued == 0) );
m_ts[m_curIssueTs].data.stopIssued = 1;
m_pDevCtx->End(m_ts[m_curIssueTs].pStop);
m_pDevCtx->End(m_ts[m_curIssueTs].pDisjointTS);
}
void GpuTimer::WaitIdle()
{
while( m_nextRetrTs != m_curIssueTs )
{
CollectData( m_nextRetrTs, true );
if( ++m_nextRetrTs == m_numTimeStamps )
m_nextRetrTs = 0;
}
// retrieve the current Ts
CollectData( m_nextRetrTs, true );
if( ++m_nextRetrTs == m_numTimeStamps )
m_nextRetrTs = 0;
if( 0 == m_CurTimeFrame.invalid )
{
m_LastTime = m_CurTime;
m_SumTime += m_CurTime;
++m_NumFrames;
}
}
void GpuTimer::FinishCollection()
{
// retrieve all available timestamps
while( CollectData(m_nextRetrTs) )
{
if( ++m_nextRetrTs == m_numTimeStamps )
m_nextRetrTs = 0;
}
}
bool GpuTimer::CollectData(UINT idx, BOOL stall)
{
if( !m_ts[idx].data.stopIssued )
return false;
// start collecting data from a new frame?
if( m_ts[idx].data.frameID != m_CurTimeFrame.id )
{
// if frametimes collected are valid: write them into m_time
// so m_time always contains the most recent valid timing data
if( 0 == m_CurTimeFrame.invalid )
{
m_LastTime = m_CurTime;
m_SumTime += m_CurTime;
++m_NumFrames;
}
// start collecting time data of the next frame
m_CurTime = 0.0;
m_CurTimeFrame.id = m_ts[idx].data.frameID;
m_CurTimeFrame.invalid = 0;
}
// if we want to retrieve the next timing data NOW the CPU will stall
// increase NumTimeStamps in Timer.h to prevent this from happening
if( stall )
{
HRESULT hr;
UINT64 start, stop;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT tsd;
do
{
hr = m_pDevCtx->GetData(m_ts[idx].pDisjointTS, &tsd, sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT), 0);
} while (hr == S_FALSE);
_ASSERT(hr == S_OK);
do
{
hr = m_pDevCtx->GetData(m_ts[idx].pStart, &start, sizeof(UINT64), 0);
} while (hr == S_FALSE);
_ASSERT(hr == S_OK);
do
{
hr = m_pDevCtx->GetData(m_ts[idx].pStop, &stop, sizeof(UINT64), 0);
} while (hr == S_FALSE);
_ASSERT(hr == S_OK);
if( tsd.Disjoint || ((start & 0xFFFFFFFF) == 0xFFFFFFFF) || ((stop & 0xFFFFFFFF) == 0xFFFFFFFF) )
{
// mark current frametime as invalid
m_CurTimeFrame.invalid = 1;
}
else
{
m_CurTime += static_cast<double>(stop - start) / static_cast<double>(tsd.Frequency);
}
m_ts[idx].state = 0;
return true;
}
// finally try collecting the available data, return false if it was not yet available
UINT64 start, stop;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT tsd;
if( S_FALSE == m_pDevCtx->GetData(m_ts[idx].pDisjointTS, &tsd, sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT), 0) )
{
return false;
}
if( S_FALSE == m_pDevCtx->GetData(m_ts[idx].pStart, &start, sizeof(UINT64), 0) )
{
return false;
}
if( S_FALSE == m_pDevCtx->GetData(m_ts[idx].pStop, &stop, sizeof(UINT64), 0) )
{
return false;
}
// all data was available, so evaluate times
if( tsd.Disjoint || ((start & 0xFFFFFFFF) == 0xFFFFFFFF) || ((stop & 0xFFFFFFFF) == 0xFFFFFFFF) )
{
// mark current frametime as invalid
m_CurTimeFrame.invalid = 1;
}
else
{
UINT64 dt = (stop - start);
m_CurTime += static_cast<double>(dt) / static_cast<double>(tsd.Frequency);
}
m_ts[idx].state = 0;
return true;
}
//-----------------------------------------------------------------------------
GpuCpuTimer::GpuCpuTimer(ID3D11Device* pDev) :
CpuTimer()
{
HRESULT hr;
_ASSERT(pDev != NULL);
pDev->GetImmediateContext(&m_pDevCtx);
_ASSERT(m_pDevCtx != NULL);
D3D11_QUERY_DESC qd;
qd.Query = D3D11_QUERY_EVENT;
qd.MiscFlags = 0;
hr = pDev->CreateQuery(&qd, &m_pEvent);
_ASSERT((hr == S_OK) && (m_pEvent != NULL));
}
GpuCpuTimer::~GpuCpuTimer()
{
SAFE_RELEASE(m_pEvent);
SAFE_RELEASE(m_pDevCtx);
}
void GpuCpuTimer::Start()
{
WaitIdle();
CpuTimer::Start();
}
void GpuCpuTimer::Stop()
{
WaitIdle();
CpuTimer::Stop();
}
void GpuCpuTimer::WaitIdle()
{
m_pDevCtx->End(m_pEvent);
HRESULT hr;
BOOL data;
do
{
hr = m_pDevCtx->GetData(m_pEvent, &data, sizeof(BOOL), 0);
} while (hr == S_FALSE);
_ASSERT(hr == S_OK);
}
//-----------------------------------------------------------------------------
// convenience timer functions
//-----------------------------------------------------------------------------
TimingEvent::TimingEvent( ) :
m_name(NULL),
m_nameLen(0),
m_used( false ),
m_parent(NULL),
m_firstChild(NULL),
m_next(NULL)
{
m_gpu = (NULL != TimerEx::Instance().GetDevice()) ? new GpuTimer( TimerEx::Instance().GetDevice(), 0, 16 ) : NULL;
}
TimingEvent::~TimingEvent()
{
SAFE_DELETE( m_gpu );
SAFE_DELETE_ARRAY(m_name);
}
void TimingEvent::SetName(LPCWSTR name)
{
size_t len_req = wcslen(name)+1;
if( len_req > m_nameLen )
{
SAFE_DELETE_ARRAY(m_name);
int len_alloc = 32 + (len_req&0xFFFFFFE0); // round up to next multiple of 32 so when reused we don't have to realloc too often
m_name = new WCHAR[len_alloc];
m_nameLen = len_alloc;
}
wcscpy_s( m_name, m_nameLen, name);
}
LPCWSTR TimingEvent::GetName( )
{
return m_name;
}
void TimingEvent::Start( )
{
m_used = true;
if( NULL != m_gpu ) m_gpu->Start();
m_cpu.Start();
}
void TimingEvent::Stop( )
{
m_cpu.Stop();
if( NULL != m_gpu ) m_gpu->Stop();
m_used = true;
}
double TimingEvent::GetTime( TimerType type, bool stall )
{
switch( type )
{
case ttCpu:
return m_cpu.GetTime();
case ttGpu:
if( NULL != m_gpu )
{
if( stall )
m_gpu->WaitIdle();
return m_gpu->GetTime();
}
// else fallthrough
default:
return 0.0f;
}
}
double TimingEvent::GetAvgTime( TimerType type, bool stall )
{
switch( type )
{
case ttCpu:
return m_cpu.GetSumTime()/m_cpu.GetTimeNumFrames();
case ttGpu:
if( NULL != m_gpu )
{
if( stall )
m_gpu->WaitIdle();
return m_gpu->GetSumTime()/m_gpu->GetTimeNumFrames();
}
// else fallthrough
default:
return 0.0f;
}
}
TimingEvent* TimingEvent::GetTimer(LPCWSTR timerId)
{
size_t len = wcslen(timerId);
size_t seperator = wcscspn( timerId, L"/|\\" );
if( seperator<len )
{
LPWSTR idCopy = new WCHAR[len+1];
wcscpy_s( idCopy, len+1, timerId );
idCopy[seperator] = 0;
TimingEvent* te = m_firstChild;
while( te )
{
if( !wcscmp(idCopy, te->m_name ) )
{
te = te->GetTimerRec( &idCopy[seperator+1] );
delete[] idCopy;
return te;
}
te = te->m_next;
}
delete[] idCopy;
}
else
{
TimingEvent* te = m_firstChild;
while( te )
{
if( !wcscmp(timerId, te->m_name ) )
return te;
te = te->m_next;
}
}
return NULL;
}
TimingEvent* TimingEvent::GetParent( )
{
return m_parent;
}
TimingEvent* TimingEvent::GetFirstChild( )
{
return m_firstChild;
}
TimingEvent* TimingEvent::GetNextTimer( )
{
return m_next;
}
// when this function is called we know we're working on a copy of the name, so we can "destruct" it
TimingEvent* TimingEvent::GetTimerRec( LPWSTR timerId )
{
size_t len = wcslen(timerId);
size_t seperator = wcscspn( timerId, L"/|\\" );
if( seperator<len )
timerId[seperator] = 0;
TimingEvent* te = m_firstChild;
while( te )
{
if( !wcscmp(timerId, te->m_name ) )
{
if( seperator<len )
te = te->GetTimerRec( &timerId[seperator+1] );
return te;
}
te = te->m_next;
}
return NULL;
}
TimingEvent* TimingEvent::FindLastChildUsed()
{
TimingEvent* ret = NULL;
TimingEvent* te = m_firstChild;
while( te )
{
if( te->m_used )
ret = te;
te = te->m_next;
}
return ret;
}
//-----------------------------------------------------------------------------
TimerEx::TimerEx( ) :
m_pDev(NULL),
m_Current(NULL),
m_Unused(NULL)
{
};
TimerEx::~TimerEx()
{
_ASSERT( "Stop() not called for every Start(...)" && (m_Current == NULL) );
Destroy();
}
void TimerEx::DeleteTimerTree( TimingEvent* te )
{
// first delete all children
while( NULL != te )
{
DeleteTimerTree( te->m_firstChild );
TimingEvent* tmp = te;
te = te->m_next;
delete tmp;
}
}
void TimerEx::Init( ID3D11Device* pDev )
{
m_pDev = pDev;
}
void TimerEx::Destroy( )
{
// delete all unused
TimingEvent* te = m_Unused;
while( NULL != te )
{
TimingEvent* tmp = te;
te = te->m_next;
delete tmp;
}
m_Unused = NULL;
// delete all used
DeleteTimerTree( m_Root );
m_Root = NULL;
m_pDev = NULL;
}
void TimerEx::Reset( TimingEvent* te, bool bResetSum )
{
TimingEvent* prev = NULL;
while( NULL != te )
{
// recursion
Reset( te->m_firstChild, bResetSum );
// reset the timer event
te->m_cpu.Reset( bResetSum );
if( NULL != te->m_gpu ) te->m_gpu->Reset( bResetSum );
if( te->m_used || !bResetSum )
{
//if it was used this frame: just reset
te->m_used = false;
prev = te;
te = te->m_next;
}
else
{
if( bResetSum && !te->m_used )
{
te->m_used = false;
// if it was not used this frame
//move to unused timer list
TimingEvent* tmp = te;
te = te->m_next;
if( NULL == prev )
{
if( NULL == tmp->m_parent )
m_Root = tmp->m_next;
else
tmp->m_parent->m_firstChild = tmp->m_next;
}
else
prev->m_next = tmp->m_next;
tmp->m_parent = NULL;
tmp->m_next = m_Unused;
m_Unused = tmp;
}
}
}
}
void TimerEx::Reset( bool bResetSum )
{
_ASSERT( "init not called or called with NULL" && (m_pDev != NULL) );
_ASSERT( "Stop() not called for every Start(...)" && (m_Current == NULL) );
if( NULL != m_Root )
Reset( m_Root, bResetSum );
}
void TimerEx::Start( LPCWSTR timerId )
{
_ASSERT( "init not called or called with NULL" && (m_pDev != NULL) );
TimingEvent* te = (NULL == m_Current) ? GetTimer(timerId) : m_Current->GetTimer(timerId);
if( NULL == te )
{
// create new timer event
if( NULL == m_Unused )
{
te = new TimingEvent();
}
else
{
te = m_Unused;
m_Unused = te->m_next;
te->m_next = NULL;
}
te->SetName( timerId );
te->m_parent = m_Current;
// now look where to insert it
TimingEvent* lu = NULL;
if( NULL == m_Current )
{
TimingEvent* tmp = m_Root;
while( tmp )
{
if( tmp->m_used )
lu = tmp;
tmp = tmp->m_next;
}
}
else
{
lu = m_Current->FindLastChildUsed();
}
if( NULL != lu )
{
te->m_next = lu->m_next;
lu->m_next = te;
}
else
{
if( NULL == m_Current )
{
te->m_next = m_Root;
m_Root = te;
}
else
{
te->m_next = m_Current->m_firstChild;
m_Current->m_firstChild = te;
}
}
}
m_Current = te;
m_Current->Start();
}
void TimerEx::Stop( )
{
_ASSERT( "init not called or called with NULL" && (m_pDev != NULL) );
_ASSERT( "Start(...) not called before Stop()" && (m_Current != NULL) );
m_Current->Stop();
m_Current = m_Current->m_parent;
}
double TimerEx::GetTime( TimerType type, LPCWSTR timerId, bool stall )
{
_ASSERT( "init not called or called with NULL" && (m_pDev != NULL) );
TimingEvent* te = NULL;
if( NULL != m_Current )
te = m_Current->GetTimer( timerId );
if( NULL == te )
te = GetTimer( timerId );
return ( NULL != te ) ? te->GetTime(type, stall) : 0.0;
}
double TimerEx::GetAvgTime( TimerType type, LPCWSTR timerId, bool stall )
{
_ASSERT( "init not called or called with NULL" && (m_pDev != NULL) );
TimingEvent* te = NULL;
if( NULL != m_Current )
te = m_Current->GetTimer( timerId );
if( NULL == te )
te = GetTimer( timerId );
return ( NULL != te ) ? te->GetAvgTime(type, stall) : 0.0;
}
TimingEvent* TimerEx::GetTimer( LPCWSTR timerId )
{
if( NULL == timerId )
return m_Root;
_ASSERT( "init not called" && (m_pDev != NULL) );
size_t len = wcslen(timerId);
size_t seperator = wcscspn( timerId, L"/|\\" );
if( seperator < len )
{
LPWSTR idCopy = new WCHAR[len+1];
wcscpy_s( idCopy, len+1, timerId );
idCopy[seperator] = 0;
TimingEvent* te = m_Root;
while( te )
{
if( !wcscmp(idCopy, te->m_name ) )
{
te = te->GetTimerRec( &idCopy[seperator+1] );
delete[] idCopy;
return te;
}
te = te->m_next;
}
delete[] idCopy;
}
else
{
TimingEvent* te = m_Root;
while( te )
{
if( !wcscmp(timerId, te->m_name ) )
return te;
te = te->m_next;
}
}
return NULL;
}
| [
"jason.stewart@amd.com"
] | jason.stewart@amd.com |
81eebe403a3245ff77aea525975cebe39c21b471 | 7c45d494e6a9afd7a1fae89e292d2eb16a1d9bde | /OrderBookSim/OrderBookSim/SimpleTraderOne.h | 14957f03ee108d80e39341c81f2d767da3e77293 | [] | no_license | jifengthu/OrderBookSimulatorWithOpenCL | 4bf6d6b8fb0909a1fa4ad48153f654d9b559811d | b3d9d3d5360120e3d31121d6845e0c134720a06f | refs/heads/master | 2023-03-17T18:37:25.870484 | 2013-05-30T20:57:21 | 2013-05-30T20:57:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | h | #pragma once
#include "ITrader.h"
class SimpleTraderOne : public ITrader
{
private:
int _currentTime;
int _time;
OrderBook* _book;
double _cash;
int _participantId;
public:
SimpleTraderOne(void);
~SimpleTraderOne(void);
void notify(int currentTime, OrderBook* orderBook);
void notify(Trade* trade);
void processBook();
};
| [
"jcukcpl@gmail.com"
] | jcukcpl@gmail.com |
ac318aa23ba9acfc31f1be3a9580eb0d84d6ab8c | e3f87e7438d7c617d60b23d45a6e60e3f560d141 | /DirectX 12/ステートパターンを使った状態管理/Player側/Player2P.cpp | e51da3024fc8320893b2b077ce439b9c85513c6c | [] | no_license | sasakiR0590/Program-Code | 61c4e35a5f8b954e2fa27b8153b581d384f4e29b | 0584bc2f46043b6c04cf940f1fdb9ba43d3f5b80 | refs/heads/master | 2023-07-14T18:42:20.578497 | 2021-08-22T05:42:46 | 2021-08-22T05:42:46 | 398,721,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | cpp | #include"class/Player/Player2P/Player2P.h"
#include"Data/HanbleData/HanbleData.h"
#include"class/Player/ActorState/Wait/Wait.h"
#include"class/Player/ActorState/SwingDown/SwingDown.h"
#include"class/Player/ActorState/Tackle/Tackle.h"
#include"class/Player/ActorState/Counter/Counter.h"
Player2P::Player2P()
{
_player_positionX = 980.0f;
_player_positionY = 270.0f;
_move_speed = 100.0f;
_action_state = false;
}
void Player2P::LoadAssets(std::vector<D3D12_GPU_DESCRIPTOR_HANDLE>& handle_path)
{
_copy_handle_path = handle_path;
ChangeState(new WaitState(this, _copy_handle_path[PLAYERBODY_2P], _copy_handle_path[BAMBOOSWORD_2P]));
}
void Player2P::Update(const float deltaTime)
{
if (_state->Update(deltaTime) == 1)
{
ChangeState(new WaitState(this, _copy_handle_path[PLAYERBODY_2P], _copy_handle_path[BAMBOOSWORD_2P]));
_action_state = false;
}
if (!_action_state)
{
if (dxtk::GetInstance()->KeyState->Right)
_player_positionX += _move_speed * deltaTime;
if (dxtk::GetInstance()->KeyState->Left)
_player_positionX -= _move_speed * deltaTime;
if (dxtk::GetInstance()->KeyState->L)
{
ChangeState(new SwingDownState(this, _copy_handle_path[PLAYERBODY_2P], _copy_handle_path[BAMBOOSWORD_2P]));
_action_state = true;
}
if (dxtk::GetInstance()->KeyState->K)
{
ChangeState(new TackleState(this, _copy_handle_path[TACKLE_2P]));
_action_state = true;
}
if (dxtk::GetInstance()->KeyState->J)
{
ChangeState(new CounterState(this, _copy_handle_path[COUNTER_2P]));
_action_state = true;
}
}
}
void Player2P::OnDeviceLost()
{
_state->OnDeviceLost();
}
void Player2P::Render(SpriteBatch* spriteBatch)
{
_state->Render(spriteBatch, _player_positionX, _player_positionY);
} | [
"rinnderu0505@gmail.com"
] | rinnderu0505@gmail.com |
5f379d2c7631ac091c396e5c4153d75f0c23ec9f | ee32d46014c1f2fc5ec7bb833233c24237270933 | /1730A/main.cpp | 2fe336339b258312c06ae60462c2fb6796a2bf83 | [] | no_license | boxnos/codeforces | 42b48367d222cc58c2bc0f408469fc6a2732cec7 | fbc358fe7ddf48d48bda29e75ef3264f9ed19852 | refs/heads/master | 2023-08-27T21:18:44.163264 | 2023-08-26T18:06:59 | 2023-08-26T18:06:59 | 192,764,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,727 | cpp | #if !defined __clang__
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#define _USE_MATH_DEFINES
#endif
#include <cstdio>
#include <cstring>
#include <utility>
#include <functional>
#include <array>
#include <limits>
//#include <ext/pb_ds/assoc_container.hpp>
//using namespace __gnu_pbds;
using namespace std;
//#define MINUS_
#define IO_
//#define PCGK_
#define I_ inline
#define T_ template
#define TN_ typename
#define TT_ T_ <TN_ T>
#define HT_ T_ <TN_ H,TN_... T>
#define OP_(t) I_ operator t()
#define ly(x) __builtin_expect(x, 1)
#define un(x) __builtin_expect(x, 0)
#ifdef IO_
namespace io {
const size_t s=1<<18;char in[s],*i {},*e {},out[s],*o=out,*f=o+s-1;
I_ char get(){return i==e?e=(i=in)+fread(in,1,s,stdin),i==e?EOF:*i++:*i++;}
I_ void flush(){fwrite(out,1,o-out,stdout);o=out;}
I_ void put(char c){*o++=c;if(o==f)flush();}
I_ void puts(char *b, char *e) {
static char *g {f + 1};
if (size_t l = e - b, r = g - o; ly(l < r))
memcpy(o, b, l), o+=l;
else {
memcpy(o, b, r), o+=r;
flush();
if (l > r)
puts(b + r, e);
}
};
#ifdef _GLIBCXX_STRING
#define S_
I_ void puts(string &t) {
static char *g {f + 1};
if (un(t.size() >= size_t(g - o)))
puts(&t[0], &t[t.size()]);
else
memcpy(o, &t[0], t.size()), o+=t.size();
};
I_ void gets(string &t) {
if (t.size() > size_t(e - i)) {
for(char &i:t)i=get();
get();
} else
memcpy(&t[0], i, t.size()), i+=t.size(), get();
};
I_ string gets() {
for (char *j = i; j != e; ++j)
if (*j == ' ' || *j == '\n')
return string(exchange(i, j + 1), j);
string s;for(char c;c=get(),c!=' '&&c!='\n';)s+=c;return s;
}
#endif
struct flush_{~flush_(){flush();}} flush__;}
#define gcu io::get
#define pcu io::put
#else
#ifdef __linux
#define _U(s) s##_unlocked
#else
#define _U(s) _##s##_nolock
#define _CRT_DISABLE_PERFCRIT_LOCKS
#endif
#define gcu _U(getchar)
#define pcu _U(putchar)
#endif
struct in_ {
I_ operator void *(){char c;do{c=gcu();}while(c!=' '&&c!='\n');return NULL;}
#ifdef S_
OP_(string){
#ifdef IO_
return io::gets();}
#else
string s;for(char c;c=get(),c!=' '&&c!='\n';)s+=c;return s;}
#endif
//OP_(string){string s;char c;while(isspace(c = gcu()));do{s+=c;}while(c=gcu(),c!=' '&&c!='\n'&&c!=EOF);return s;}
I_ string read(int n,char c) {
string v(n,c);
#ifdef IO_
io::gets(v);
#else
for(char &i:v)i=gcu();gcu();
#endif
return v;
}
#endif
OP_(char){char c=gcu();gcu();return c;}
#ifndef IO_
OP_(double){double d; scanf("%lf",&d); gcu();return d;}
#endif
TT_ I_ T RI_(char c){T n{};do{n=10*n+(c-'0'),c=gcu();}while(c>='0'/* &&c<='9' */);return n;}
TT_ OP_(T){
char c=gcu();
#ifdef PCK_
for(;isspace(c);c=gcu());
#endif
#ifdef MINUS_
return c=='-'?~(RI_<T>(gcu())-1):RI_<T>(c);
#else
return RI_<T>(c);
#endif
}
#ifdef _GLIBCXX_VECTOR
#define TI_ T_<TN_ T=vector<int>, TN_ I=TN_ T::value_type>
TI_ I_ T read(int n) {T v(n);for(I &i:v)i=*this;return v;}
TI_ I_ T read(int n,function<int(TN_ T::value_type)>f){T v(n);for(I &i:v)i=f(*this);return v;}
TI_ I_ T read(int n,function<void(TN_ T::value_type&,TN_ T::value_type)>f){T v(n);for(I &i:v)f(i,*this);return v;}
#endif
T_ <int N, TN_ T=int> array<T, N> read(){array<T, N>a;for(T &i:a)i=*this;return a;}
} in;
T_ <TN_ T=int> struct ist {
int n; ist(int _n) : n(_n) {};
struct it { int p; it(int _p) : p(_p) {}; I_ T operator *() const {return T(in);};
I_ bool operator !=(const it& v) {return p != v.p;}; I_ it & operator ++() {++p; return *this;}; };
I_ it begin() {return {0};}; I_ it end() {return {n};};
};
#define DEF_(r, n, ...) I_ r n(__VA_ARGS__)
#define OUT_(...) DEF_(void,out,__VA_ARGS__)
#define OUTL_(...) DEF_(void,outl,__VA_ARGS__)
OUT_(bool b){pcu('0'+b);}
OUT_(const char *s){while(*s)pcu(*s++);}
OUT_(char c){pcu(c);}
#ifdef S_
OUT_(string &s){
#ifdef IO_
io::puts(s);
#else
for(char c:s)pcu(c);
#endif
}
//OUT_(string s){for(char c:s)pcu(c);}
#endif
//TT_ DEF_(void,OUTX_,T n){if(n<10)pcu(n+'0');else OUTX_(n/10),pcu(n%10+'0');}
TT_ OUT_(T n){
#ifdef MINUS_
if(n<0)pcu('-'),n=-n;
#endif
static char b[20], *a=b+20;
char *p=a;
if(n)while(n)*--p=n%10+'0',n/=10;else*--p='0';
#ifdef IO_
io::puts(p, a);
#else
while(p!=a)pcu(*p++);
#endif
//OUTX_(n);
}
TT_ OUT_(initializer_list<T> v){for(auto i{begin(v)};i!=end(v);++i)out(i==begin(v)?"":" "),out(*i);}
#ifdef _GLIBCXX_VECTOR
TT_ OUT_(vector<T> &v){if(auto i{begin(v)},e{end(v)};i!=e){out(*i++);for(;i!=e;++i)out(' '),out(*i);}}
#endif
HT_ OUT_(H &&h,T... t){out(h);out(t...);}
OUTL_(){out('\n');}
T_ <TN_... T> OUTL_(T... t){out(t...);outl();}
T_ <TN_ I,TN_... T> OUTL_(initializer_list<I> v,T... t){for(auto i{begin(v)};i!=end(v);++i)out(i==begin(v)?"":" "),out(*i);outl(t...);}
T_ <TN_ T=int> struct range{
T e,b=0,s=1;range(T b,T e,T s):e(e),b(b),s(s){} range(T b,T e): e(e), b(b){} range(T e):e(e){}
struct it{T v,s; it(T v,T s):v(v),s(s){} operator T()const{return v;} I_ operator T&(){return v;}T operator*()const{return v;}
I_ it& operator++(){v+=s;return *this;}}; it begin(){return {b,s};} it end(){return {e,s};}};
#define Range(b,...)for([[maybe_unused]] auto b:range<int>((int) __VA_ARGS__))
#define Test Range(testcase__, in)
#define dbg(...)fprintf(stderr,__VA_ARGS__)
using LL=long long;
#define tee(s,v)({dbg(s,v);v;})
#define TAPP(t,s)t tapp(t v){return tee(s, v);}
TAPP(char,"%c") TAPP(int,"%d") TAPP(LL,"%lld") TAPP(const char *, "%s") TAPP(bool, "%d")
#ifdef S_
string tapp(string s) {return tee("%s",s.c_str());}
#endif
TT_ T tapp(T v){for (auto i: v){tapp(i);dbg(" ");}return v;}
TT_ T tapl(T v){tapp(v);dbg("\n");return v;}
#ifdef _GLIBCXX_IOSTREAM
void fast_io() {ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);}
#endif
#ifdef _FUNCTIONAL_HASH_H
#include <chrono>
struct custom_hash{size_t operator()(size_t x)const{static const size_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); x += 0x9e3779b97f4a7c15 + FIXED_RANDOM; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } };
#endif
TT_ constexpr T inf {numeric_limits<T>::max()};
TT_ T sign(T a) {return (a > 0) - (a < 0);}
I_ int bsign(bool b){return b - !b;}
TT_ T eucdiv(T a, T b) {T t = a / b; return a % b < 0 ? t - 1: t;}
TT_ T eucmod(T a, T b) {T t = a % b; return t < 0 ? t + abs(b) : t;}
TT_ I_ T ceil(T a, T b) {return (a + b - 1) / b;}
T_ <TN_ P, TN_ O> I_ constexpr int len(P &p, O o) {return distance(begin(p), o);}
TT_ I_ constexpr int len(T p) {return size(p);}
int main() {
Test {
int n {in}, c {in}, t {1}, r {};
vector<int> a {in.read(n)};
sort(begin(a), end(a));
Range (i, 1, n)
if (a[i - 1] == a[i])
t++;
else
r += min(t, c), t = 1;
outl(r + min(t, c));
}
}
/* vim: set ts=4 noet: */
| [
"boxnos@yahoo.com"
] | boxnos@yahoo.com |
3925eb875a4e71d49ee27aa1c1d6b03e52655edf | a09274b324f25cf167090f6b75b3f5eb56a6e1b5 | /1/1hw/11/11/11.cpp | 76dc099aef5c9578eda3140a2d748e392979762b | [] | no_license | shurik111333/homework | e409ddd5a0250c9544b2513ecf6c38a1ba98e65c | 7a97089572f1c316fd2bae620bfba8ff796822f1 | refs/heads/master | 2020-05-21T12:33:33.080528 | 2017-06-03T09:44:52 | 2017-06-03T09:44:52 | 47,825,887 | 1 | 1 | null | 2017-06-03T09:44:53 | 2015-12-11T12:36:12 | C++ | WINDOWS-1251 | C++ | false | false | 1,318 | cpp | // 11.cpp: определяет точку входа для консольного приложения.
//
#include <iostream>
using namespace std;
void qSort(int left, int right, int arr[])
{
int leftIndex = left;
int rightIndex = right;
int comparingElement = arr[(left + right) / 2];
while (leftIndex < rightIndex)
{
while (arr[leftIndex] < comparingElement)
{
leftIndex++;
}
while (arr[rightIndex] > comparingElement)
{
rightIndex--;
}
if (leftIndex <= rightIndex)
{
swap(arr[leftIndex], arr[rightIndex]);
leftIndex++;
rightIndex--;
}
}
if (leftIndex < right)
{
qSort(leftIndex, right, arr);
}
if (rightIndex > left)
{
qSort(left, rightIndex, arr);
}
}
int main()
{
setlocale(LC_ALL, "rus");
cout << "Программа сортирует массив по убыванию алгоритмом быстрой сортировки" << endl;
cout << "Введите количество элементов массива" << endl;
int n = 0;
cin >> n;
cout << "Введите элементы массива" << endl;
int *inputArray = new int[n];
for (int i = 0; i < n; i++)
{
cin >> inputArray[i];
}
qSort(0, n - 1, inputArray);
for (int i = 0; i < n; i++)
{
cout << inputArray[i] << " ";
}
cout << endl;
delete[] inputArray;
return 0;
} | [
"chudov.aleksandr94@gmail.com"
] | chudov.aleksandr94@gmail.com |
1847b54a8566b9548ca2e4bb467328fdf6dd761c | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/gcc/d/imports.cc | 6747ee5df27a459bd772b4246f655e23c1b48b06 | [
"LGPL-2.1-only",
"FSFAP",
"LGPL-3.0-only",
"GPL-3.0-only",
"GPL-2.0-only",
"GCC-exception-3.1",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 5,484 | cc | /* imports.cc -- Build imported modules/declarations.
Copyright (C) 2014-2022 Free Software Foundation, Inc.
GCC 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, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "dmd/aggregate.h"
#include "dmd/declaration.h"
#include "dmd/enum.h"
#include "dmd/identifier.h"
#include "dmd/import.h"
#include "dmd/module.h"
#include "tree.h"
#include "stringpool.h"
#include "d-tree.h"
static hash_map<Dsymbol *, tree> *imported_decls;
/* Implements the visitor interface to build debug trees for all
module and import declarations, where RESULT_ holds the back-end
representation to be cached and returned from the caller. */
class ImportVisitor : public Visitor
{
using Visitor::visit;
tree result_;
/* Build the declaration DECL as an imported symbol. */
tree make_import (tree decl)
{
gcc_assert (decl != NULL_TREE);
tree import = build_decl (input_location, IMPORTED_DECL,
DECL_NAME (decl), void_type_node);
IMPORTED_DECL_ASSOCIATED_DECL (import) = decl;
d_keep (import);
return import;
}
public:
ImportVisitor (void)
{
this->result_ = NULL_TREE;
}
tree result (void)
{
return this->result_;
}
/* This should be overridden by each symbol class. */
void visit (Dsymbol *)
{
gcc_unreachable ();
}
/* Build the module decl for M, this is considered toplevel, regardless
of whether there are any parent packages in the module system. */
void visit (Module *m)
{
Loc loc = (m->md != NULL) ? m->md->loc
: Loc (m->srcfile.toChars (), 1, 0);
this->result_ = build_decl (make_location_t (loc), NAMESPACE_DECL,
get_identifier (m->toPrettyChars ()),
void_type_node);
d_keep (this->result_);
if (!m->isRoot ())
DECL_EXTERNAL (this->result_) = 1;
TREE_PUBLIC (this->result_) = 1;
DECL_CONTEXT (this->result_) = NULL_TREE;
}
/* Build an import of another module symbol. */
void visit (Import *m)
{
tree module = build_import_decl (m->mod);
this->result_ = this->make_import (module);
}
/* Build an import for any kind of user defined type.
Use the TYPE_DECL associated with the type symbol. */
void visit (EnumDeclaration *d)
{
tree type = build_ctype (d->type);
/* Not all kinds of D enums create a TYPE_DECL. */
if (TREE_CODE (type) == ENUMERAL_TYPE)
this->result_ = this->make_import (TYPE_STUB_DECL (type));
}
void visit (AggregateDeclaration *d)
{
tree type = build_ctype (d->type);
this->result_ = this->make_import (TYPE_STUB_DECL (type));
}
void visit (ClassDeclaration *d)
{
/* Want the RECORD_TYPE, not POINTER_TYPE. */
tree type = TREE_TYPE (build_ctype (d->type));
this->result_ = this->make_import (TYPE_STUB_DECL (type));
}
/* For now, ignore importing other kinds of dsymbols. */
void visit (ScopeDsymbol *)
{
}
/* Alias symbols aren't imported, but their targets are. */
void visit (AliasDeclaration *d)
{
Dsymbol *dsym = d->toAlias ();
if (dsym == d)
{
Type *type = d->getType ();
/* Type imports should really be part of their own visit method. */
if (type != NULL)
{
if (type->ty == TY::Tenum)
dsym = type->isTypeEnum ()->sym;
else if (type->ty == TY::Tstruct)
dsym = type->isTypeStruct ()->sym;
else if (type->ty == TY::Tclass)
dsym = type->isTypeClass ()->sym;
}
}
/* This symbol is really an alias for another, visit the other. */
if (dsym != d)
dsym->accept (this);
}
/* Visit the underlying alias symbol of overloadable aliases. */
void visit (OverDeclaration *d)
{
if (d->aliassym != NULL)
d->aliassym->accept (this);
}
/* Function aliases are the same as alias symbols. */
void visit (FuncAliasDeclaration *d)
{
FuncDeclaration *fd = d->toAliasFunc ();
if (fd != NULL)
fd->accept (this);
}
/* Skip over importing templates and tuples. */
void visit (TemplateDeclaration *)
{
}
void visit (TupleDeclaration *)
{
}
/* Import any other kind of declaration. If the class does not implement
symbol generation routines, the compiler will throw an error. */
void visit (Declaration *d)
{
this->result_ = this->make_import (get_symbol_decl (d));
}
};
/* Build a declaration for the symbol D that can be used for the
debug_hook imported_module_or_decl. */
tree
build_import_decl (Dsymbol *d)
{
hash_map_maybe_create<hm_ggc> (imported_decls);
if (tree *decl = imported_decls->get (d))
return *decl;
location_t saved_location = input_location;
ImportVisitor v = ImportVisitor ();
input_location = make_location_t (d->loc);
d->accept (&v);
input_location = saved_location;
/* Not all visitors set `result'. */
tree isym = v.result ();
if (isym != NULL_TREE)
imported_decls->put (d, isym);
return isym;
}
| [
"rink@rink.nu"
] | rink@rink.nu |
8d97dafe78248c7f531550ccd5164078c25f7b8b | 85635724b2fca00487089b316516cc1ade4eff6b | /docs/Lab4/RF24.cpp | 6032c5474eae5d648d98e46444b861d500eb16d9 | [] | no_license | bjeong99/MazeTraversalRobot | 0d6aa1a8cb6b75cfda22e6fa390b43a808e3c1df | 386a0de5d08e31a639950e09701693dc13c8fb8f | refs/heads/master | 2020-12-03T23:55:55.391398 | 2020-01-03T06:44:35 | 2020-01-03T06:44:35 | 231,529,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,030 | cpp | /*
Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
#include "nRF24L01.h"
#include "RF24_config.h"
#include "RF24.h"
/****************************************************************************/
void RF24::csn(int mode)
{
// Minimum ideal SPI bus speed is 2x data rate
// If we assume 2Mbs data rate and 16Mhz clock, a
// divider of 4 is the minimum we want.
// CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz
#ifdef ARDUINO
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV8);
#endif
digitalWrite(csn_pin,mode);
}
/****************************************************************************/
void RF24::ce(int level)
{
digitalWrite(ce_pin,level);
}
/****************************************************************************/
uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len)
{
uint8_t status;
csn(LOW);
status = SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
while ( len-- )
*buf++ = SPI.transfer(0xff);
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::read_register(uint8_t reg)
{
csn(LOW);
SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) );
uint8_t result = SPI.transfer(0xff);
csn(HIGH);
return result;
}
/****************************************************************************/
uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len)
{
uint8_t status;
csn(LOW);
status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
while ( len-- )
SPI.transfer(*buf++);
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::write_register(uint8_t reg, uint8_t value)
{
uint8_t status;
IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value));
csn(LOW);
status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) );
SPI.transfer(value);
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::write_payload(const void* buf, uint8_t len)
{
uint8_t status;
const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);
uint8_t data_len = min(len,payload_size);
uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len;
//printf("[Writing %u bytes %u blanks]",data_len,blank_len);
csn(LOW);
status = SPI.transfer( W_TX_PAYLOAD );
while ( data_len-- )
SPI.transfer(*current++);
while ( blank_len-- )
SPI.transfer(0);
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::read_payload(void* buf, uint8_t len)
{
uint8_t status;
uint8_t* current = reinterpret_cast<uint8_t*>(buf);
uint8_t data_len = min(len,payload_size);
uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len;
//printf("[Reading %u bytes %u blanks]",data_len,blank_len);
csn(LOW);
status = SPI.transfer( R_RX_PAYLOAD );
while ( data_len-- )
*current++ = SPI.transfer(0xff);
while ( blank_len-- )
SPI.transfer(0xff);
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::flush_rx(void)
{
uint8_t status;
csn(LOW);
status = SPI.transfer( FLUSH_RX );
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::flush_tx(void)
{
uint8_t status;
csn(LOW);
status = SPI.transfer( FLUSH_TX );
csn(HIGH);
return status;
}
/****************************************************************************/
uint8_t RF24::get_status(void)
{
uint8_t status;
csn(LOW);
status = SPI.transfer( NOP );
csn(HIGH);
return status;
}
/****************************************************************************/
void RF24::print_status(uint8_t status)
{
printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"),
status,
(status & _BV(RX_DR))?1:0,
(status & _BV(TX_DS))?1:0,
(status & _BV(MAX_RT))?1:0,
((status >> RX_P_NO) & B111),
(status & _BV(TX_FULL))?1:0
);
}
/****************************************************************************/
void RF24::print_observe_tx(uint8_t value)
{
printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"),
value,
(value >> PLOS_CNT) & B1111,
(value >> ARC_CNT) & B1111
);
}
/****************************************************************************/
void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty)
{
char extra_tab = strlen_P(name) < 8 ? '\t' : 0;
printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab);
while (qty--)
printf_P(PSTR(" 0x%02x"),read_register(reg++));
printf_P(PSTR("\r\n"));
}
/****************************************************************************/
void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty)
{
char extra_tab = strlen_P(name) < 8 ? '\t' : 0;
printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab);
while (qty--)
{
uint8_t buffer[5];
read_register(reg++,buffer,sizeof buffer);
printf_P(PSTR(" 0x"));
uint8_t* bufptr = buffer + sizeof buffer;
while( --bufptr >= buffer )
printf_P(PSTR("%02x"),*bufptr);
}
printf_P(PSTR("\r\n"));
}
/****************************************************************************/
RF24::RF24(uint8_t _cepin, uint8_t _cspin):
ce_pin(_cepin), csn_pin(_cspin), wide_band(true), p_variant(false),
payload_size(32), ack_payload_available(false), dynamic_payloads_enabled(false),
pipe0_reading_address(0)
{
}
/****************************************************************************/
void RF24::setChannel(uint8_t channel)
{
// TODO: This method could take advantage of the 'wide_band' calculation
// done in setChannel() to require certain channel spacing.
const uint8_t max_channel = 127;
write_register(RF_CH,min(channel,max_channel));
}
/****************************************************************************/
void RF24::setPayloadSize(uint8_t size)
{
const uint8_t max_payload_size = 32;
payload_size = min(size,max_payload_size);
}
/****************************************************************************/
uint8_t RF24::getPayloadSize(void)
{
return payload_size;
}
/****************************************************************************/
static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS";
static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS";
static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS";
static const char * const rf24_datarate_e_str_P[] PROGMEM = {
rf24_datarate_e_str_0,
rf24_datarate_e_str_1,
rf24_datarate_e_str_2,
};
static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01";
static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+";
static const char * const rf24_model_e_str_P[] PROGMEM = {
rf24_model_e_str_0,
rf24_model_e_str_1,
};
static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled";
static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits";
static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ;
static const char * const rf24_crclength_e_str_P[] PROGMEM = {
rf24_crclength_e_str_0,
rf24_crclength_e_str_1,
rf24_crclength_e_str_2,
};
static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN";
static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW";
static const char rf24_pa_dbm_e_str_2[] PROGMEM = "LA_MED";
static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_HIGH";
static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = {
rf24_pa_dbm_e_str_0,
rf24_pa_dbm_e_str_1,
rf24_pa_dbm_e_str_2,
rf24_pa_dbm_e_str_3,
};
void RF24::printDetails(void)
{
print_status(get_status());
print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2);
print_byte_register(PSTR("RX_ADDR_P2-5"),RX_ADDR_P2,4);
print_address_register(PSTR("TX_ADDR"),TX_ADDR);
print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6);
print_byte_register(PSTR("EN_AA"),EN_AA);
print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR);
print_byte_register(PSTR("RF_CH"),RF_CH);
print_byte_register(PSTR("RF_SETUP"),RF_SETUP);
print_byte_register(PSTR("CONFIG"),CONFIG);
print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2);
printf_P(PSTR("Data Rate\t = %S\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()]));
printf_P(PSTR("Model\t\t = %S\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()]));
printf_P(PSTR("CRC Length\t = %S\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()]));
printf_P(PSTR("PA Power\t = %S\r\n"),pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()]));
}
/****************************************************************************/
void RF24::begin(void)
{
// Initialize pins
pinMode(ce_pin,OUTPUT);
pinMode(csn_pin,OUTPUT);
// Initialize SPI bus
SPI.begin();
ce(LOW);
csn(HIGH);
// Must allow the radio time to settle else configuration bits will not necessarily stick.
// This is actually only required following power up but some settling time also appears to
// be required after resets too. For full coverage, we'll always assume the worst.
// Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped.
// Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure.
// WARNING: Delay is based on P-variant whereby non-P *may* require different timing.
delay( 5 ) ;
// Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier
// WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet
// sizes must never be used. See documentation for a more complete explanation.
write_register(SETUP_RETR,(B0100 << ARD) | (B1111 << ARC));
// Restore our default PA level
setPALevel( RF24_PA_MAX ) ;
// Determine if this is a p or non-p RF24 module and then
// reset our data rate back to default value. This works
// because a non-P variant won't allow the data rate to
// be set to 250Kbps.
if( setDataRate( RF24_250KBPS ) )
{
p_variant = true ;
}
// Then set the data rate to the slowest (and most reliable) speed supported by all
// hardware.
setDataRate( RF24_1MBPS ) ;
// Initialize CRC and request 2-byte (16bit) CRC
setCRCLength( RF24_CRC_16 ) ;
// Disable dynamic payloads, to match dynamic_payloads_enabled setting
write_register(DYNPD,0);
// Reset current status
// Notice reset and flush is the last thing we do
write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Set up default configuration. Callers can always change it later.
// This channel should be universally safe and not bleed over into adjacent
// spectrum.
setChannel(76);
// Flush buffers
flush_rx();
flush_tx();
}
/****************************************************************************/
void RF24::startListening(void)
{
write_register(CONFIG, read_register(CONFIG) | _BV(PWR_UP) | _BV(PRIM_RX));
write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Restore the pipe0 adddress, if exists
if (pipe0_reading_address)
write_register(RX_ADDR_P0, reinterpret_cast<const uint8_t*>(&pipe0_reading_address), 5);
// Flush buffers
flush_rx();
flush_tx();
// Go!
ce(HIGH);
// wait for the radio to come up (130us actually only needed)
delayMicroseconds(130);
}
/****************************************************************************/
void RF24::stopListening(void)
{
ce(LOW);
flush_tx();
flush_rx();
}
/****************************************************************************/
void RF24::powerDown(void)
{
write_register(CONFIG,read_register(CONFIG) & ~_BV(PWR_UP));
}
/****************************************************************************/
void RF24::powerUp(void)
{
write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP));
}
/******************************************************************/
bool RF24::write( const void* buf, uint8_t len )
{
bool result = false;
// Begin the write
startWrite(buf,len);
// ------------
// At this point we could return from a non-blocking write, and then call
// the rest after an interrupt
// Instead, we are going to block here until we get TX_DS (transmission completed and ack'd)
// or MAX_RT (maximum retries, transmission failed). Also, we'll timeout in case the radio
// is flaky and we get neither.
// IN the end, the send should be blocking. It comes back in 60ms worst case, or much faster
// if I tighted up the retry logic. (Default settings will be 1500us.
// Monitor the send
uint8_t observe_tx;
uint8_t status;
uint32_t sent_at = millis();
const uint32_t timeout = 500; //ms to wait for timeout
do
{
status = read_register(OBSERVE_TX,&observe_tx,1);
IF_SERIAL_DEBUG(Serial.print(observe_tx,HEX));
}
while( ! ( status & ( _BV(TX_DS) | _BV(MAX_RT) ) ) && ( millis() - sent_at < timeout ) );
// The part above is what you could recreate with your own interrupt handler,
// and then call this when you got an interrupt
// ------------
// Call this when you get an interrupt
// The status tells us three things
// * The send was successful (TX_DS)
// * The send failed, too many retries (MAX_RT)
// * There is an ack packet waiting (RX_DR)
bool tx_ok, tx_fail;
whatHappened(tx_ok,tx_fail,ack_payload_available);
//printf("%u%u%u\r\n",tx_ok,tx_fail,ack_payload_available);
result = tx_ok;
IF_SERIAL_DEBUG(Serial.print(result?"...OK.":"...Failed"));
// Handle the ack packet
if ( ack_payload_available )
{
ack_payload_length = getDynamicPayloadSize();
IF_SERIAL_DEBUG(Serial.print("[AckPacket]/"));
IF_SERIAL_DEBUG(Serial.println(ack_payload_length,DEC));
}
// Yay, we are done.
// Power down
powerDown();
// Flush buffers (Is this a relic of past experimentation, and not needed anymore??)
flush_tx();
return result;
}
/****************************************************************************/
void RF24::startWrite( const void* buf, uint8_t len )
{
// Transmitter power-up
write_register(CONFIG, ( read_register(CONFIG) | _BV(PWR_UP) ) & ~_BV(PRIM_RX) );
delayMicroseconds(150);
// Send the payload
write_payload( buf, len );
// Allons!
ce(HIGH);
delayMicroseconds(15);
ce(LOW);
}
/****************************************************************************/
uint8_t RF24::getDynamicPayloadSize(void)
{
uint8_t result = 0;
csn(LOW);
SPI.transfer( R_RX_PL_WID );
result = SPI.transfer(0xff);
csn(HIGH);
return result;
}
/****************************************************************************/
bool RF24::available(void)
{
return available(NULL);
}
/****************************************************************************/
bool RF24::available(uint8_t* pipe_num)
{
uint8_t status = get_status();
// Too noisy, enable if you really want lots o data!!
//IF_SERIAL_DEBUG(print_status(status));
bool result = ( status & _BV(RX_DR) );
if (result)
{
// If the caller wants the pipe number, include that
if ( pipe_num )
*pipe_num = ( status >> RX_P_NO ) & B111;
// Clear the status bit
// ??? Should this REALLY be cleared now? Or wait until we
// actually READ the payload?
write_register(STATUS,_BV(RX_DR) );
// Handle ack payload receipt
if ( status & _BV(TX_DS) )
{
write_register(STATUS,_BV(TX_DS));
}
}
return result;
}
/****************************************************************************/
bool RF24::read( void* buf, uint8_t len )
{
// Fetch the payload
read_payload( buf, len );
// was this the last of the data available?
return read_register(FIFO_STATUS) & _BV(RX_EMPTY);
}
/****************************************************************************/
void RF24::whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready)
{
// Read the status & reset the status in one easy call
// Or is that such a good idea?
uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
// Report to the user what happened
tx_ok = status & _BV(TX_DS);
tx_fail = status & _BV(MAX_RT);
rx_ready = status & _BV(RX_DR);
}
/****************************************************************************/
void RF24::openWritingPipe(uint64_t value)
{
// Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+)
// expects it LSB first too, so we're good.
write_register(RX_ADDR_P0, reinterpret_cast<uint8_t*>(&value), 5);
write_register(TX_ADDR, reinterpret_cast<uint8_t*>(&value), 5);
const uint8_t max_payload_size = 32;
write_register(RX_PW_P0,min(payload_size,max_payload_size));
}
/****************************************************************************/
static const uint8_t child_pipe[] PROGMEM =
{
RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5
};
static const uint8_t child_payload_size[] PROGMEM =
{
RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5
};
static const uint8_t child_pipe_enable[] PROGMEM =
{
ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5
};
void RF24::openReadingPipe(uint8_t child, uint64_t address)
{
// If this is pipe 0, cache the address. This is needed because
// openWritingPipe() will overwrite the pipe 0 address, so
// startListening() will have to restore it.
if (child == 0)
pipe0_reading_address = address;
if (child <= 6)
{
// For pipes 2-5, only write the LSB
if ( child < 2 )
write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 5);
else
write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 1);
write_register(pgm_read_byte(&child_payload_size[child]),payload_size);
// Note it would be more efficient to set all of the bits for all open
// pipes at once. However, I thought it would make the calling code
// more simple to do it this way.
write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child])));
}
}
/****************************************************************************/
void RF24::toggle_features(void)
{
csn(LOW);
SPI.transfer( ACTIVATE );
SPI.transfer( 0x73 );
csn(HIGH);
}
/****************************************************************************/
void RF24::enableDynamicPayloads(void)
{
// Enable dynamic payload throughout the system
write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) );
// If it didn't work, the features are not enabled
if ( ! read_register(FEATURE) )
{
// So enable them and try again
toggle_features();
write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) );
}
IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
// Enable dynamic payload on all pipes
//
// Not sure the use case of only having dynamic payload on certain
// pipes, so the library does not support it.
write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0));
dynamic_payloads_enabled = true;
}
/****************************************************************************/
void RF24::enableAckPayload(void)
{
//
// enable ack payload and dynamic payload features
//
write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) );
// If it didn't work, the features are not enabled
if ( ! read_register(FEATURE) )
{
// So enable them and try again
toggle_features();
write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) );
}
IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE)));
//
// Enable dynamic payload on pipes 0 & 1
//
write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0));
}
/****************************************************************************/
void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len)
{
const uint8_t* current = reinterpret_cast<const uint8_t*>(buf);
csn(LOW);
SPI.transfer( W_ACK_PAYLOAD | ( pipe & B111 ) );
const uint8_t max_payload_size = 32;
uint8_t data_len = min(len,max_payload_size);
while ( data_len-- )
SPI.transfer(*current++);
csn(HIGH);
}
/****************************************************************************/
bool RF24::isAckPayloadAvailable(void)
{
bool result = ack_payload_available;
ack_payload_available = false;
return result;
}
/****************************************************************************/
bool RF24::isPVariant(void)
{
return p_variant ;
}
/****************************************************************************/
void RF24::setAutoAck(bool enable)
{
if ( enable )
write_register(EN_AA, B111111);
else
write_register(EN_AA, 0);
}
/****************************************************************************/
void RF24::setAutoAck( uint8_t pipe, bool enable )
{
if ( pipe <= 6 )
{
uint8_t en_aa = read_register( EN_AA ) ;
if( enable )
{
en_aa |= _BV(pipe) ;
}
else
{
en_aa &= ~_BV(pipe) ;
}
write_register( EN_AA, en_aa ) ;
}
}
/****************************************************************************/
bool RF24::testCarrier(void)
{
return ( read_register(CD) & 1 );
}
/****************************************************************************/
bool RF24::testRPD(void)
{
return ( read_register(RPD) & 1 ) ;
}
/****************************************************************************/
void RF24::setPALevel(rf24_pa_dbm_e level)
{
uint8_t setup = read_register(RF_SETUP) ;
setup &= ~(_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ;
// switch uses RAM (evil!)
if ( level == RF24_PA_MAX )
{
setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ;
}
else if ( level == RF24_PA_HIGH )
{
setup |= _BV(RF_PWR_HIGH) ;
}
else if ( level == RF24_PA_LOW )
{
setup |= _BV(RF_PWR_LOW);
}
else if ( level == RF24_PA_MIN )
{
// nothing
}
else if ( level == RF24_PA_ERROR )
{
// On error, go to maximum PA
setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ;
}
write_register( RF_SETUP, setup ) ;
}
/****************************************************************************/
rf24_pa_dbm_e RF24::getPALevel(void)
{
rf24_pa_dbm_e result = RF24_PA_ERROR ;
uint8_t power = read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ;
// switch uses RAM (evil!)
if ( power == (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) )
{
result = RF24_PA_MAX ;
}
else if ( power == _BV(RF_PWR_HIGH) )
{
result = RF24_PA_HIGH ;
}
else if ( power == _BV(RF_PWR_LOW) )
{
result = RF24_PA_LOW ;
}
else
{
result = RF24_PA_MIN ;
}
return result ;
}
/****************************************************************************/
bool RF24::setDataRate(rf24_datarate_e speed)
{
bool result = false;
uint8_t setup = read_register(RF_SETUP) ;
// HIGH and LOW '00' is 1Mbs - our default
wide_band = false ;
setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ;
if( speed == RF24_250KBPS )
{
// Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0
// Making it '10'.
wide_band = false ;
setup |= _BV( RF_DR_LOW ) ;
}
else
{
// Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1
// Making it '01'
if ( speed == RF24_2MBPS )
{
wide_band = true ;
setup |= _BV(RF_DR_HIGH);
}
else
{
// 1Mbs
wide_band = false ;
}
}
write_register(RF_SETUP,setup);
// Verify our result
if ( read_register(RF_SETUP) == setup )
{
result = true;
}
else
{
wide_band = false;
}
return result;
}
/****************************************************************************/
rf24_datarate_e RF24::getDataRate( void )
{
rf24_datarate_e result ;
uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH));
// switch uses RAM (evil!)
// Order matters in our case below
if ( dr == _BV(RF_DR_LOW) )
{
// '10' = 250KBPS
result = RF24_250KBPS ;
}
else if ( dr == _BV(RF_DR_HIGH) )
{
// '01' = 2MBPS
result = RF24_2MBPS ;
}
else
{
// '00' = 1MBPS
result = RF24_1MBPS ;
}
return result ;
}
/****************************************************************************/
void RF24::setCRCLength(rf24_crclength_e length)
{
uint8_t config = read_register(CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ;
// switch uses RAM (evil!)
if ( length == RF24_CRC_DISABLED )
{
// Do nothing, we turned it off above.
}
else if ( length == RF24_CRC_8 )
{
config |= _BV(EN_CRC);
}
else
{
config |= _BV(EN_CRC);
config |= _BV( CRCO );
}
write_register( CONFIG, config ) ;
}
/****************************************************************************/
rf24_crclength_e RF24::getCRCLength(void)
{
rf24_crclength_e result = RF24_CRC_DISABLED;
uint8_t config = read_register(CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ;
if ( config & _BV(EN_CRC ) )
{
if ( config & _BV(CRCO) )
result = RF24_CRC_16;
else
result = RF24_CRC_8;
}
return result;
}
/****************************************************************************/
void RF24::disableCRC( void )
{
uint8_t disable = read_register(CONFIG) & ~_BV(EN_CRC) ;
write_register( CONFIG, disable ) ;
}
/****************************************************************************/
void RF24::setRetries(uint8_t delay, uint8_t count)
{
write_register(SETUP_RETR,(delay&0xf)<<ARD | (count&0xf)<<ARC);
}
// vim:ai:cin:sts=2 sw=2 ft=cpp
| [
"noreply@github.coecis.cornell.edu"
] | noreply@github.coecis.cornell.edu |
985709fdecb867f42f240f6f1072febb52e49733 | 8929c305fc101641cbb615f5f4108a36d9aae9bb | /codeforces/755c.cpp | 56750339e5ad09175d8c5bed297930eed927e776 | [] | no_license | rresol/Practice | 629403d32bc0e2d80ad3769527ca6ab8338593c0 | 13b9bb892af6a051b23db5023a906078849365be | refs/heads/master | 2021-01-12T18:06:27.145251 | 2017-10-04T10:06:11 | 2017-10-04T10:06:11 | 71,325,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | #include<bits/stdc++.h>
using namespace std;
bool visited[10005];
int trace(int parent[], int n, int i )
{
if(visited[i])
return parent[i];
if(parent[i]!=i) {
visited[i] = true;
parent[i] = trace(parent,n,parent[i]);
}
return parent[i];
}
int main()
{
int n;
cin>>n;
int parent[n+1];
int cou[n+1];
memset(cou, 0 ,sizeof(cou));
for(int i=0;i<=n;i++) parent[i] = i;
int p[n+1];
for(int i=1;i<=n;i++)
{
cin>>p[i];
parent[i] = parent[p[i]];
}
for(int i=1;i<=n;i++)
{
trace(parent,n,i);
}
for(int i=1;i<=n;i++)
{
cou[parent[i]] = 1;
}
int ans =0;
for(int i=0;i<=n;i++)
{
if(cou[i])
ans++;
}
cout<<ans<<endl;
}
| [
"shashank.kumar.apc13@itbhu.ac.in"
] | shashank.kumar.apc13@itbhu.ac.in |
fc1d36afa95f48a7bf05dbd16237524615466c1d | 42a27c4eb1a673101a85458243f9f4e7dd5df339 | /Graph/Mother-Vertex.cpp | f60fe24793f87cdccfad32d13be41a94eb3489c1 | [] | no_license | arnavkundalia/Algorithms-and-Data-Structres_Extra | d5234e4e3537af2479a35b98f73d40d1a29f5668 | bf85d18283798605f32b8fed040a9a0a0a96e2cf | refs/heads/master | 2023-03-21T22:08:54.557840 | 2020-07-07T01:07:39 | 2020-07-07T01:07:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | cpp | /*
Problem URL :- https://practice.geeksforgeeks.org/problems/mother-vertex/1
*/
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*
* Function to find if there is a mother vertex in the given graph
* V: number of vertices in the graph
* adj[]: graph representation
*/
void dfs(int src,vector<bool> &vis,vector<int> adj[]){
vis[src]=true;
for(int i=0;i<adj[src].size();i++){
if(vis[adj[src][i]]==false)
dfs(adj[src][i],vis,adj);
}
}
int findMother(int n, vector<int> adj[])
{
int mother=0;
vector<bool> vis(n,false);
for(int i=0;i<n;i++){
if(vis[i]==false)
{
dfs(i,vis,adj);
mother=i;
}
}
vector<bool> visited(n,false);
dfs(mother,visited,adj);
for(int i=0;i<n;i++){
if(visited[i]==false)
mother=-1;
}
return mother;
}
// { Driver Code Starts.
int main()
{
int T;
cin>>T;
while(T--){
int num, edges;
cin>>num>>edges;
vector<int> adj[num];
int u, v;
while(edges--){
cin>>u>>v;
adj[u].push_back(v);
}
cout<<findMother(num, adj)<<endl;
}
return 0;
} // } Driver Code Ends
| [
"gjainiitr@gmail.com"
] | gjainiitr@gmail.com |
6afe2c8298981d8c74aa240d16971f7ef81c1e13 | 61e50889296080d0732a50a49897515fbc23f1b8 | /Lab/Scene.cpp | e05581781d69fdc4cc574079ea7c08a0e5f6833d | [
"MIT"
] | permissive | ysei/fizzim | 8f26c11b0a5b9544d4dae33acf17373c8a2dede4 | 42ccc6b4fa7ac1bc3cc8c35997c03cac159dda3b | refs/heads/master | 2021-01-15T22:34:09.263514 | 2014-01-28T15:41:36 | 2014-01-28T15:41:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,933 | cpp |
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined(__APPLE__) && defined(__MACH__)
#include <OpenGL/gl.h> // Header File For The OpenGL32 Library
#include <OpenGL/glu.h> // Header File For The GLu32 Library
#else
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#endif
#include <fltk/run.h>
#include "Scene.h"
// we make a vanilla stock material always available
DiffuseMaterial gStockMaterial;
Scene* gScene = 0;
void Renderer :: SetViewport(float left, float right, float width, float height) {
m_Left = left;
m_Right = right;
m_Width = width;
m_Height = height;
glViewport((int)left, (int)right, (int)width, (int)height);
}
// cribbed from a flipcode COTD
void Renderer :: ProjectToScreen(PMath::Vec3f& ret, const PMath::Vec3f v) {
double modelView[16];
double projection[16];
double viewport[4];
double depthRange[2];
glGetDoublev(GL_MODELVIEW_MATRIX, modelView);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetDoublev(GL_VIEWPORT, viewport);
glGetDoublev(GL_DEPTH_RANGE, depthRange);
// Compose the matrices into a single row-major transformation
PMath::Vec4f T[4];
int r, c, i;
for (r = 0; r < 4; ++r) {
for (c = 0; c < 4; ++c) {
T[r][c] = k0;
for (i = 0; i < 4; ++i) {
// OpenGL matrices are column major
T[r][c] += (float) (projection[r + i * 4] * modelView[i + c * 4]);
}
}
}
// Transform the vertex
PMath::Vec4f result;
PMath::Vec4f temp;
temp[0] = v[0]; temp[1] = v[1]; temp[2] = v[2]; temp[3] = k1;
for (r = 0; r < 4; ++r) {
result[r] = PMath::Vec4fDot(T[r], temp);
}
// Homogeneous divide
// it might be interesting to return rhw at some point
const double rhw = 1.0 / result[3];
ret[0] = (float)((k1 + result[0] * rhw) * viewport[2] * kHalf + viewport[0]);
ret[1] = (float)((k1 - result[1] * rhw) * viewport[3] * kHalf + viewport[1]);
ret[2] = (float)(( result[2] * rhw) * (depthRange[1] - depthRange[0]) + depthRange[0]);
}
void Renderer :: Render(DrawObject* pObject) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
pObject->LoadMatrix();
pObject->BindMaterial();
pObject->Render();
pObject->UnbindMaterial();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void Renderer :: Render(std::vector<DrawObject*>& objects) {
for (int i = 0; i < (int) objects.size(); ++i) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
objects[i]->LoadMatrix();
objects[i]->BindMaterial();
objects[i]->Render();
objects[i]->UnbindMaterial();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
}
void Renderer :: BeginScene() {
glClearColor(m_BackgroundColor[0], m_BackgroundColor[1], m_BackgroundColor[2], m_BackgroundColor[3]);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
mp_Camera->SetCameraMatrices(m_Width, m_Height);
}
Scene :: Scene() : mp_Renderer(0), mp_Window(0),
m_LightsGroup(0), m_ActorsGroup(0),
m_Browser(0), m_CameraProperties(0), m_PropProperties(0),
m_CameraModel(0), m_ArrowheadModel(0), m_IcosaModel(0),
m_PrimarySelect(&m_Deselected), m_SecondarySelect(&m_Deselected), m_PotentialSelect(&m_Deselected)
{
}
Scene :: ~Scene() {
delete m_GridMaterial;
delete m_DrawGrid;
}
static char timeBuff[128];
void Scene :: Idle() {
TimeVal newTime;
int i;
m_Clock->update();
if (!m_Clock->getPausedState()) {
m_Clock->update();
newTime = m_Clock->getSimulationTime();
Real dt = (Real) (newTime - m_PrevTime);
m_PrevTime = newTime;
dt = PMath::Clamp(dt, k1 / Real(60.0f), k1 / Real(20.0f));
m_Phys.Simulate(dt);
for (i = 0; i < m_PropList.size(); ++i) {
WOT* pObj = m_PropList.m_Objects[i];
int body = pObj->m_Physics;
if (body != 0) {
m_Phys.GetRigidBodyTransformMatrix(body, pObj->mp_Drawn->GetLocalToWorldPtr());
}
}
static TimeVal prevDisplay = 0;
// only display to 1/10 of a second
if (newTime - prevDisplay > 0.09) {
prevDisplay = newTime;
// update time display
int nt = (int) newTime;
int subseconds = (int) (10.0 * (newTime - (TimeVal) nt));
int seconds = nt % 60;
int minutes = nt / 60;
int hours = nt / (60 * 60);
sprintf(timeBuff, "%02d:%02d:%02d.%d", hours, minutes, seconds, subseconds);
m_TimeDisplay->value(timeBuff);
}
}
}
void Scene :: IdleCallback(void* pV) {
Scene* pScene = (Scene*) pV;
pScene->Idle();
}
bool Scene :: Init() {
m_GridMaterial = new DiffuseMaterial();
m_DrawGrid = new DrawGrid(m_GridMaterial, 10, 10);
m_CameraModel = new DrawMesh(&gStockMaterial);
m_ArrowheadModel = new DrawMesh(&gStockMaterial);
m_IcosaModel = new DrawMesh(new DiffuseMaterial());
m_CameraModel->CreateFromOBJFile("data/motioncamera.obj");
m_ArrowheadModel->CreateFromOBJFile("data/arrowhead.obj");
m_IcosaModel->CreateFromOBJFile("data/icosahedron.obj");
mp_Renderer = new Renderer();
m_Clock = new Clock();
m_Clock->update();
m_PrevTime = m_Clock->getSimulationTime();
m_Clock->setPausedState(true);
m_Phys.SetMinTimeStep(1.0f/50.0f);
PMath::Vec3f gravity = {k0, k0, Real(-9.8f)};
m_Phys.SetGravity(gravity);
fltk::add_idle(IdleCallback, this);
return true; ///< @todo check if models successfully loaded
}
void Scene :: CreateCamera(char* pName) {
// create a new camera and push it on the list
CameraWOT* pNewCamera = new CameraWOT();
strcpy(pNewCamera->m_Name, pName);
m_CameraList.m_Objects.push_back(pNewCamera);
// add a widget to the browser
pNewCamera->mp_Widget = AddItem(m_CameraList.m_Group, pNewCamera->m_Name, 1, m_CameraList.m_Icon);
pNewCamera->mp_Widget->callback(SelectCameraFromList);
m_Browser->goto_focus();
PrimarySelect(pNewCamera);
// and set the camera to be the current camera
mp_Renderer->CurrentCamera(&pNewCamera->m_Camera);
}
void Scene :: DupCamera() {
char temp[32];
// remember existing camera settings
Camera* pCamera = mp_Renderer->CurrentCamera();
// create the new camera
sprintf(temp, "Camera %d", m_CameraList.unique());
CreateCamera(temp);
// copy the business from the previos camera into the new one
mp_Renderer->CurrentCamera()->Set(*pCamera);
}
void Scene :: AddProp(DrawObject* pObject, ePropType propType) {
WOT* pProp = new WOT(kSelectProp, pObject);
m_PropList.m_Objects.push_back(pProp);
sprintf(pProp->m_Name, "Prop %d", m_PropList.unique());
pProp->mp_Widget = AddItem(m_PropList.m_Group, pProp->m_Name, 1, m_PropList.m_Icon);
pProp->mp_Widget->callback(SelectPropFromList);
if (propType == kSphere) {
PMath::Vec3f spherePos;
pObject->GetWorldPosition(spherePos);
pProp->m_Physics = m_Phys.AddRigidBodySphere(1.0f);
m_Phys.SetRigidBodyVec3f(pProp->m_Physics, Physics::Engine::propPosition, spherePos);
m_Phys.SetRigidBodyBool(pProp->m_Physics, Physics::Engine::propCollidable, true);
m_Phys.SetRigidBodyBool(pProp->m_Physics, Physics::Engine::propTranslatable, true);
}
}
void Scene :: AddSet(DrawObject* pObject, eSetType setType) {
SetWOT* pSet = new SetWOT(pObject);
m_SetList.m_Objects.push_back(pSet);
sprintf(pSet->m_Name, "Set %d", m_SetList.unique());
pSet->mp_Widget = AddItem(m_SetList.m_Group, pSet->m_Name, 1, m_SetList.m_Icon);
pSet->mp_Widget->callback(SelectSetFromList);
if (setType == kInfinitePlane) {
PMath::Vec3f origin;
pObject->GetPosition(origin);
PMath::Vec3f up;
Real* pMatrix = pObject->GetLocalToWorldPtr();
up[0] = pMatrix[2];
up[1] = pMatrix[6];
up[2] = pMatrix[10];
PMath::Plane plane(origin, up);
pSet->m_Physics = m_Phys.AddRigidBodyPlane(plane);
m_Phys.SetRigidBodyBool(pSet->m_Physics, Physics::Engine::propCollidable, true);
m_Phys.SetRigidBodyBool(pSet->m_Physics, Physics::Engine::propTranslatable, false);
}
}
void Scene :: Deselect() {
m_PrimarySelect = &m_Deselected;
m_SecondarySelect = &m_Deselected;
m_PotentialSelect = &m_Deselected;
HideAllProperties();
}
void Scene :: SelectCameraFromList(fltk::Widget* pWidget, void* pWindow) {
int i = gScene->m_CameraList.FindWidget(pWidget);
if (i != -1) {
gScene->PrimarySelect(gScene->m_CameraList.m_Objects[i]);
}
}
void Scene :: SelectPropFromList(fltk::Widget* pWidget, void* pWindow) {
int i = gScene->m_PropList.FindWidget(pWidget);
if (i != -1) {
gScene->PrimarySelect(gScene->m_PropList.m_Objects[i]);
}
}
void Scene :: PrimarySelect(WOT* pWOT) {
HideAllProperties();
m_PrimarySelect = (pWOT != 0) ? pWOT : &m_Deselected;
if (pWOT->Kind() == kSelectCamera) {
m_CameraPropertyName->value(pWOT->mp_Widget->label());
m_CameraProperties->show();
}
else if (pWOT->Kind() == kSelectProp) {
m_PropPropertyName->value(pWOT->mp_Widget->label());
m_PropProperties->show();
bool active = m_Phys.GetRigidBodyBool(pWOT->m_Physics, Physics::Engine::propActive);
m_PropActive->value(active);
}
else if (pWOT->Kind() == kSelectSet) {
m_SetPropertyName->value(pWOT->mp_Widget->label());
m_SetProperties->show();
bool collider = m_Phys.GetRigidBodyBool(pWOT->m_Physics, Physics::Engine::propCollidable);
m_SetCollider->value(collider);
}
}
void Scene :: SecondarySelect(WOT* pWOT) {
m_SecondarySelect = (pWOT != 0) ? pWOT : &m_Deselected;
}
void Scene :: PotentialSelect(WOT* pWOT) {
m_PotentialSelect = (pWOT != 0) ? pWOT : &m_Deselected;
}
void Scene :: SelectSetFromList(fltk::Widget* pWidget, void* pWindow) {
int i = gScene->m_SetList.FindWidget(pWidget);
if (i != -1) {
gScene->PrimarySelect(gScene->m_SetList.m_Objects[i]);
gScene->mp_Window->redraw();
}
}
void Scene::SceneList :: Render() {
for (int i = 0; i < size(); ++i) {
DrawObject* pDraw = m_Objects[i]->mp_Drawn;
if (pDraw->Visible()) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
pDraw->LoadMatrix();
pDraw->BindMaterial();
pDraw->Render();
pDraw->UnbindMaterial();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
}
}
int Scene::SceneList :: FindWidget(fltk::Widget* pWidget) {
int ret = -1;
for (int i = 0; i < (int) m_Objects.size(); ++i) {
if (pWidget == m_Objects[i]->mp_Widget) { // found the widget?
ret = i;
break;
}
}
return ret;
}
int Scene::SceneList :: FindObject(Renderer* pRenderer, float x, float y) {
int ret = -1;
float distance = 1.0e6f;
PMath::Vec3f position, objectPosition;
position[0] = x;
position[1] = y;
for (int i = 0; i < (int) m_Objects.size(); ++i) {
DrawObject* pDraw = m_Objects[i]->mp_Drawn;
if (pDraw && pDraw->Visible()) {
pDraw->GetPosition(objectPosition);
PMath::Mat44Transform3x3(objectPosition, (Real const*const) pDraw->GetLocalToWorldPtr(), objectPosition);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
pDraw->LoadMatrix();
pRenderer->ProjectToScreen(objectPosition, objectPosition);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
position[2] = objectPosition[2];
float dist = PMath::Vec3fDistance(position, objectPosition);
if (dist < 40.0f) {
if (dist < distance) {
ret = i;
}
}
}
}
return ret;
}
| [
""
] | |
d37666163603082eed792c5617b5b2120818e026 | 077b52d6bf4438d2e0172531ba6acb27b1aaf8dd | /Inheritance/6/controller.hpp | b78842707e42d7c438dc98a5e0b53e6c1c106a88 | [] | no_license | bmvskii/OOP | a41ccf5a9862f6f112e8a82a25462bac4c605a64 | 810ad97eb418024cfac7beb66a8fff76cae73b90 | refs/heads/master | 2020-03-25T02:03:42.824530 | 2019-08-01T13:31:00 | 2019-08-01T13:31:00 | 143,271,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,467 | hpp | // (C) 2013-2016, Sergei Zaychenko, KNURE, Kharkiv, Ukraine
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
/*****************************************************************************/
#include "date.hpp"
#include "expirypolicykind.hpp"
#include "utils.hpp"
#include <string>
#include <unordered_map>
#include <memory>
/*****************************************************************************/
class ExpiryPolicy;
class Consignment;
class Controller
{
/*-----------------------------------------------------------------*/
public:
/*-----------------------------------------------------------------*/
Controller();
Controller(const Controller &) = delete;
Controller & operator = (const Controller &) = delete;
~Controller();
/*-----------------------------------------------------------------*/
void createConsignment(
std::string const & _productName
, double _initialAmount
, Date const & _date
, double _price
, ExpiryPolicyKind _expiryPolicyKind
, int _expiresDays = -1
);
double getConsignmentAmount(std::string const & _productName) const;
double getConsignmentPrice(std::string const & _productName) const;
Date getConsignmentProductionDate(std::string const & _productName) const;
ExpiryPolicyKind getConsignmentExpiryPolicyKind(std::string const & _productName) const;
bool isConsignmentExpired(std::string const & _productName) const;
/*-----------------------------------------------------------------*/
double getTotalFreshCost() const;
double getConsignmentFreshCost(std::string const & _productName) const;
double getTotalExpiredCost() const;
double getConsignmentExpiredCost(std::string const & _productName) const;
/*-----------------------------------------------------------------*/
void sell(std::string const & _productName, double _amount);
/*-----------------------------------------------------------------*/
void setCurrentDate(Date _date);
/*-----------------------------------------------------------------*/
private:
/*-----------------------------------------------------------------*/
std::unordered_map<std::string, std::unique_ptr<ExpiryPolicy> > m_policies;
std::unordered_map<std::string, std::unique_ptr<Consignment> > m_consignments;
Date m_currentDate = Date();
/*-----------------------------------------------------------------*/
};
/*****************************************************************************/
#endif // _CONTROLLER_HPP_ | [
"evg.rogovoy@gmail.com"
] | evg.rogovoy@gmail.com |
7c96d7e577edbfdfe3d7c0c0c9d206aaf0d09a89 | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/include/Gwen/ToolTip.h | d446649983df8c8f5704919ee46fef295c36d18e | [
"MIT",
"Zlib"
] | permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#pragma once
#include "Gwen/Controls/Base.h"
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
using namespace Gwen;
using namespace Gwen::Controls;
namespace ToolTip
{
GWEN_EXPORT void Enable ( Controls::Base* pControl );
GWEN_EXPORT void Disable ( Controls::Base* pControl );
GWEN_EXPORT void ControlDeleted ( Controls::Base* pControl );
GWEN_EXPORT void RenderToolTip ( Skin::Base* skin );
}
| [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
] | haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793 |
867f204b2eacf5487a0269205d9f9778566d3246 | 891b7bfb6798411a4d41e958a4bd1c622776a215 | /OpenGLQtApp/DockFrame.cpp | 997612ec19df095de288effd034d2d13dd313984 | [] | no_license | leonhardrocha-zz/OpenGLApplication | b078453c2b97775adb84eaaaa5ae838d40e3957e | 8b8ea087f8e62b118af980718b12f8e515e5838d | refs/heads/master | 2022-10-11T20:07:13.276709 | 2014-04-25T14:58:01 | 2014-04-25T14:58:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,420 | cpp | #include "DockFrame.h"
QColor bgColorForName(const QString &name)
{
if (name == "Black")
return QColor("#D8D8D8");
else if (name == "White")
return QColor("#F1F1F1");
else if (name == "Red")
return QColor("#F1D8D8");
else if (name == "Green")
return QColor("#D8E4D8");
else if (name == "Blue")
return QColor("#D8D8F1");
else if (name == "Yellow")
return QColor("#F1F0D8");
return QColor(name).light(110);
}
QColor fgColorForName(const QString &name)
{
if (name == "Black")
return QColor("#6C6C6C");
else if (name == "White")
return QColor("#F8F8F8");
else if (name == "Red")
return QColor("#F86C6C");
else if (name == "Green")
return QColor("#6CB26C");
else if (name == "Blue")
return QColor("#6C6CF8");
else if (name == "Yellow")
return QColor("#F8F76C");
return QColor(name);
}
DockFrame::DockFrame(const QString &c, QWidget *parent)
: QFrame(parent) , color(c)
{
QFont font = this->font();
font.setPointSize(8);
setFont(font);
szHint = QSize(-1, -1);
minSzHint = QSize(125, 75);
}
QSize DockFrame::sizeHint() const
{
return szHint;
}
QSize DockFrame::minimumSizeHint() const
{
return minSzHint;
}
void DockFrame::paintEvent(QPaintEvent *e)
{
#ifdef DEBUG_SIZEHINTS
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.fillRect(rect(), bgColorForName(color));
p.save();
extern void render_qt_text(QPainter *, int, int, const QColor &);
render_qt_text(&p, width(), height(), fgColorForName(color));
p.restore();
p.setRenderHint(QPainter::Antialiasing, false);
QSize sz = size();
QSize szHint = sizeHint();
QSize minSzHint = minimumSizeHint();
QSize maxSz = maximumSize();
QString text = QString::fromLatin1("sz: %1x%2\nszHint: %3x%4\nminSzHint: %5x%6\n"
"maxSz: %8x%9")
.arg(sz.width()).arg(sz.height())
.arg(szHint.width()).arg(szHint.height())
.arg(minSzHint.width()).arg(minSzHint.height())
.arg(maxSz.width()).arg(maxSz.height());
QRect r = fontMetrics().boundingRect(rect(), Qt::AlignLeft|Qt::AlignTop, text);
r.adjust(-2, -2, 1, 1);
p.translate(4, 4);
QColor bg = Qt::yellow;
bg.setAlpha(120);
p.setBrush(bg);
p.setPen(Qt::black);
p.drawRect(r);
p.drawText(rect(), Qt::AlignLeft|Qt::AlignTop, text);
#endif // DEBUG_SIZEHINTS
}
static QSpinBox *createSpinBox(int value, QWidget *parent, int max = 1000)
{
QSpinBox *result = new QSpinBox(parent);
result->setMinimum(-1);
result->setMaximum(max);
result->setValue(value);
return result;
}
void DockFrame::changeSizeHints()
{
QDialog dialog(this);
dialog.setWindowTitle(color);
QVBoxLayout *topLayout = new QVBoxLayout(&dialog);
QGridLayout *inputLayout = new QGridLayout();
topLayout->addLayout(inputLayout);
inputLayout->addWidget(new QLabel(tr("Size Hint:"), &dialog), 0, 0);
inputLayout->addWidget(new QLabel(tr("Min Size Hint:"), &dialog), 1, 0);
inputLayout->addWidget(new QLabel(tr("Max Size:"), &dialog), 2, 0);
inputLayout->addWidget(new QLabel(tr("Dockwgt Max Size:"), &dialog), 3, 0);
QSpinBox *szHintW = createSpinBox(szHint.width(), &dialog);
inputLayout->addWidget(szHintW, 0, 1);
QSpinBox *szHintH = createSpinBox(szHint.height(), &dialog);
inputLayout->addWidget(szHintH, 0, 2);
QSpinBox *minSzHintW = createSpinBox(minSzHint.width(), &dialog);
inputLayout->addWidget(minSzHintW, 1, 1);
QSpinBox *minSzHintH = createSpinBox(minSzHint.height(), &dialog);
inputLayout->addWidget(minSzHintH, 1, 2);
QSize maxSz = maximumSize();
QSpinBox *maxSzW = createSpinBox(maxSz.width(), &dialog, QWIDGETSIZE_MAX);
inputLayout->addWidget(maxSzW, 2, 1);
QSpinBox *maxSzH = createSpinBox(maxSz.height(), &dialog, QWIDGETSIZE_MAX);
inputLayout->addWidget(maxSzH, 2, 2);
QSize dwMaxSz = parentWidget()->maximumSize();
QSpinBox *dwMaxSzW = createSpinBox(dwMaxSz.width(), &dialog, QWIDGETSIZE_MAX);
inputLayout->addWidget(dwMaxSzW, 3, 1);
QSpinBox *dwMaxSzH = createSpinBox(dwMaxSz.height(), &dialog, QWIDGETSIZE_MAX);
inputLayout->addWidget(dwMaxSzH, 3, 2);
inputLayout->setColumnStretch(1, 1);
inputLayout->setColumnStretch(2, 1);
topLayout->addStretch();
QHBoxLayout *buttonBox = new QHBoxLayout();
topLayout->addLayout(buttonBox);
QPushButton *okButton = new QPushButton(tr("Ok"), &dialog);
QPushButton *cancelButton = new QPushButton(tr("Cancel"), &dialog);
connect(okButton, SIGNAL(clicked()), &dialog, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()), &dialog, SLOT(reject()));
buttonBox->addStretch();
buttonBox->addWidget(cancelButton);
buttonBox->addWidget(okButton);
if (!dialog.exec())
return;
szHint = QSize(szHintW->value(), szHintH->value());
minSzHint = QSize(minSzHintW->value(), minSzHintH->value());
maxSz = QSize(maxSzW->value(), maxSzH->value());
setMaximumSize(maxSz);
dwMaxSz = QSize(dwMaxSzW->value(), dwMaxSzH->value());
parentWidget()->setMaximumSize(dwMaxSz);
updateGeometry();
update();
}
void DockFrame::setCustomSizeHint(const QSize &size)
{
szHint = size;
updateGeometry();
} | [
"leonhardrocha@gmail.com"
] | leonhardrocha@gmail.com |
a150c8a88a62023e2020ccb5f5039f78092cb977 | f9bb5344bbec438b252d29197e35e60be57f7c58 | /g2o/src/g2o/core/robust_kernel_impl.cpp | 6363c7df0e183a0ecbf24ee03b75eba46bfa917b | [] | no_license | tanzby/orb_slam2 | 360796b4181dee161ef74ceb9c606d064a6fb3a0 | 95058cbc11a1db948fb91d89bdd8e46b5c33fe2b | refs/heads/master | 2020-09-15T02:26:37.623560 | 2019-11-22T06:04:16 | 2019-11-22T06:04:16 | 223,325,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,654 | cpp | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "robust_kernel_impl.h"
#include "robust_kernel_factory.h"
#include <cmath>
namespace g2o {
RobustKernelScaleDelta::RobustKernelScaleDelta(const RobustKernelPtr &kernel, double delta) :
RobustKernel(delta),
_kernel(kernel) {
}
RobustKernelScaleDelta::RobustKernelScaleDelta(double delta) :
RobustKernel(delta) {
}
void RobustKernelScaleDelta::setKernel(const RobustKernelPtr &ptr) {
_kernel = ptr;
}
void RobustKernelScaleDelta::robustify(double error, Eigen::Vector3d &rho) const {
if (_kernel.get()) {
double dsqr = _delta * _delta;
double dsqrReci = 1. / dsqr;
_kernel->robustify(dsqrReci * error, rho);
rho[0] *= dsqr;
rho[2] *= dsqrReci;
} else { // no robustification
rho[0] = error;
rho[1] = 1.;
rho[2] = 0.;
}
}
void RobustKernelHuber::setDelta(double delta) {
dsqr = delta * delta;
_delta = delta;
}
void RobustKernelHuber::setDeltaSqr(const double &delta, const double &deltaSqr) {
dsqr = deltaSqr;
_delta = delta;
}
void RobustKernelHuber::robustify(double e, Eigen::Vector3d &rho) const {
//dsqr = _delta * _delta;
if (e <= dsqr) { // inlier
rho[0] = e;
rho[1] = 1.;
rho[2] = 0.;
} else { // outlier
double sqrte = sqrt(e); // absolut value of the error
rho[0] = 2 * sqrte * _delta - dsqr; // rho(e) = 2 * delta * e^(1/2) - delta^2
rho[1] = _delta / sqrte; // rho'(e) = delta / sqrt(e)
rho[2] = -0.5 * rho[1] / e; // rho''(e) = -1 / (2*e^(3/2)) = -1/2 * (delta/e) / e
}
}
void RobustKernelTukey::setDeltaSqr(const double &deltaSqr, const double &inv) {
_deltaSqr = deltaSqr;
_invDeltaSqr = inv;
}
void RobustKernelTukey::robustify(double e, Eigen::Vector3d &rho) const {
if (e <= _deltaSqr) { // inlier
double factor = e * _invDeltaSqr;
double d = 1 - factor;
double dd = d * d;
rho[0] = _deltaSqr * (1 - dd * d);
rho[1] = 3 * dd;
rho[2] = -6 * _invDeltaSqr * d;
} else { // outlier
rho[0] = _deltaSqr; // rho(e) = delta^2
rho[1] = 0.;
rho[2] = 0.;
}
}
void RobustKernelPseudoHuber::robustify(double e2, Eigen::Vector3d &rho) const {
double dsqr = _delta * _delta;
double dsqrReci = 1. / dsqr;
double aux1 = dsqrReci * e2 + 1.0;
double aux2 = sqrt(aux1);
rho[0] = 2 * dsqr * (aux2 - 1);
rho[1] = 1. / aux2;
rho[2] = -0.5 * dsqrReci * rho[1] / aux1;
}
void RobustKernelCauchy::robustify(double e2, Eigen::Vector3d &rho) const {
double dsqr = _delta * _delta;
double dsqrReci = 1. / dsqr;
double aux = dsqrReci * e2 + 1.0;
rho[0] = dsqr * log(aux);
rho[1] = 1. / aux;
rho[2] = -dsqrReci * std::pow(rho[1], 2);
}
void RobustKernelSaturated::robustify(double e2, Eigen::Vector3d &rho) const {
double dsqr = _delta * _delta;
if (e2 <= dsqr) { // inlier
rho[0] = e2;
rho[1] = 1.;
rho[2] = 0.;
} else { // outlier
rho[0] = dsqr;
rho[1] = 0.;
rho[2] = 0.;
}
}
//delta is used as $phi$
void RobustKernelDCS::robustify(double e2, Eigen::Vector3d &rho) const {
const double &phi = _delta;
double scale = (2.0 * phi) / (phi + e2);
if (scale >= 1.0)
scale = 1.0;
rho[0] = scale * e2 * scale;
rho[1] = (scale * scale);
rho[2] = 0;
}
// register the kernel to their factory
G2O_REGISTER_ROBUST_KERNEL(Huber, RobustKernelHuber)
G2O_REGISTER_ROBUST_KERNEL(Tukey, RobustKernelTukey)
G2O_REGISTER_ROBUST_KERNEL(PseudoHuber, RobustKernelPseudoHuber)
G2O_REGISTER_ROBUST_KERNEL(Cauchy, RobustKernelCauchy)
G2O_REGISTER_ROBUST_KERNEL(Saturated, RobustKernelSaturated)
G2O_REGISTER_ROBUST_KERNEL(DCS, RobustKernelDCS)
} // end namespace g2o
| [
"tanzby@outlook.com"
] | tanzby@outlook.com |
9f1d7a836cd408cc3b262b49250af198886dac95 | d86abcfa1266a8e6de573b197fd9a30c4bf7c1d5 | /tests/test_endpoint_set.cpp | e301b711625fbc5cb725d5d0bb3d6e1ccb9fc210 | [] | no_license | berkus/libuia | 68872f357ca28442f056b72f8b466e8c37ef0bb0 | 60adbe3669fae75a037aa1ff0b17569b1a4c335c | refs/heads/master | 2023-07-10T23:00:53.681151 | 2016-03-15T18:19:51 | 2016-03-15T18:19:51 | 43,468,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | cpp | //
// Part of Metta OS. Check http://atta-metta.net for latest version.
//
// Copyright 2007 - 2014, Stanislav Karchebnyy <berkus@atta-metta.net>
//
// Distributed under the Boost Software License, Version 1.0.
// (See file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)
//
#define BOOST_TEST_MODULE Test_endpoint_set
#include <boost/test/unit_test.hpp>
#include "uia/comm/endpoint_set.h"
using namespace std;
using namespace uia;
using namespace uia::comm;
struct EpsFixture
{
endpoint_set eps{
endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 1024),
endpoint(boost::asio::ip::address::from_string("192.168.0.1"), 1024),
endpoint(boost::asio::ip::address::from_string("192.168.10.255"), 1024),
endpoint(boost::asio::ip::address::from_string("10.0.0.1"), 1024),
endpoint(boost::asio::ip::address::from_string("10.10.10.1"), 1024),
endpoint(boost::asio::ip::address::from_string("8.8.8.8"), 1024),
endpoint(boost::asio::ip::address::from_string("0.0.0.1"), 1024),
endpoint(boost::asio::ip::address::from_string("::fff1"), 1024),
endpoint(boost::asio::ip::address::from_string("::1"), 1024),
// own endpoint address
endpoint(boost::asio::ip::address::from_string("85.253.73.240"), 1024),
// presumable gateway addresses
endpoint(boost::asio::ip::address::from_string("85.253.73.1"), 1024),
endpoint(boost::asio::ip::address::from_string("85.253.73.2"), 1024),
endpoint(boost::asio::ip::address::from_string("85.253.73.255"), 1024),
endpoint(boost::asio::ip::address::from_string("85.253.73.254"), 1024),
};
};
BOOST_FIXTURE_TEST_CASE(ipv4_simple_affinity, EpsFixture)
{
endpoint my_ep(boost::asio::ip::address::from_string("85.253.73.240"), 1024);
cout << "Endpoints near " << my_ep << endl;
for (auto x : eps.affinity_sorted_to(my_ep)) {
cout << x << endl;
}
}
BOOST_FIXTURE_TEST_CASE(ipv6_simple_affinity, EpsFixture)
{
endpoint my_ep(boost::asio::ip::address::from_string("::1"), 1024);
cout << "Endpoints near " << my_ep << endl;
for (auto x : eps.affinity_sorted_to(my_ep)) {
cout << x << endl;
}
}
BOOST_AUTO_TEST_CASE(nat_affinity)
{
// Advanced cases - give more affinity to nearby NAT gates
}
| [
"berkus@madfire.net"
] | berkus@madfire.net |
2fe355505f5db5badf0153f93c8f29d5324dd046 | 57439cb79bdd298ffaf096dc081bc61f625ef786 | /serial.cpp | 98ede6e782f79b45c80c1589780f9f590fd0b204 | [] | no_license | 6289526/machine_1_RASPI | cbe21c25c3b24d47889f9c335090994f389b225d | f9fbed081f8b1a0b87b0e246af9dfbc46108f1c8 | refs/heads/master | 2023-07-25T12:49:40.755236 | 2019-08-08T11:01:14 | 2019-08-08T11:01:14 | 403,712,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,529 | cpp | #include "serial.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
////////////////////////////////
// コンストラクタ //
////////////////////////////////
serial::serial(const char* fd_name, unsigned int baud_rate)
{
fd = 0;
int sci_fd;
if(fd_name == nullptr){
return;
}
this->init(fd_name, baud_rate);
}
////////////////////////////////
// デストラクタ //
////////////////////////////////
serial::~serial()
{
if(fd != 0)
this->close();
}
////////////////////////////////
// シリアルポートの初期化関数 //
////////////////////////////////
int serial::init(const char* fd_name, unsigned int baud_rate)
{
fd = 0;
int sci_fd;
printf("open sci:[%s]\n",fd_name);
if ((sci_fd = open(fd_name, O_RDWR | O_NOCTTY | O_NONBLOCK))<0)
{
printf("sci open failed. : %d\n", sci_fd);
return -1;
}
fd = sci_fd;
this->set_baudrate(baud_rate);
return fd;
}
int serial::set_baudrate(unsigned int baud_rate)
{
struct termios tio;
int ret;
memset(&tio,0x00,sizeof(tio));
tio.c_cflag = baud_rate | CRTSCTS | CS8 | CLOCAL | CREAD;
tio.c_iflag = IGNPAR;
tio.c_oflag = 0;
tio.c_lflag = 0;
tio.c_cc[VTIME] = 0;
tio.c_cc[VMIN] = 1;
tcflush(fd, TCIFLUSH);
ret = tcsetattr(fd, TCSANOW, &tio);
fcntl(fd, F_SETFL, FNDELAY);
return ret;
}
//////////////////////////////////
// シリアルポートのクローズ関数 //
//////////////////////////////////
int serial::close()
{
::close(fd);
fd = 0;
return 0;
}
int serial::available(){
int bytes_available = 0;
ioctl(fd, FIONREAD, &bytes_available);
return bytes_available;
}
/////////////////////////////
// シリアル受信関数 //
/////////////////////////////
int serial::read(void *buffer, size_t size)
{
int retval=0;
//サイズが負の場合は1を返す
if(size < 0)
return 1;
while((retval = ::read(fd, buffer, size))<0) {
switch (errno) {
case EAGAIN :
break;
default :
perror(strerror(errno));
return -1;
}
}
return retval;
}
///////////////////////
// シリアル送信関数 //
//////////////////////
int serial::write(void *buffer,size_t size)
{
int retval = ::write(fd, buffer, size);
return retval;
} | [
"48006819+tokudairobocon@users.noreply.github.com"
] | 48006819+tokudairobocon@users.noreply.github.com |
7bbae805edc229f08c699385971b53dd887041d0 | e67ac6db3204e1acdd1cd16178905f63e4510b34 | /Empty project/Src/Core Code/Line2D.cpp | 63983ccdcc4bc97e2d1f81c569ee6554b3f72ebc | [] | no_license | nesa24/bgf3d | fd4959a0d838ff3811de7960630de16f53968c51 | 6e1aa4d451c7f0a1d56c555f6c75b09be6cf1941 | refs/heads/master | 2020-05-02T01:55:48.781811 | 2009-05-21T13:47:28 | 2009-05-21T13:47:28 | 32,896,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | cpp | #include ".\line2d.h"
Line2D::Line2D(void)
{
m_PosStart.x = 0;
m_PosStart.y = 0;
m_PosEnd.x = 0;
m_PosEnd.y = 0;
m_iPrimitiveNbr = iVertexNumberLine2D;
//set initial layer
m_uiLayer = i2DPrimitiveInitLayer;
}
Line2D::~Line2D(void)
{
}
/////////////////////////////////////////////////////////////////
//method override
//different shape will have different method of creating vertex
void Line2D::CreateVertexBuffer()
{
g_pCanvas->GetGraphics()->CreateVertexBuffer( &m_pVertexBuffer, m_iPrimitiveNbr, true);
}
//the update of vertex is also different, accordingly
void Line2D::UpdateVertexBuffer()
{
//init vertex
//Set the layer of the primitive as the layer of the object
const float fLayer = this->GetLayer() / 10000.0f;
const DWORD Color = GetColorDWORD();
//Create vertex according to position and color
CustomVertex2D TempVertex[2] = {
{ m_PosStart.x, m_PosStart.y, fLayer, 0.0f, Color },
{ m_PosEnd.x, m_PosEnd.y, fLayer, 0.0f, Color },
};
//update vertex buffer
g_pCanvas->GetGraphics()->UpdateVertexBuffer( TempVertex, m_pVertexBuffer, sizeof(TempVertex) );
}
//Primitive type
ShapeType Line2D::GetShapeType()
{
return ShapeLine;
}
//3D primitive type
bool Line2D::Is3DShape()
{
return false;
}
/////////////////////////////////////////////////////////////////
//unique method
void Line2D::UpdatePos( const POINT2D PS, const POINT2D PE )
{
m_PosStart = PS;
m_PosEnd = PE;
//update vertex buffer after alter of pos
UpdateVertexBuffer();
}
void Line2D::UpdateColor( const DWORD Color )
{
SetColorDWORD( Color );
//update vertex buffer after alter of color
UpdateVertexBuffer();
}
| [
"lyDASHsBOK@579413f5-764d-0410-af70-c34dc4d35548"
] | lyDASHsBOK@579413f5-764d-0410-af70-c34dc4d35548 |
0a8da2fb4a0ad5bc61127cd784a8fe4de8029ee4 | 008d13edc16c97e93d0b720a504b470c444a4ec7 | /src/ImageLib/src/Filters/Gamma.cpp | 0c16ca81905b0e6d2889168b099e28d2db58bc30 | [
"MIT"
] | permissive | AndreyBuyanov/ImageProcessing | 7f3cab485e64235e30f71eb03eed2d348eba84b4 | 8af677d416ba32d2d4a07e84befbbb25abf5c602 | refs/heads/master | 2022-01-29T02:43:43.521266 | 2022-01-18T12:01:49 | 2022-01-18T12:01:49 | 173,819,198 | 0 | 1 | MIT | 2021-12-05T09:12:10 | 2019-03-04T20:49:48 | C++ | UTF-8 | C++ | false | false | 2,139 | cpp | #include "ImageLib/Filters/Gamma.hpp"
#include "ImageLib/ImageLib.hpp"
#include <cmath>
namespace ImageLib::Filters
{
Gamma::Gamma() :
m_Bitmap(nullptr),
m_ProgressEventHandler(nullptr),
m_FilterControlEventHandler(nullptr),
m_Thread(CreateThread(this)),
m_Gamma(0.01f) {}
void Gamma::ProcessBitmap()
{
m_Thread->Start();
}
void Gamma::SetBitmap(
IBitmap *bitmap)
{
if (m_Thread->IsStopped()) {
m_Bitmap = bitmap;
}
}
void Gamma::RegisterProgressEventHandler(
IProgressEventHandler *handler)
{
if (m_Thread->IsStopped()) {
m_ProgressEventHandler = handler;
}
}
void Gamma::RegisterFilterControlEventHandler(
IFilterControlEventHandler *handler)
{
if (m_Thread->IsStopped()) {
m_FilterControlEventHandler = handler;
}
}
std::string Gamma::GetName() const
{
return "Gamma";
}
void Gamma::SetGamma(
const float gamma)
{
if (m_Thread->IsStopped()) {
m_Gamma = gamma;
}
}
void Gamma::Run()
{
if (m_FilterControlEventHandler) {
m_FilterControlEventHandler->FilterStarted();
}
if (m_Bitmap) {
const float gamma = 1.0f / m_Gamma;
const uint32_t w = m_Bitmap->Width();
const uint32_t h = m_Bitmap->Height();
const uint32_t p = w * 4;
uint8_t *bits = m_Bitmap->Data();
for (uint32_t y = 0; y < h; y++) {
if (m_Thread->IsStopped()) {
break;
}
uint8_t *pixel = bits;
for (uint32_t x = 0; x < w; x++) {
pixel[0] = static_cast<uint8_t>(255.0f * powf(pixel[0] / 255.0f, gamma));
pixel[1] = static_cast<uint8_t>(255.0f * powf(pixel[1] / 255.0f, gamma));
pixel[2] = static_cast<uint8_t>(255.0f * powf(pixel[2] / 255.0f, gamma));
pixel += 4;
}
if (m_ProgressEventHandler) {
m_ProgressEventHandler->UpdateProgress(int32_t(float(y) / h * 100));
}
bits += p;
}
}
if (m_FilterControlEventHandler) {
m_FilterControlEventHandler->FilterFinished();
}
}
}
| [
"andreew.12.87@gmail.com"
] | andreew.12.87@gmail.com |
2594e45e6e8b573d2bce4bdec6b052929433a831 | 7416235b0d156e9778766844141eec453ba5803e | /CPUDrivenGPUTest2/Software_d3d9_Driver/TestProjects/D3D9AlphaTestingTest/D3D9AlphaTestingTest/Main.cpp | 7878b7a32aa4c2d85179398cac58f749378e0492 | [
"Zlib"
] | permissive | code-tom-code/FPGAGPUTesting | 1dd575767226503c014e71337b43990a69870188 | 1ae15035637c1bdabc73fefd66e0046793666447 | refs/heads/master | 2023-08-04T12:02:43.399872 | 2023-08-03T04:29:29 | 2023-08-03T04:29:29 | 222,173,769 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,537 | cpp | #pragma once
#ifdef _DEBUG
#define D3D_DEBUG_INFO 1
#else
#undef D3D_DEBUG_INFO
#endif
#undef UNICODE
#undef _UNICODE
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h> // for printf
#include <d3d9.h> // for D3D9
#include <d3dx9.h> // for D3DX9
#include <vector>
#ifdef _DEBUG
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9d.lib")
#else
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")
#endif
static const char* const windowClassName = "TomsWindowClass";
static const char* const windowName = "TomsWindow";
static const unsigned windowWidth = 640u;
static const unsigned windowHeight = 480u;
static LPDIRECT3D9 d3d9 = NULL;
static LPDIRECT3DDEVICE9 d3d9dev = NULL;
static LPDIRECT3DSURFACE9 originalBackbuffer = NULL;
static LPDIRECT3DTEXTURE9 fenceAlphaTex = NULL;
static LPDIRECT3DTEXTURE9 ventGrateColorKeyTex = NULL;
static LPDIRECT3DTEXTURE9 mazeTex = NULL;
static LPDIRECT3DTEXTURE9 bricksTex = NULL;
static LPDIRECT3DTEXTURE9 blackTex = NULL;
static LPDIRECT3DVERTEXBUFFER9 cubeVB = NULL;
static LPDIRECT3DINDEXBUFFER9 cubeIB = NULL;
static LPDIRECT3DVERTEXBUFFER9 planeVB = NULL;
static LPD3DXMESH teapotMesh = NULL;
struct vert3D
{
D3DXVECTOR3 pos;
D3DCOLOR vertColor;
D3DXVECTOR2 texcoord;
};
static bool bDone = false;
static const unsigned short staticIndices[] =
{
0 + 0, 1 + 0, 2 + 0,
1 + 0, 3 + 0, 2 + 0,
0 + 4, 1 + 4, 2 + 4,
1 + 4, 3 + 4, 2 + 4,
0 + 8, 1 + 8, 2 + 8,
1 + 8, 3 + 8, 2 + 8,
0 + 12, 1 + 12, 2 + 12,
1 + 12, 3 + 12, 2 + 12,
0 + 16, 1 + 16, 2 + 16,
1 + 16, 3 + 16, 2 + 16,
0 + 20, 1 + 20, 2 + 20,
1 + 20, 3 + 20, 2 + 20
};
static inline const int PumpWindowsMessageLoop(HWND wnd)
{
MSG msg = {0};
while (!bDone)
{
if (PeekMessageA(&msg, wnd, 0, 0, PM_NOREMOVE) )
{
switch (GetMessageA(&msg, wnd, 0, 0) )
{
case -1:
printf("Error in GetMessageA. GLE: %u\n", GetLastError() );
return -1;
case 0:
printf("WM_QUIT received, done!\n");
return 0;
default:
TranslateMessage(&msg);
DispatchMessageA(&msg);
break;
}
}
else
{
// No more messages
return 1;
}
}
return 1;
}
static LRESULT CALLBACK MyWindowProc(_In_ HWND hwnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
printf("WM_CLOSE\n");
bDone = true;
break;
}
return DefWindowProcA(hwnd, uMsg, wParam, lParam);
}
static inline void RenderScene0(const long double currentTime)
{
D3DXMATRIXA16 boxRotation, teapotRotation, teapotScale, teapotWorld;
D3DXMatrixRotationY(&boxRotation, (const float)(currentTime / 10.0) );
D3DXMatrixRotationY(&teapotRotation, (const float)(-currentTime / 20.0) );
D3DXMatrixScaling(&teapotScale, 0.5f, 0.5f, 0.5f);
teapotWorld = teapotScale * teapotRotation;
const float alphaSine = (const float)(sin(currentTime * 0.5) * 0.5 + 0.5);
const unsigned alphaRef = (const unsigned)(alphaSine * 255.0f);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3d9dev->SetRenderState(D3DRS_ALPHAREF, alphaRef);
d3d9dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_LESS);
d3d9dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3d9dev->SetStreamSource(0, cubeVB, 0, sizeof(vert3D) );
d3d9dev->SetIndices(cubeIB);
d3d9dev->SetTexture(0, bricksTex);
d3d9dev->SetTransform(D3DTS_WORLD, &boxRotation);
d3d9dev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4*6, 0, 2*6);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
d3d9dev->SetTexture(0, NULL);
d3d9dev->SetTransform(D3DTS_WORLD, &teapotWorld);
teapotMesh->DrawSubset(0);
}
static inline void RenderScene1(const long double currentTime)
{
D3DXMATRIXA16 boxScaledUp;
D3DXMatrixScaling(&boxScaledUp, 4.0f, 4.0f, 4.0f);
d3d9dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3d9dev->SetRenderState(D3DRS_ALPHAREF, 0x60);
d3d9dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
d3d9dev->SetStreamSource(0, planeVB, 0, sizeof(vert3D) );
d3d9dev->SetIndices(NULL);
d3d9dev->SetTexture(0, ventGrateColorKeyTex);
d3d9dev->SetTransform(D3DTS_WORLD, &boxScaledUp);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
static inline void RenderScene2(const long double currentTime)
{
D3DXMATRIXA16 boxScaledUp;
D3DXMatrixScaling(&boxScaledUp, 4.0f, 4.0f, 4.0f);
d3d9dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3d9dev->SetRenderState(D3DRS_ALPHAREF, 0x60);
d3d9dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
d3d9dev->SetStreamSource(0, planeVB, 0, sizeof(vert3D) );
d3d9dev->SetIndices(NULL);
d3d9dev->SetTexture(0, fenceAlphaTex);
d3d9dev->SetTransform(D3DTS_WORLD, &boxScaledUp);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
static inline void RenderScene3(const long double currentTime)
{
D3DXMATRIXA16 boxScaledUp, boxScaledUp2, view;
D3DXMatrixScaling(&boxScaledUp, 4.001f, 4.001f, 4.001f);
D3DXMatrixScaling(&boxScaledUp2, 4.002f, 4.002f, 4.002f);
D3DXVECTOR3 eye(0.0f, 0.0f, -2.05f);
D3DXVECTOR3 at(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
D3DXMatrixLookAtRH(&view, &eye, &at, &up);
d3d9dev->SetTransform(D3DTS_VIEW, &view);
d3d9dev->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
d3d9dev->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
d3d9dev->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
d3d9dev->SetRenderState(D3DRS_ZENABLE, FALSE);
d3d9dev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
d3d9dev->SetStreamSource(0, planeVB, 0, sizeof(vert3D) );
d3d9dev->SetIndices(NULL);
d3d9dev->SetTransform(D3DTS_WORLD, &boxScaledUp);
d3d9dev->SetTexture(0, blackTex);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
d3d9dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3d9dev->SetRenderState(D3DRS_ALPHAREF, 255);
d3d9dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_EQUAL);
d3d9dev->SetTexture(0, mazeTex);
d3d9dev->SetTransform(D3DTS_WORLD, &boxScaledUp);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
unsigned alphaRef = ( (const unsigned)(currentTime * 10.0) ) & 0xFF;
if (alphaRef == 0xFF)
alphaRef = 0x00;
d3d9dev->SetRenderState(D3DRS_ALPHAREF, alphaRef);
d3d9dev->SetTransform(D3DTS_WORLD, &boxScaledUp2);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
/*alphaRef++;
if (alphaRef == 0xFF)
alphaRef = 0x00;
d3d9dev->SetRenderState(D3DRS_ALPHAREF, alphaRef);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
alphaRef++;
if (alphaRef == 0xFF)
alphaRef = 0x00;
d3d9dev->SetRenderState(D3DRS_ALPHAREF, alphaRef);
d3d9dev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);*/
}
static inline void RenderFrame(const long double timeDelta)
{
static long double currentTime = 0.0;
currentTime += timeDelta;
static unsigned sceneID = 0;
if ( (GetAsyncKeyState('0') & 0x8000) || (GetAsyncKeyState('R') & 0x8000) )
sceneID = 0;
else if (GetAsyncKeyState('1') & 0x8000)
sceneID = 1;
else if (GetAsyncKeyState('2') & 0x8000)
sceneID = 2;
else if (GetAsyncKeyState('3') & 0x8000)
sceneID = 3;
switch (sceneID)
{
default:
case 0:
case 3:
d3d9dev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(127, 127, 127), 1.0f, 0x00000000);
break;
case 1:
case 2:
d3d9dev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0x00000000);
break;
}
d3d9dev->BeginScene();
// Set our global renderstates here:
d3d9dev->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0) );
d3d9dev->SetRenderState(D3DRS_LIGHTING, FALSE);
d3d9dev->SetRenderState(D3DRS_COLORVERTEX, TRUE);
d3d9dev->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1);
d3d9dev->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
d3d9dev->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
d3d9dev->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
d3d9dev->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
d3d9dev->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
d3d9dev->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
d3d9dev->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
d3d9dev->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
d3d9dev->SetRenderState(D3DRS_ZENABLE, TRUE);
D3DXMATRIXA16 world, view, proj;
D3DXMatrixIdentity(&world);
D3DXVECTOR3 eye(0.0f, 1.5f, -1.5f);
D3DXVECTOR3 at(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
D3DXMatrixLookAtRH(&view, &eye, &at, &up);
D3DXMatrixPerspectiveFovRH(&proj, D3DXToRadian(90.0f), 640.0f / 480.0f, 0.01f, 100.0f);
d3d9dev->SetTransform(D3DTS_WORLD, &world);
d3d9dev->SetTransform(D3DTS_VIEW, &view);
d3d9dev->SetTransform(D3DTS_PROJECTION, &proj);
// Render stuff here!
switch (sceneID)
{
default:
case 0:
RenderScene0(currentTime);
break;
case 1:
RenderScene1(currentTime);
break;
case 2:
RenderScene2(currentTime);
break;
case 3:
RenderScene3(currentTime);
break;
}
d3d9dev->EndScene();
d3d9dev->Present(NULL, NULL, NULL, NULL);
}
// Make sure to call free() on the memory after you're done with it
DWORD* const LoadShaderToMemory(const char* const filename)
{
if (!filename)
{
printf("Error: NULL filename passed to LoadShaderToMemory!\n");
return NULL;
}
if (!*filename)
{
printf("Error: Empty filename passed to LoadShaderToMemory!\n");
return NULL;
}
char buffer[MAX_PATH] = {0};
#pragma warning(push)
#pragma warning(disable:4996)
sprintf(buffer, "%s.cso", filename);
#pragma warning(pop)
HANDLE hFile = CreateFileA(buffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
#pragma warning(push)
#pragma warning(disable:4996)
#ifdef _DEBUG
sprintf(buffer, "..\\Debug\\%s.cso", filename);
#else
sprintf(buffer, "..\\Release\\%s.cso", filename);
#endif
#pragma warning(pop)
hFile = CreateFileA(buffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("Error: Cannot open file \"%s\" for reading!\n", filename);
return NULL;
}
}
const DWORD fileSize = GetFileSize(hFile, NULL);
if (!fileSize)
{
CloseHandle(hFile);
printf("Error getting file size\n");
return NULL;
}
DWORD* const data = (DWORD* const)malloc(fileSize);
if (!data)
{
CloseHandle(hFile);
printf("Error mallocing %u bytes!\n", fileSize);
return NULL;
}
DWORD bytesRead = 0;
if (!ReadFile(hFile, data, fileSize, &bytesRead, NULL) || bytesRead != fileSize)
{
free(data);
CloseHandle(hFile);
printf("Error in ReadFile!\n");
return NULL;
}
CloseHandle(hFile);
return data;
}
LPDIRECT3DPIXELSHADER9 LoadPixelShader(const char* const filename)
{
DWORD* const shaderMemory = LoadShaderToMemory(filename);
LPDIRECT3DPIXELSHADER9 ret = NULL;
if (FAILED(d3d9dev->CreatePixelShader(shaderMemory, &ret) ) || !ret)
{
free(shaderMemory);
printf("Error in CreatePixelShader!\n");
return NULL;
}
free(shaderMemory);
return ret;
}
LPDIRECT3DVERTEXSHADER9 LoadVertexShader(const char* const filename)
{
DWORD* const shaderMemory = LoadShaderToMemory(filename);
LPDIRECT3DVERTEXSHADER9 ret = NULL;
if (FAILED(d3d9dev->CreateVertexShader(shaderMemory, &ret) ) || !ret)
{
free(shaderMemory);
printf("Error in CreateVertexShader!\n");
return NULL;
}
free(shaderMemory);
return ret;
}
void AddDissolveAlphaToBricksTex(LPDIRECT3DTEXTURE9 bricksTex)
{
D3DLOCKED_RECT d3dlr = {0};
D3DSURFACE_DESC desc = {};
bricksTex->GetLevelDesc(0, &desc);
bricksTex->LockRect(0, &d3dlr, NULL, 0);
D3DCOLOR* const startingTexel = (D3DCOLOR* const)d3dlr.pBits;
for (unsigned y = 0; y < desc.Height; ++y)
{
D3DCOLOR* const rowStart = (D3DCOLOR* const)( (const char* const)startingTexel + d3dlr.Pitch * y);
for (unsigned x = 0; x < desc.Width; ++x)
{
D3DCOLOR& thisTexel = rowStart[x];
const unsigned texelB = thisTexel & 0xFF;
const unsigned texelG = (thisTexel >> 8) & 0xFF;
const unsigned texelR = (thisTexel >> 16) & 0xFF;
const unsigned texelA = 255 - (rand() % 224 + 16); // Invert our alpha so that we can use D3DCMP_LESS as the alpha-test
thisTexel = D3DCOLOR_ARGB(texelA, texelR, texelG, texelB);
}
}
bricksTex->UnlockRect(0);
}
struct uint2
{
unsigned x;
unsigned y;
inline const bool operator==(const uint2& rhs) const
{
return x == rhs.x && y == rhs.y;
}
};
static inline const bool IsTexelMazePath(const D3DCOLOR color)
{
const unsigned thisColorR = (color >> 16) & 0xFF;
return thisColorR > 0x80;
}
static inline const bool IsPointAlreadyInSet(const uint2& newPoint, const std::vector<uint2>& foundMazePoints)
{
const unsigned numPoints = (const unsigned)foundMazePoints.size();
for (unsigned x = 0; x < numPoints; ++x)
{
if (newPoint == foundMazePoints[x])
return true;
}
return false;
}
void AddAlphaToMazeTex(LPDIRECT3DTEXTURE9 mazeTex)
{
D3DLOCKED_RECT d3dlr = {0};
D3DSURFACE_DESC desc = {};
mazeTex->GetLevelDesc(0, &desc);
mazeTex->LockRect(0, &d3dlr, NULL, 0);
std::vector<uint2> foundMazePathInOrder;
std::vector<D3DCOLOR> textureCopy;
textureCopy.resize(128 * 128);
D3DCOLOR* const startingTexel = (D3DCOLOR* const)d3dlr.pBits;
for (unsigned y = 0; y < desc.Height; ++y)
{
D3DCOLOR* const rowStart = (D3DCOLOR* const)( (const char* const)startingTexel + d3dlr.Pitch * y);
memcpy(&textureCopy[y * 128], rowStart, 128 * sizeof(D3DCOLOR) );
}
unsigned firstMazeLineFound = 0;
for (unsigned x = 0; x < 128; ++x)
{
const D3DCOLOR thisTexel = textureCopy[x];
if (IsTexelMazePath(thisTexel) )
{
firstMazeLineFound = x;
break;
}
}
uint2 startingPos = { firstMazeLineFound, 0 };
foundMazePathInOrder.push_back(startingPos);
while (true)
{
const uint2 currentPos = foundMazePathInOrder.back();
const D3DCOLOR* const currentTexel = &textureCopy[currentPos.y * 128 + currentPos.x];
const D3DCOLOR* rightTexel = NULL;
const D3DCOLOR* leftTexel = NULL;
const D3DCOLOR* topTexel = NULL;
const D3DCOLOR* bottomTexel = NULL;
uint2 rightPoint, leftPoint, topPoint, bottomPoint;
if (currentPos.x < 127)
{
rightPoint = currentPos;
rightPoint.x += 1;
rightTexel = &textureCopy[rightPoint.y * 128 + rightPoint.x];
}
if (currentPos.x > 0)
{
leftPoint = currentPos;
leftPoint.x -= 1;
leftTexel = &textureCopy[leftPoint.y * 128 + leftPoint.x];
}
if (currentPos.y > 0)
{
topPoint = currentPos;
topPoint.y -= 1;
topTexel = &textureCopy[topPoint.y * 128 + topPoint.x];
}
if (currentPos.y < 127)
{
bottomPoint = currentPos;
bottomPoint.y += 1;
bottomTexel = &textureCopy[bottomPoint.y * 128 + bottomPoint.x];
}
if (rightTexel && IsTexelMazePath(*rightTexel) && !IsPointAlreadyInSet(rightPoint, foundMazePathInOrder) )
{
foundMazePathInOrder.push_back(rightPoint);
}
else if (leftTexel && IsTexelMazePath(*leftTexel) && !IsPointAlreadyInSet(leftPoint, foundMazePathInOrder) )
{
foundMazePathInOrder.push_back(leftPoint);
}
else if (topTexel && IsTexelMazePath(*topTexel) && !IsPointAlreadyInSet(topPoint, foundMazePathInOrder) )
{
foundMazePathInOrder.push_back(topPoint);
}
else if (bottomTexel && IsTexelMazePath(*bottomTexel) && !IsPointAlreadyInSet(bottomPoint, foundMazePathInOrder) )
{
foundMazePathInOrder.push_back(bottomPoint);
}
else
{
// We're done! No more points to be discovered
break;
}
}
const unsigned numMazeLineEntries = (const unsigned)foundMazePathInOrder.size();
const float iterAlpha = 254.0f / numMazeLineEntries;
float currentAlpha = 0.0f;
for (unsigned mazeLineIndex = 0; mazeLineIndex < numMazeLineEntries; ++mazeLineIndex)
{
const uint2& thisPoint = foundMazePathInOrder[mazeLineIndex];
D3DCOLOR* const rowStart = (D3DCOLOR* const)( (const char* const)startingTexel + d3dlr.Pitch * thisPoint.y);
D3DCOLOR& thisTexel = rowStart[thisPoint.x];
const unsigned texelB = thisTexel & 0xFF;
const unsigned texelG = (thisTexel >> 8) & 0xFF;
const unsigned texelR = (thisTexel >> 16) & 0xFF;
const unsigned texelA = (const unsigned)currentAlpha;
thisTexel = D3DCOLOR_ARGB(texelA, texelR, texelG, texelB);
currentAlpha += iterAlpha;
}
mazeTex->UnlockRect(0);
}
static void CreateCube()
{
if (FAILED(d3d9dev->CreateVertexBuffer(4 * 6 * sizeof(vert3D), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0), D3DPOOL_DEFAULT, &cubeVB, NULL) ) )
{
printf("Error in CreateVertexBuffer()\n");
return;
}
if (FAILED(d3d9dev->CreateIndexBuffer(2 * 3 * 6 * sizeof(unsigned short), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &cubeIB, NULL) ) )
{
printf("Error in CreateIndexBuffer()\n");
return;
}
vert3D* lockedVB = NULL;
cubeVB->Lock(0, 0, (void**)&lockedVB, NULL);
// -x face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 0];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(-1.0f, thisVert.texcoord.x * 2.0f - 1.0f, thisVert.texcoord.y * 2.0f - 1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
// +x face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 4];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(1.0f, thisVert.texcoord.x * 2.0f - 1.0f, thisVert.texcoord.y * 2.0f - 1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
// -y face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 8];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(thisVert.texcoord.x * 2.0f - 1.0f, -1.0f, thisVert.texcoord.y * 2.0f - 1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
// +y face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 12];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(thisVert.texcoord.x * 2.0f - 1.0f, 1.0f, thisVert.texcoord.y * 2.0f - 1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
// -z face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 16];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(thisVert.texcoord.x * 2.0f - 1.0f, thisVert.texcoord.y * 2.0f - 1.0f, -1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
// +z face
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x + 20];
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.pos = D3DXVECTOR3(thisVert.texcoord.x * 2.0f - 1.0f, thisVert.texcoord.y * 2.0f - 1.0f, 1.0f);
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
cubeVB->Unlock();
unsigned short* lockedIB = NULL;
cubeIB->Lock(0, 0, (void**)&lockedIB, NULL);
memcpy(lockedIB, staticIndices, sizeof(staticIndices) );
cubeIB->Unlock();
}
int main(const unsigned argc, const char* const argv[])
{
WNDCLASSEXA classParams = {0};
classParams.cbSize = sizeof(WNDCLASSEX);
classParams.lpfnWndProc = &MyWindowProc;
classParams.style = CS_BYTEALIGNCLIENT | CS_BYTEALIGNWINDOW | CS_HREDRAW | CS_VREDRAW;
classParams.hInstance = (const HINSTANCE)GetModuleHandle(NULL);
classParams.lpszClassName = windowClassName;
const ATOM classAtom = RegisterClassExA(&classParams);
if (!classAtom)
{
printf("Error in RegisterClassExA. GLE: %u\n", GetLastError() );
return 1;
}
HWND wnd = CreateWindowExA(0L, (LPCSTR)classAtom, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, windowWidth, windowHeight, NULL, NULL, classParams.hInstance, NULL);
if (!wnd)
{
printf("Error in CreateWindowExA. GLE: %u\n", GetLastError() );
return 1;
}
ShowWindow(wnd, SW_SHOW);
UpdateWindow(wnd);
d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
if (!d3d9)
{
printf("Error in Direct3DCreate9(). GLE: %u\n", GetLastError() );
return 1;
}
D3DPRESENT_PARAMETERS d3dpp = {0};
d3dpp.BackBufferWidth = windowWidth;
d3dpp.BackBufferHeight = windowHeight;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = wnd;
d3dpp.Windowed = TRUE;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24X8;
d3dpp.Flags = D3DPRESENTFLAG_DEVICECLIP | D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
HRESULT createDeviceHR = d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, wnd, D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &d3dpp, &d3d9dev);
if (FAILED(createDeviceHR) || !d3d9dev)
{
printf("Error in CreateDevice(). HRESULT: 0x%08X. GLE: %u\n", createDeviceHR, GetLastError() );
return 1;
}
d3d9dev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(127, 127, 127), 1.0f, 0x00000000);
d3d9dev->Present(NULL, NULL, NULL, NULL);
if (FAILED(d3d9dev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &originalBackbuffer) ) || !originalBackbuffer)
{
printf("Error in GetBackBuffer()\n");
return 1;
}
if (FAILED(D3DXCreateTextureFromFileExA(d3d9dev, "FenceCrosshatchAlpha128x128.png", D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000, NULL, NULL, &fenceAlphaTex) ) )
{
printf("Error loading texture\n");
return 1;
}
if (FAILED(D3DXCreateTextureFromFileExA(d3d9dev, "VentGrate128x128.png", D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_ARGB(255, 255, 0, 255), NULL, NULL, &ventGrateColorKeyTex) ) )
{
printf("Error loading texture\n");
return 1;
}
if (FAILED(D3DXCreateTextureFromFileExA(d3d9dev, "MazeOpaque128x128.png", D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000, NULL, NULL, &mazeTex) ) )
{
printf("Error loading texture\n");
return 1;
}
AddAlphaToMazeTex(mazeTex);
if (FAILED(D3DXCreateTextureFromFileExA(d3d9dev, "TilingBricks64x64.png", D3DX_FROM_FILE, D3DX_FROM_FILE, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000, NULL, NULL, &bricksTex) ) )
{
printf("Error loading texture\n");
return 1;
}
AddDissolveAlphaToBricksTex(bricksTex);
if (FAILED(d3d9dev->CreateTexture(1, 1, 0, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &blackTex, NULL) ) )
{
printf("Error creating texture\n");
return 1;
}
if (FAILED(d3d9dev->CreateVertexBuffer(4 * sizeof(vert3D), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0), D3DPOOL_DEFAULT, &planeVB, NULL) ) )
{
printf("Error creating vertex buffer\n");
return 1;
}
vert3D* lockedVB = NULL;
planeVB->Lock(0, 0, (void**)&lockedVB, 0);
for (unsigned x = 0; x < 4; ++x)
{
vert3D& thisVert = lockedVB[x];
thisVert.texcoord.x = (const float)(x & 0x1);
thisVert.texcoord.y = (const float)( (x >> 1) & 0x1);
thisVert.vertColor = D3DCOLOR_ARGB(255, 255, 255, 255);
thisVert.pos.x = thisVert.texcoord.x - 0.5f;
thisVert.pos.y = thisVert.texcoord.y - 0.5f;
thisVert.pos.z = 0.0f;
thisVert.texcoord.x *= 2.0f;
thisVert.texcoord.y *= 2.0f;
}
planeVB->Unlock();
D3DLOCKED_RECT d3dlr = {0};
blackTex->LockRect(0, &d3dlr, NULL, 0);
{
D3DCOLOR* const texels = (D3DCOLOR* const)d3dlr.pBits;
*texels = D3DCOLOR_ARGB(255, 0, 0, 0);
}
blackTex->UnlockRect(0);
CreateCube();
if (FAILED(D3DXCreateTeapot(d3d9dev, &teapotMesh, NULL) ) )
{
printf("Failed to create sphere mesh\n");
return 1;
}
LARGE_INTEGER freq = {0};
QueryPerformanceFrequency(&freq);
const long double ldFreq = (const long double)freq.QuadPart;
LARGE_INTEGER lastTime = {0};
QueryPerformanceCounter(&lastTime);
MSG msg = {0};
while (!bDone)
{
if (PumpWindowsMessageLoop(wnd) < 1)
break;
LARGE_INTEGER currentTime = {0};
QueryPerformanceCounter(¤tTime);
const long double timeDeltaSeconds = (currentTime.QuadPart - lastTime.QuadPart) / ldFreq;
lastTime = currentTime;
RenderFrame(timeDeltaSeconds);
Sleep(16);
}
DestroyWindow(wnd);
UnregisterClassA( (LPCSTR)classAtom, classParams.hInstance);
return 0;
}
| [
"48116778+code-tom-code@users.noreply.github.com"
] | 48116778+code-tom-code@users.noreply.github.com |
a9716ae6a27a5f1ed8e0790065d44bbc85939b0a | e70cf2d50eda95b59c199c01e03901460c07a6ed | /bankAccountImplemnt.cpp | 91f91412aa6d98428649060c6f6791c53e6a8683 | [] | no_license | 3barney/Credit-Account-in-C-- | d6c7d1a3cddd06938801b386e3ced841425a418b | 9244e1e107bbebe48883a1e6183657f7c6290b64 | refs/heads/master | 2020-05-19T08:12:02.904822 | 2014-11-25T06:16:31 | 2014-11-25T06:16:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | #include "bankAccount.h"
#include <iostream>
using namespace std;
BankAccount::BankAccount( int balance )
{
if (balance >= 0)
accountBalance = balance;
if (balance < 0)
{
accountBalance = 0;
cout << "Initial balance was INvalid, Account balance set to zero (0)";
cout << endl;
}
}
int BankAccount::getAccountBalance()
{
//return accountBalance;
if (accountBalance >= 0)
{
return accountBalance;
}
else if (accountBalance <= 0)
{
return defaultValue;
}
}
void BankAccount::credit(int credit)
{
cout << "You have credited(borrowed) the amount : " << credit << endl;
accountBalance += credit;
}
void BankAccount::debit(int debit)
{
if(debit < accountBalance)
{
cout << "You debited(deposit) the amount : " << debit << endl;
accountBalance -= debit;
}
if (debit > accountBalance)
{
cout << "You cannot withdraw more than you have in your account balance" << endl;
}
}
| [
"brnbsjm@gmail.com"
] | brnbsjm@gmail.com |
2c518744c7df095545ee23cf9bfd8d8b69b3f4d2 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /media/learning/impl/learning_task_controller_helper.cc | 753dfb0940eedf6c8b93d9b602a7022bd288414b | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 4,295 | cc | // Copyright 2019 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 "media/learning/impl/learning_task_controller_helper.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/threading/sequenced_task_runner_handle.h"
namespace media {
namespace learning {
LearningTaskControllerHelper::LearningTaskControllerHelper(
const LearningTask& task,
AddExampleCB add_example_cb,
SequenceBoundFeatureProvider feature_provider)
: task_(task),
feature_provider_(std::move(feature_provider)),
task_runner_(base::SequencedTaskRunnerHandle::Get()),
add_example_cb_(std::move(add_example_cb)) {}
LearningTaskControllerHelper::~LearningTaskControllerHelper() = default;
void LearningTaskControllerHelper::BeginObservation(
base::UnguessableToken id,
FeatureVector features,
base::Optional<ukm::SourceId> source_id) {
auto& pending_example = pending_examples_[id];
if (source_id)
pending_example.source_id = *source_id;
// Start feature prediction, so that we capture the current values.
if (!feature_provider_.is_null()) {
feature_provider_.Post(
FROM_HERE, &FeatureProvider::AddFeatures, std::move(features),
base::BindOnce(&LearningTaskControllerHelper::OnFeaturesReadyTrampoline,
task_runner_, AsWeakPtr(), id));
} else {
pending_example.example.features = std::move(features);
pending_example.features_done = true;
}
}
void LearningTaskControllerHelper::CompleteObservation(
base::UnguessableToken id,
const ObservationCompletion& completion) {
auto iter = pending_examples_.find(id);
if (iter == pending_examples_.end())
return;
iter->second.example.target_value = completion.target_value;
iter->second.example.weight = completion.weight;
iter->second.target_done = true;
ProcessExampleIfFinished(std::move(iter));
}
void LearningTaskControllerHelper::CancelObservation(
base::UnguessableToken id) {
auto iter = pending_examples_.find(id);
if (iter == pending_examples_.end())
return;
// This would have to check for pending predictions, if we supported them, and
// defer destruction until the features arrive.
pending_examples_.erase(iter);
}
// static
void LearningTaskControllerHelper::OnFeaturesReadyTrampoline(
scoped_refptr<base::SequencedTaskRunner> task_runner,
base::WeakPtr<LearningTaskControllerHelper> weak_this,
base::UnguessableToken id,
FeatureVector features) {
// TODO(liberato): this would benefit from promises / deferred data.
auto cb = base::BindOnce(&LearningTaskControllerHelper::OnFeaturesReady,
std::move(weak_this), id, std::move(features));
if (!task_runner->RunsTasksInCurrentSequence()) {
task_runner->PostTask(FROM_HERE, std::move(cb));
} else {
std::move(cb).Run();
}
}
void LearningTaskControllerHelper::OnFeaturesReady(base::UnguessableToken id,
FeatureVector features) {
PendingExampleMap::iterator iter = pending_examples_.find(id);
// It's possible that OnLabelCallbackDestroyed has already run. That's okay
// since we don't support prediction right now.
if (iter == pending_examples_.end())
return;
iter->second.example.features = std::move(features);
iter->second.features_done = true;
ProcessExampleIfFinished(std::move(iter));
}
void LearningTaskControllerHelper::ProcessExampleIfFinished(
PendingExampleMap::iterator iter) {
if (!iter->second.features_done || !iter->second.target_done)
return;
add_example_cb_.Run(std::move(iter->second.example), iter->second.source_id);
pending_examples_.erase(iter);
// TODO(liberato): If we receive FeatureVector f1 then f2, and start filling
// in features for a prediction, and if features become available in the order
// f2, f1, and we receive a target value for f2 before f1's features are
// complete, should we insist on deferring training with f2 until we start
// prediction on f1? I suppose that we could just insist that features are
// provided in the same order they're received, and it's automatic.
}
} // namespace learning
} // namespace media
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
5e6cdb0b0f1a6255c0e09ad12c6919d30dc8ab07 | c67ea0d1c27f5cc709b52092e01adeb7e5779887 | /GameEngine/Generated Files/XamlTypeInfo.g.cpp | 29c9e73bee4914317702e233a183fdab881a8ba2 | [] | no_license | dufenmiao/SoftwareEngine | 921442c042c1d662227bf8306b4ecd14cc53891f | 098a08b0607fb684c6891f127f69fdee6199afba | refs/heads/master | 2020-05-29T11:39:44.698972 | 2015-05-20T16:14:56 | 2015-05-20T16:14:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | cpp | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#include "pch.h"
#include "XamlTypeInfo.g.h"
#include "App.xaml.h"
#include "MainPage.xaml.h"
#include "App.g.hpp"
#include "MainPage.g.hpp"
::Platform::Collections::Vector<::Windows::UI::Xaml::Markup::IXamlMetadataProvider^>^ ::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider::OtherProviders::get()
{
if(_otherProviders == nullptr)
{
_otherProviders = ref new ::Platform::Collections::Vector<::Windows::UI::Xaml::Markup::IXamlMetadataProvider^>();
}
return _otherProviders;
}
::Windows::UI::Xaml::Markup::IXamlType^ ::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider::CheckOtherMetadataProvidersForName(::Platform::String^ typeName)
{
::Windows::UI::Xaml::Markup::IXamlType^ foundXamlType = nullptr;
for (unsigned int i = 0; i < OtherProviders->Size; i++)
{
auto xamlType = OtherProviders->GetAt(i)->GetXamlType(typeName);
if(xamlType != nullptr)
{
if(xamlType->IsConstructible) // not Constructible means it might be a Return Type Stub
{
return xamlType;
}
foundXamlType = xamlType;
}
}
return foundXamlType;
}
::Windows::UI::Xaml::Markup::IXamlType^ ::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider::CheckOtherMetadataProvidersForType(::Windows::UI::Xaml::Interop::TypeName t)
{
::Windows::UI::Xaml::Markup::IXamlType^ foundXamlType = nullptr;
for (unsigned int i = 0; i < OtherProviders->Size; i++)
{
auto xamlType = OtherProviders->GetAt(i)->GetXamlType(t);
if(xamlType != nullptr)
{
if(xamlType->IsConstructible) // not Constructible means it might be a Return Type Stub
{
return xamlType;
}
foundXamlType = xamlType;
}
}
return foundXamlType;
}
::Windows::UI::Xaml::Markup::IXamlType^ ::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider::CreateXamlType(::Platform::String^ typeName)
{
if (typeName == L"Windows.UI.Xaml.Controls.Page")
{
return ref new XamlSystemBaseType(typeName);
}
if (typeName == L"Windows.UI.Xaml.Controls.UserControl")
{
return ref new XamlSystemBaseType(typeName);
}
if (typeName == L"GameEngine.MainPage")
{
::XamlTypeInfo::InfoProvider::XamlUserType^ userType = ref new ::XamlTypeInfo::InfoProvider::XamlUserType(this, typeName, GetXamlTypeByName(L"Windows.UI.Xaml.Controls.Page"));
userType->KindOfType = ::Windows::UI::Xaml::Interop::TypeKind::Custom;
userType->Activator =
[]() -> Platform::Object^
{
return ref new ::GameEngine::MainPage();
};
userType->SetIsLocalType();
return userType;
}
return nullptr;
}
::Windows::UI::Xaml::Markup::IXamlMember^ ::XamlTypeInfo::InfoProvider::XamlTypeInfoProvider::CreateXamlMember(::Platform::String^ longMemberName)
{
// No Local Properties
(void)longMemberName; // Unused parameter
return nullptr;
}
| [
"imbosong@gmail.com"
] | imbosong@gmail.com |
0bb5bf09d3123b4922ac0d57826fef2569484a53 | 5ed6a17f8a5b5d3fd915061c3b0b0bc833e8b80d | /乘积小于K的子数组.cpp | 5272a882a0b96a33927b0f752ee725a700d470cb | [] | no_license | young1928/Cpp | 9b084b498a56586804f2f5bda055df2e43ff5e6f | 4a80a11976392f3cb936353a784d916966432f99 | refs/heads/master | 2023-04-12T18:23:22.115514 | 2021-04-19T14:34:41 | 2021-04-19T14:34:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 894 | cpp | //给定一个正整数数组?nums。
//找出该数组内乘积小于?k?的连续的子数组的个数。
//示例 1:
//输入: nums = [10,5,2,6], k = 100
//输出: 8
//解释: 8个乘积小于100的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。
//需要注意的是 [10,5,2] 并不是乘积小于100的子数组。
//说明:
//0 < nums.length <= 50000
//0 < nums[i] < 1000
//0 <= k < 10^6
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int len = nums.size();
int ans = 0;
int left = 0;
int mul = 1;
for(int i = 0; i < len; i++)
{
mul *= nums[i];
while(mul >= k && left <= i)
mul /= nums[left++];
if(mul < k) ans += i-left+1;
//cout<<left<<' '<<i<<' '<<ans<<endl;
}
return ans;
}
};
| [
"2664484273@qq.com"
] | 2664484273@qq.com |
985553c20cef580dd72b339d9b06961310df6b34 | 4933920a4543d0b82ca2c109a396f6d56b8e118c | /Interview Bit/Linked Lists/list_cycle.cpp | 2723822193f5467a2936f353fe15f19eb256f155 | [] | no_license | dRadest/CodingChallenges | e0baf44222be70be3f39cedeabe1929e15a76205 | 65a8e58fc27abf3d4322d1a55da587a907cc79b9 | refs/heads/master | 2020-04-01T22:50:00.384441 | 2019-03-29T09:52:36 | 2019-03-29T09:52:36 | 153,728,863 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | cpp | /*
* https://www.interviewbit.com/problems/list-cycle/
*
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*
* Try solving it using constant additional space.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::detectCycle(ListNode* A) {
if(!A || !A->next)
return NULL;
ListNode* slow, *fast; //Floyd's cycle finding algorithm
slow = fast = A;
while (fast) //if you give condn slow!=fast; it's wrong since slow=fast=A initially.
{
if (!fast->next || !fast->next->next)
return NULL;
slow = slow->next;
fast = fast->next->next;
if(slow==fast)
break;
}
slow = A;
while(slow!=fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
| [
"progdrad@gmail.com"
] | progdrad@gmail.com |
56aa62a0533a1b0eced33ee3c280162ef86e5298 | da103d1c07f5d0ba3c41b245b5b0d7baeddc0418 | /codesamples/circlelights/circlelights.ino | 736a0e5f1997d6ca32cbeb1b4665ffe7256d4592 | [
"MIT"
] | permissive | tehfedaykin/CodingWithJewelbots | 0a9fd4796e907869fe985cf7f41422c15918ef3f | 47fa589da62f0e3c23b52d6291567d2ff0232104 | refs/heads/master | 2021-01-01T19:28:07.845594 | 2018-11-01T13:58:19 | 2018-11-01T13:58:19 | 98,597,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | ino | void setup() {
// put your setup code here, to run once:
}
LED light;
Timer timefor;
void loop() {
// put your main code here, to run repeatedly:
light.turn_on_single(SW, RED);
timefor.pause(150);
light.turn_off_single(SW);
light.turn_on_single(NW, RED);
timefor.pause(150);
light.turn_off_single(NW);
light.turn_on_single(NE, RED);
timefor.pause(150);
light.turn_off_single(NE);
light.turn_on_single(SE, RED);
timefor.pause(150);
light.turn_off_single(SE);
}
| [
"jennifer.wadella@gmail.com"
] | jennifer.wadella@gmail.com |
ddbf2500065ebe0ef16990fda42d58c01279a177 | d4017895ae2175fed7bc72a8403467150611edfb | /Space/Texture.h | b8d3575ed1f93a4d4f746a074181103716e9c4aa | [] | no_license | Whatop/Meteor | 6b4bead9958e12d334aeb2c676b921c6c2d52bd0 | d34752525bcbbcff8a7d11fe1d2ee42d3b096ab7 | refs/heads/main | 2023-03-02T15:19:08.539290 | 2021-02-17T06:55:20 | 2021-02-17T06:55:20 | 339,631,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | h | #pragma once
class Texture
{
LPDIRECT3DTEXTURE9 m_pTexture;
LPDIRECT3DDEVICE9 m_Dev;
Vec2 m_Size;
public:
Texture();
~Texture();
public:
bool Init(std::wstring fileName);
public:
LPDIRECT3DTEXTURE9 GetTexture() { return m_pTexture; }
Vec2 GetSize() { return m_Size; }
};
| [
"whdgkr1215@naver.com"
] | whdgkr1215@naver.com |
98eefe6d9b03175bf281f7771b834a3a493d2c1b | 902a7285713ba08930ccc42205bfce6deef933a9 | /Graph/Polygon.h | 6029cfc0cdda420ee4a9b1b44288d274f4335d85 | [
"MIT"
] | permissive | neville1/Graph2D | cf66cd84ec3122e6c9b651f75bd464604d89bf64 | 646177e824098ad06c34bd28ae92f2840103ec50 | refs/heads/master | 2020-12-02T21:12:33.188434 | 2017-07-05T03:20:53 | 2017-07-05T03:20:53 | 96,272,163 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,051 | h | #pragma once
typedef struct PtListHeader {
int Length; /* # of points */
POINT * PointPtr; /* pointer to list of points */
}PtListHeader;
#include "Line.h"
class __declspec(dllexport) CPolygon : public CLine
{
public:
CPolygon() {}
~CPolygon() {}
void DrawPolyLine(LPPOINT lpPoints, int nCount, COLORREF col);
void DrawSwitchColPolyLine(LPPOINT lpPoints, int nCount, int nStep, COLORREF col1, COLORREF col2);
void DrawPolygon(LPPOINT lpPoints, int nCount, COLORREF col);
void FillAnyPolygon(LPPOINT lpPoints,int nCount ,COLORREF col);
void FillConvexPolygon(LPPOINT lpPoints, int nCount, COLORREF col);
private:
void BuildGET(PtListHeader * VertexList,struct EdgeState * NextFreeEdgeStruc);
void MoveXSortedToAET(int YToMove);
void ScanOutAET(int YToScan, UINT16 col16);
void AdvanceAET();
void XSortAET();
void ScanEdge(int X1, int Y1, int X2, int Y2, int SetXStart,
int SkipFirst, struct HorLine **EdgePointPtr);
void DrawHorizontalLineList(struct HorLineList * HLineListPtr, UINT16 col16);
};
| [
"nevillegee@sysgration.com"
] | nevillegee@sysgration.com |
7f0bd1ff87a714b620b02c77ea2a53ffc8ead832 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/old_hunk_6031.cpp | 9fd2b914e15ee46c5caa56301ab981243bc44689 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp |
diskdinfo->smsgid = msgget((key_t) ikey, 0700 | IPC_CREAT);
if (diskdinfo->smsgid < 0) {
debug(50, 0) ("storeDiskdInit: msgget: %s\n", xstrerror());
fatal("msgget failed");
}
diskdinfo->rmsgid = msgget((key_t) (ikey + 1), 0700 | IPC_CREAT);
if (diskdinfo->rmsgid < 0) {
debug(50, 0) ("storeDiskdInit: msgget: %s\n", xstrerror());
fatal("msgget failed");
}
diskdinfo->shm.id = shmget((key_t) (ikey + 2),
SHMBUFS * SHMBUF_BLKSZ, 0600 | IPC_CREAT);
if (diskdinfo->shm.id < 0) {
debug(50, 0) ("storeDiskdInit: shmget: %s\n", xstrerror());
fatal("shmget failed");
}
diskdinfo->shm.buf = shmat(diskdinfo->shm.id, NULL, 0);
if (diskdinfo->shm.buf == (void *) -1) {
debug(50, 0) ("storeDiskdInit: shmat: %s\n", xstrerror());
fatal("shmat failed");
}
diskd_stats.shmbuf_count += SHMBUFS;
for (i = 0; i < SHMBUFS; i++)
storeDiskdShmPut(sd, i * SHMBUF_BLKSZ);
snprintf(skey1, 32, "%d", ikey);
snprintf(skey2, 32, "%d", ikey + 1);
snprintf(skey3, 32, "%d", ikey + 2);
| [
"993273596@qq.com"
] | 993273596@qq.com |
86fa62a866694f5f728888a6ba7a90c5304b070d | 7d1dc4ef43930b76635ad88b1dc33b8438b03b23 | /Monitoring/build-online_display-Desktop_Qt_5_4_2_GCC_64bit-Debug/moc_frame.cpp | 66eec6eea003fbb3a7dafeb1c2026122c84aa47a | [] | no_license | meleneemil/OLD-nsw-vmm-monitoring | 4ad66027539f2bf9d56ac7553a1c76813ac863c8 | d8e3992b1ed6adaee0dcfe27f5a04b30088ba66b | refs/heads/master | 2021-06-04T15:54:02.602024 | 2016-07-23T16:21:09 | 2016-07-23T16:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,582 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'frame.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../monitoring/frame.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'frame.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_frame_t {
QByteArrayData data[6];
char stringdata[54];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_frame_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_frame_t qt_meta_stringdata_frame = {
{
QT_MOC_LITERAL(0, 0, 5), // "frame"
QT_MOC_LITERAL(1, 6, 18), // "handle_root_events"
QT_MOC_LITERAL(2, 25, 0), // ""
QT_MOC_LITERAL(3, 26, 14), // "divideCanvases"
QT_MOC_LITERAL(4, 41, 6), // "height"
QT_MOC_LITERAL(5, 48, 5) // "width"
},
"frame\0handle_root_events\0\0divideCanvases\0"
"height\0width"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_frame[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x0a /* Public */,
3, 2, 25, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 4, 5,
0 // eod
};
void frame::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
frame *_t = static_cast<frame *>(_o);
switch (_id) {
case 0: _t->handle_root_events(); break;
case 1: _t->divideCanvases((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
default: ;
}
}
}
const QMetaObject frame::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_frame.data,
qt_meta_data_frame, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *frame::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *frame::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_frame.stringdata))
return static_cast<void*>(const_cast< frame*>(this));
return QWidget::qt_metacast(_clname);
}
int frame::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"root@pcatlnswdev01.dyndns.cern.ch"
] | root@pcatlnswdev01.dyndns.cern.ch |
b469c490f2b84ffa0b14f13f2c8ac4698d2b1fc6 | d9db6449de08b2341c70597290d3005abf00f47e | /leetcode/HashTable/UniqueOccurrence.cpp | 02459e11cdaea0983a80182e9f4bf75e14969c67 | [] | no_license | Harshsngh07/DataStructures_and_Algorithms | bd22af0b83017a7e00a6f85d12b12b2316fc8b15 | 451d54d9fa9f8708fd545a17d57cb85b5fdde2f9 | refs/heads/master | 2023-07-31T14:13:10.404941 | 2021-06-22T05:25:18 | 2021-06-22T05:25:18 | 252,812,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
unordered_map<int,int> m;
for(int i:arr)
m[i]++;
unordered_set<int> s;
for(auto i: m)
s.insert(i.second);
return m.size()==s.size();
}
};
static int fastio = []() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}(); | [
"harshsngh07@gmail.com"
] | harshsngh07@gmail.com |
18c04a0dca15a0e2680a0966ac8d46453051eacf | 122c628a8dc72460e9c568b1f77482017004f658 | /src/costs.cpp | a0a06e29a2d5bb5ba543eb6ed39222b7908b0906 | [
"MIT"
] | permissive | ferorga/CarND-Path-Planning-Project | 44dad39b7095291871a2796d32521778a6caac93 | 3c3fdef76758819ccccd8a12f92de4d94f2b6803 | refs/heads/master | 2020-04-26T01:22:42.371546 | 2019-04-04T19:06:19 | 2019-04-04T19:06:19 | 173,202,355 | 0 | 0 | null | 2019-02-28T23:21:19 | 2019-02-28T23:21:18 | null | UTF-8 | C++ | false | false | 6,307 | cpp | #include "costs.h"
double final_velocity_cost(Trajectory ego_tj)
{
double target_vel = mph2mps(48.5);
double v_lim = mph2mps(49.9);
double final_vel = ego_tj.lastSV();
double cost = 1.0;
//std::cout<<"final velocity cost "<<final_vel<<std::endl;
if (final_vel < target_vel)
{
cost = 1.0 - final_vel/target_vel;
//cost = -exp((final_vel-target_vel)/10.0) + 1.0;
}
else if(final_vel >target_vel && final_vel< v_lim)
{
double m = 1.0/(v_lim-target_vel);
double b = 1.0 - m*v_lim;
cost = (m*final_vel+b);
//cost = exp(7*(-v_lim+final_vel));
}
return cost;
}
double max_velocity_cost(Trajectory ego_tj)
{
double target_vel = mph2mps(47.0);
double v_lim = mph2mps(49.5);
double vel = 0.0;
double cost = 0.0;
for (int i = 0; i<ego_tj.size(); i++)
{
double cost_temp = 1.0;
vel = ego_tj.sv(i);
//std::cout<<"final velocity cost "<<final_vel<<std::endl;
if (vel < target_vel)
{
cost_temp = 0.0;
//cost = -exp((final_vel-target_vel)/10.0) + 1.0;
}
else
{
double m = 1.0/(v_lim-target_vel);
double b = 1.0 - m*v_lim;
cost_temp = (m*vel+b);
//cost = exp(7*(-v_lim+final_vel));
}
if (cost_temp > 1.0)
cost_temp = 1.0;
if (cost_temp > cost)
{
cost = cost_temp;
}
}
return cost;
}
double acceleration_peak_cost(Trajectory ego_tj)
{
double cost = 0;
//std::cout<<"acc"<<std::endl;
for (int i = 0; i<ego_tj.size();i++)
{
double acc = abs(ego_tj.sa(i));
// std::cout<<" "<<acc;
double cost_temp = 1.0 - exp(-(acc)/10.0);
if (cost_temp>1.0)
{
cost_temp = 1.0;
}
else if (cost_temp<0.0)
{
cost_temp = 0.0;
}
if (cost_temp > cost)
{
cost = cost_temp;
}
}
//std::cout<<std::endl;
return cost;
}
double acceleration_avg_cost(Trajectory ego_tj)
{
double cost = 0;
double avg = 0;
//std::cout<<"acc"<<std::endl;
for (int i = 0; i<ego_tj.size();i++)
{
double acc = abs(ego_tj.sa(i));
// std::cout<<" "<<acc;
avg += acc;
}
cost = avg/ego_tj.size()/20.0;
if (cost > 1.0)
{
cost = 1.0;
}
//std::cout<<std::endl;
return cost;
}
double driving_forward_cost(Trajectory ego_tj)
{
double cost = 0.0;
if (ego_tj.lastS()<ego_tj.s(0))
{
//std::cout<<"driving backwards!!"<<std::endl;
cost = 1.0;
}
return cost;
}
double car_ahead_cost(Trajectory ego_tj, vector<Vehicle> other_cars)
{
double cost = 0.0;
for (Vehicle other : other_cars)
{
Trajectory other_tj = other.getTrajectory();
int other_lane = getLane(other_tj.lastD(), 4, 2);
for (int i = 0; i<ego_tj.size(); i++)
{
if (getLane(ego_tj.d(i),4,2) == other_lane)
{
double dist = abs(other_tj.s(i) - ego_tj.s(i));
double cost_temp = exp(-0.3 * dist);
if (cost_temp > 1.0)
{
cost_temp = 1.0;
}
else if (cost_temp < 0.0)
{
cost_temp = 0.0;
}
if (cost_temp > cost)
{
cost = cost_temp;
}
}
}
}
return cost;
}
double change_lane_cost(Trajectory ego_tj)
{
double cost = 0.0;
if(getLane(ego_tj.lastD(),4,2) != getLane(ego_tj.d(0),4,2))
{
cost = 1.0;
}
return cost;
}
double prohibited_lane_cost(Trajectory ego_tj)
{
double cost = 0.0;
if(getLane(ego_tj.lastD(),4,1.8)<0 || getLane(ego_tj.lastD(),4,1.8)>2)
{
cost = 1.0;
}
return cost;
}
double distance_to_vehicle(Trajectory ego_tj, vector<Vehicle> other_cars)
{
double cost = 0.0;
double max_dist = 3.0;
for (Vehicle other : other_cars)
{
Trajectory other_tj = other.getTrajectory();
for (int i = 0; i<other_tj.size();i++)
{
double o_s = other_tj.s(i);
double o_d = other_tj.d(i);
double e_s = ego_tj.s(i);
double e_d = ego_tj.d(i);
double cost_temp = 0.0;
if(abs(o_d - e_d)<1 && abs(o_s - e_s)<2)
{
cost_temp = 1.0;
}
//double dist = sqrt((o_x-e_x)*(o_x-e_x) + (o_y-e_y)*(o_y-e_y));
//double cost_temp = 1.0 - exp((dist - max_dist)/1.0);
//if (cost_temp>1.0)
//{
// cost_temp = 1.0;
// }
// else if (cost_temp < 0.0)
// {
// cost_temp = 0.0;
// }
if (cost_temp>cost)
{
cost = cost_temp;
}
}
}
return cost;
}
double inside_lane_cost(Trajectory ego_tj)
{
double cost = 0.0;
for (int i = 0; i<ego_tj.size();i++)
{
double d = ego_tj.d(i);
double lane_d = getLaneCenterFrenet(getLane(d, 4, 2));
double error = abs(lane_d - d);
double cost_temp = error/4.0;
if (cost_temp > 1.0)
{
cost_temp = 1.0;
}
if (cost_temp > cost)
{
cost = cost_temp;
}
}
return cost;
}
double nocars_ahead_cost(Trajectory ego_tj, vector<Vehicle> other_cars)
{
double cost = 0.0;
double max_dist = 10.0;
for (Vehicle other : other_cars)
{
Trajectory other_tj = other.getTrajectory();
int other_lane = getLane(other_tj.lastD(), 4, 2);
int ego_lane = getLane(ego_tj.lastD(), 4, 2);
if (other_lane == ego_lane &&
other_tj.lastS() > ego_tj.lastS())
{
cost = 1.0;
}
}
return cost;
}
double change_safe_cost(Trajectory ego_tj, vector<Vehicle> other_cars)
{
double cost = 0.0;
int ego_lane_1 = getLane(ego_tj.d(0), 4, 2);
int ego_lane_2 = getLane(ego_tj.lastD(), 4, 2);
if (ego_lane_1 != ego_lane_2)
{
for (Vehicle other : other_cars)
{
Trajectory other_tj = other.getTrajectory();
int other_lane = getLane(other_tj.lastD(), 4, 2);
if (ego_lane_2 == other_lane)
{
double ego_s = ego_tj.lastS();
double other_s = other_tj.lastS();
double ego_d = ego_tj.lastD();
double other_d = other_tj.lastD();
double dist = sqrt((ego_s - other_s)*(ego_s - other_s)+(ego_d - other_d)*(ego_d - other_d));
double cost_temp = -dist/20 + 1;
if (cost_temp<0.0)
{
cost_temp = 0.0;
}
else if (cost_temp>1.0)
{
cost_temp = 1.0;
}
if (cost_temp>cost)
{
cost = cost_temp;
}
}
}
}
return cost;
}
| [
"ferorga1@gmail.com"
] | ferorga1@gmail.com |
87426fc2c535ba8015ebf2bb38e78aa4f4a6d8b8 | 18a789d8f140ac0c6f6edc8105f47ff7d79140f1 | /Source/URoboSim/Public/pr2_controllers_msgs/PR2GripperCommandActionGoal.h | e61b21c36308f6399a38a6288594799eef881f23 | [
"BSD-3-Clause"
] | permissive | robcog-iai/URoboSim | c95ce33dd176c01d6395f2ed6360477abd2e0768 | 5fbe6af8e2ae5518a85bb4e1425bc8bdcf3c0564 | refs/heads/master | 2022-07-11T04:19:11.433825 | 2022-04-01T07:24:22 | 2022-04-01T07:24:22 | 90,127,747 | 58 | 27 | BSD-3-Clause | 2018-04-14T08:54:48 | 2017-05-03T08:45:20 | C++ | UTF-8 | C++ | false | false | 2,480 | h | #pragma once
#include "ROSBridgeMsg.h"
#include "std_msgs/Header.h"
#include "actionlib_msgs/GoalID.h"
#include "pr2_controllers_msgs/PR2GripperCommandGoal.h"
namespace pr2_controllers_msgs
{
class PR2GripperCommandActionGoal : public FROSBridgeMsg
{
std_msgs::Header Header;
actionlib_msgs::GoalID GoalId;
pr2_controllers_msgs::PR2GripperCommandGoal Goal;
public:
PR2GripperCommandActionGoal()
{
MsgType = "pr2_controllers_msgs/PR2GripperCommandActionGoal";
}
PR2GripperCommandActionGoal
(
std_msgs::Header InHeader,
actionlib_msgs::GoalID InGoalId,
pr2_controllers_msgs::PR2GripperCommandGoal InGoal
):
Header(InHeader),
GoalId(InGoalId),
Goal(InGoal)
{
MsgType = "pr2_controllers_msgs/PR2GripperCommandActionGoal";
}
~PR2GripperCommandActionGoal() override {}
std_msgs::Header GetHeader() const
{
return Header;
}
actionlib_msgs::GoalID GetGoalId() const
{
return GoalId;
}
pr2_controllers_msgs::PR2GripperCommandGoal GetGoal() const
{
return Goal;
}
void SetHeader(std_msgs::Header InHeader)
{
Header = InHeader;
}
void SetGoalId(actionlib_msgs::GoalID InGoalId)
{
GoalId = InGoalId;
}
void SetGoal(pr2_controllers_msgs::PR2GripperCommandGoal InGoal)
{
Goal = InGoal;
}
virtual void FromJson(TSharedPtr<FJsonObject> JsonObject) override
{
Header = std_msgs::Header::GetFromJson(JsonObject->GetObjectField(TEXT("header")));
GoalId = actionlib_msgs::GoalID::GetFromJson(JsonObject->GetObjectField(TEXT("goal_id")));
Goal = pr2_controllers_msgs::PR2GripperCommandGoal::GetFromJson(JsonObject->GetObjectField(TEXT("goal")));
}
static PR2GripperCommandActionGoal GetFromJson(TSharedPtr<FJsonObject> JsonObject)
{
PR2GripperCommandActionGoal Result;
Result.FromJson(JsonObject);
return Result;
}
virtual TSharedPtr<FJsonObject> ToJsonObject() const override
{
TSharedPtr<FJsonObject> Object = MakeShareable<FJsonObject>(new FJsonObject());
Object->SetObjectField(TEXT("header"), Header.ToJsonObject());
Object->SetObjectField(TEXT("goal_id"), GoalId.ToJsonObject());
Object->SetObjectField(TEXT("goal"), Goal.ToJsonObject());
return Object;
}
virtual FString ToYamlString() const override
{
FString OutputString;
TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
FJsonSerializer::Serialize(ToJsonObject().ToSharedRef(), Writer);
return OutputString;
}
};
}
| [
"neumann.michael@uni-bremen.de"
] | neumann.michael@uni-bremen.de |
92f7746d4794975f73cf0e8b7dfdba2402b7dba9 | 0484f5f227abbf5dc3a7f6310f0d2cac26633e00 | /TJU/1930 - Doubles.cpp | 922474c4d776f44bb3ff0375bc954ed04037eaec | [] | no_license | LiboMa/Competitive-Programming | 826d32bcc116acdb5993e842a5a17786ce27c528 | 016e9ad599276dc1549ef4fa389658b2126098eb | refs/heads/master | 2020-12-11T03:43:30.861873 | 2015-10-25T17:12:08 | 2015-10-25T17:12:08 | 45,236,810 | 0 | 1 | null | 2015-10-30T07:55:16 | 2015-10-30T07:55:16 | null | UTF-8 | C++ | false | false | 1,007 | cpp | /*
1930 - Doubles
TJU Online Judge
Esteban Arango Medina
marranoparael31@gmail.com
*/
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main(){
int num;
cin>>num;
while(num!=-1){
int cont =0;
vector <int> doubles;
doubles.push_back(num);
cin>>num;
while(num){
doubles.push_back(num);
cin>>num;
}
int tamV=doubles.size();
for(int i=0;i<tamV;i++){
if(!(doubles[i]&1)){
int mid= doubles[i]/2;
int it;
it = (int) count (doubles.begin(), doubles.end(), mid);
if(it>0)cont++;
}
}
cout<<cont<<endl;
cin>>num;
}
return 0;
}
| [
"marranoparael31@gmail.com"
] | marranoparael31@gmail.com |
1388924debbbc7bbc0e339f5edc212b9e1e9d2e6 | 9b6ffd0f128375534b3e34c4ac0e5eebca93555a | /src/grovelinefinder/grovelinefinder.h | e5d2ff1f29528700a6fa59c792069e5923e3363d | [
"MIT"
] | permissive | zylix666/upm | 93211fe1f9e69b5204f2708a947935c94cac7a53 | e3ba0d7b0ac3ec7ae9cc43871b0c00276820d50f | refs/heads/master | 2021-01-18T01:56:26.508893 | 2015-03-31T00:04:58 | 2015-03-31T00:04:58 | 33,230,433 | 1 | 0 | null | 2015-04-01T06:24:21 | 2015-04-01T06:24:20 | null | UTF-8 | C++ | false | false | 2,159 | h | /*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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.
*/
#pragma once
#include <string>
#include <mraa/gpio.h>
namespace upm {
/**
* @brief C++ API for the Grove Line Finder sensor
*
* UPM module for the Grove Line Finder sensor. It outputs a
* digital signal indicating whether it is detecting black on a
* white background, or white on a black background.
*
* @ingroup gpio
* @snippet grovelinefinder.cxx Interesting
*/
class GroveLineFinder {
public:
/**
* Grove Line Finder digital sensor constructor
*
* @param pin digital pin to use
*/
GroveLineFinder(int pin);
/**
* GroveLineFinder Destructor
*/
~GroveLineFinder();
/**
* Determine whether white has been detected
*
* @return True if white is being detected
*/
bool whiteDetected();
/**
* Determine whether black has been detected
*
* @return True if black is being detected
*/
bool blackDetected();
private:
mraa_gpio_context m_gpio;
};
}
| [
"sarah.knepper@intel.com"
] | sarah.knepper@intel.com |
0dcffa0375db0008842920d2e5a239a22b97f6e0 | 461223861be1551ca5cb13be11a08d3c263103bf | /DELD/deld vhdl/3. hsub/hsub/isim/work/hsub12/testbench_arch.h | 4626349e78f69eb4a2a87d99c3202ad9c3cd9e55 | [] | no_license | RaghavShubham/VHDL_Codes | 457fb63526d4ac1a08f393a500a4f805a7409e3a | e9ec43ba3fb258f1b0a7174b85da2a760ebcff89 | refs/heads/master | 2020-09-02T11:43:48.088469 | 2019-11-02T20:59:55 | 2019-11-02T20:59:55 | 219,213,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 993 | h | ////////////////////////////////////////////////////////////////////////////////
// ____ ____
// / /\/ /
// /___/ \ /
// \ \ \/
// \ \ Copyright (c) 2003-2004 Xilinx, Inc.
// / / All Right Reserved.
// /---/ /\
// \ \ / \
// \___\/\___\
////////////////////////////////////////////////////////////////////////////////
#ifndef H_Work_hsub12_testbench_arch_H
#define H_Work_hsub12_testbench_arch_H
#ifdef __MINGW32__
#include "xsimMinGW.h"
#else
#include "xsim.h"
#endif
class Work_hsub12_testbench_arch: public HSim__s6 {
public:
HSimFileVar Results;
HSim__s4 Vy;
HSimAccessVar VB;
HSim__s1 SA[4];
Work_hsub12_testbench_arch(const char * name);
~Work_hsub12_testbench_arch();
void constructObject();
void constructPorts();
void reset();
void architectureInstantiate(HSimConfigDecl* cfg);
virtual void vhdlArchImplement();
};
HSim__s6 *createWork_hsub12_testbench_arch(const char *name);
#endif
| [
"shubham3raghav@gmail.com"
] | shubham3raghav@gmail.com |
aeec81ef72824c5da35ef16010f99d575f4dd291 | 55f16afe2eafa8998cc3935f4b99e31e60092b1c | /zstdpp.hpp | ee2692a962d2a3a54a683bbdee5213b59b56c1ef | [
"MIT"
] | permissive | andreiamatuni/zstdpp | 4ae246942b16a34447348fdd242489799dd0129c | 9454e426e2da519137441c8328d6588f663aab45 | refs/heads/master | 2021-01-21T10:52:22.076363 | 2017-03-01T00:19:10 | 2017-03-01T00:19:10 | 83,492,559 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,866 | hpp | #include <string.h>
#include "zstd.h"
namespace zstdpp {
inline std::string compress(const std::string data, int compress_level) {
size_t est_compress_size = ZSTD_compressBound(data.size());
std::string comp_buffer{};
comp_buffer.resize(est_compress_size);
auto compress_size =
ZSTD_compress((void*)comp_buffer.data(), est_compress_size, data.data(),
data.size(), compress_level);
comp_buffer.resize(compress_size);
comp_buffer.shrink_to_fit();
return comp_buffer;
}
inline std::string decompress(std::string data) {
auto const est_decomp_size =
ZSTD_getDecompressedSize(data.data(), data.size());
std::string decomp_buffer{};
decomp_buffer.resize(est_decomp_size);
size_t const decomp_size = ZSTD_decompress(
(void*)decomp_buffer.data(), est_decomp_size, data.data(), data.size());
decomp_buffer.resize(decomp_size);
decomp_buffer.shrink_to_fit();
return decomp_buffer;
}
inline std::string& buff_compress(const std::string data, std::string& buffer,
int compress_level) {
size_t est_compress_size = ZSTD_compressBound(data.size());
buffer.resize(est_compress_size);
auto compress_size = ZSTD_compress((void*)buffer.data(), est_compress_size,
data.data(), data.size(), compress_level);
buffer.resize(compress_size);
buffer.shrink_to_fit();
return buffer;
}
inline std::string& buff_decompress(const std::string& data,
std::string& buffer) {
auto const est_decomp_size =
ZSTD_getDecompressedSize(data.data(), data.size());
buffer.resize(est_decomp_size);
size_t const decomp_size = ZSTD_decompress(
(void*)buffer.data(), est_decomp_size, data.data(), data.size());
buffer.resize(decomp_size);
buffer.shrink_to_fit();
return buffer;
}
}
| [
"andrei.amatuni@gmail.com"
] | andrei.amatuni@gmail.com |
34d6e1ead6fbb2fe7157558654cd5fbd3653eb2f | 22f8a03664971ef42eb224f5b7fc9db472600eb2 | /test/include/dlaf_test/blas/invoke.h | f0554a8469a0f06d79e606c09f54b7f9bf2c03e9 | [
"BSD-3-Clause"
] | permissive | eth-cscs/DLA-Future | 3b560b3f45342bfd6db8bb5260df597cc9837155 | 7f96b895bb6942286390ef6275161c25855e02ed | refs/heads/master | 2023-08-30T13:27:04.784583 | 2023-08-30T13:25:37 | 2023-08-30T13:25:37 | 203,823,766 | 49 | 10 | BSD-3-Clause | 2023-09-13T12:29:40 | 2019-08-22T15:33:30 | C++ | UTF-8 | C++ | false | false | 2,118 | h | //
// Distributed Linear Algebra with Future (DLAF)
//
// Copyright (c) 2018-2023, ETH Zurich
// All rights reserved.
//
// Please, refer to the LICENSE file in the root directory.
// SPDX-License-Identifier: BSD-3-Clause
//
#pragma once
#ifdef DLAF_WITH_GPU
#include <whip.hpp>
#endif
#include <dlaf/types.h>
#ifdef DLAF_WITH_GPU
#include <dlaf/gpu/blas/api.h>
#include <dlaf/gpu/blas/error.h>
#endif
namespace dlaf::test {
namespace internal {
template <Device D>
struct Invoke;
template <>
struct Invoke<Device::CPU> {
template <class F, class... Args>
static void call(F&& f, Args&&... args) {
f(std::forward<Args>(args)...);
}
};
#ifdef DLAF_WITH_GPU
template <>
struct Invoke<Device::GPU> {
template <class F, class... Args>
static void call(F&& f, Args&&... args) {
f(std::forward<Args>(args)..., nullptr);
whip::device_synchronize();
}
};
#endif
template <Device D>
struct InvokeBlas;
template <>
struct InvokeBlas<Device::CPU> {
template <class F, class... Args>
static void call(F&& f, Args&&... args) {
f(std::forward<Args>(args)...);
}
};
#ifdef DLAF_WITH_GPU
template <>
struct InvokeBlas<Device::GPU> {
template <class F, class... Args>
static void call(F&& f, Args&&... args) {
cublasHandle_t handle;
DLAF_GPUBLAS_CHECK_ERROR(cublasCreate(&handle));
f(handle, std::forward<Args>(args)...);
whip::device_synchronize();
DLAF_GPUBLAS_CHECK_ERROR(cublasDestroy(handle));
}
};
#endif
}
/// Invokes a call in a generic way:
/// For CPU it calls f(args...),
/// For GPU it calls f(args..., stream) with the null stream and it synchronizes.
template <Device D, class F, class... Args>
void invoke(F&& f, Args&&... args) {
internal::Invoke<D>::call(std::forward<F>(f), std::forward<Args>(args)...);
}
/// Invokes a Blas call in a generic way:
/// For CPU it calls f(args...),
/// For GPU it creates a cublas handle, it calls f(handle, args...) and it synchronizes.
template <Device D, class F, class... Args>
void invokeBlas(F&& f, Args&&... args) {
internal::InvokeBlas<D>::call(std::forward<F>(f), std::forward<Args>(args)...);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
9c88b2049c12df11fc357a4217cb3f58fa5b3f2a | 0b715a5559280f99bf11d5e0ec08750505729c15 | /engine/source/sceneGraph/sceneRoot.h | 4aec07ee607e48add39004a91b33d22eae4bebe9 | [] | no_license | MBU-Team/OpenMBU | ee24dbd21eca66c9b269626d269e89b90fbcbcda | 4227ce343d3e1af20ec9a5548b1e65060fb208d4 | refs/heads/master | 2023-09-04T22:27:34.705946 | 2023-08-10T01:07:31 | 2023-08-10T01:07:31 | 338,863,302 | 71 | 16 | null | 2023-09-02T19:42:09 | 2021-02-14T17:41:11 | C++ | UTF-8 | C++ | false | false | 1,407 | h | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#ifndef _SCENEROOT_H_
#define _SCENEROOT_H_
//Includes
#ifndef _PLATFORM_H_
#include "platform/platform.h"
#endif
#ifndef _SCENEOBJECT_H_
#include "sim/sceneObject.h"
#endif
/// Root of scene graph.
class SceneRoot : public SceneObject
{
typedef SceneObject Parent;
protected:
bool onSceneAdd(SceneGraph* graph);
void onSceneRemove();
bool getOverlappingZones(SceneObject* obj, U32* zones, U32* numZones);
bool prepRenderImage(SceneState* state, const U32 stateKey, const U32 startZone,
const bool modifyBaseZoneState);
bool scopeObject(const Point3F& rootPosition,
const F32 rootDistance,
bool* zoneScopeState);
public:
SceneRoot();
~SceneRoot();
};
extern SceneRoot* gClientSceneRoot; ///< Client's scene graph root.
extern SceneRoot* gServerSceneRoot; ///< Server's scene graph root.
extern SceneRoot* gSPModeSceneRoot; ///< SPMode's scene graph root.
inline SceneRoot* getCurrentServerSceneRoot()
{
return gSPMode ? gSPModeSceneRoot : gServerSceneRoot;
}
inline SceneRoot* getCurrentClientSceneRoot()
{
return gSPMode ? gSPModeSceneRoot : gClientSceneRoot;
}
#endif //_SCENEROOT_H_
| [
"39096122+HumanGamer@users.noreply.github.com"
] | 39096122+HumanGamer@users.noreply.github.com |
f78ba3d74ca8cff3f6b2611086330df04abae429 | 01d7149cc49b20116190e19017d3a8d74de644a0 | /sqler/session.h | f89c7374a67a9c6b212847238abeac07d0c0a3e7 | [] | no_license | jianpanlanyue/libs | 8980fe751530bf1978541ee31a89cd8ffcca36d0 | 0f92408ba876aa1ca444092370905c6b4a93b86c | refs/heads/master | 2021-11-13T04:59:49.172814 | 2021-11-12T11:57:16 | 2021-11-12T11:57:16 | 41,011,083 | 4 | 4 | null | 2021-11-12T11:57:17 | 2015-08-19T03:25:29 | C++ | GB18030 | C++ | false | false | 11,356 | h | //这是一个c++数据库访问层,初衷在于提供简洁接口的同时,不失灵活性。目前只支持mysql,后续考虑增加其他数据库的支持。
//有些时候,我们需要执行增删改查之外的其他操作,而类中提供的接口很难覆盖数据库的全部原生接口,则可以通过get_backend_impl()获取底层数据库的描述符,以调用数据库原生接口完成需求。
//在设计的时候,并没有使用查询类,结果集类等常见的模式,而是直接模拟数据库的查询,提供一个query()核心方法,数据库中使用什么样的sql语句,query()的参数就是什么样的——所见即所见。
//传递sql语句的时候,支持本地参数(sql中需要参数的地方以"?"代替),后面接本地参数。 支持变参与可变参数类型,见demo。
//支持数据库连接池、支持存储过程。
//如果出现编译时出现socket相关函数的重复定义错误,可能是之前已经包含了低版本的socket头文件。将本头文件放到低版本socket头文件前面,或者直接放在所有语句最前面,即可解决。
#pragma once
#if defined(_MSC_VER) && _MSC_VER < 1800
#error "Compiler need to support c++11, please use vs2013 or above, vs2015 e.g."
#endif
#include "../based/headers_all.h"
#include "session_pool.h"
namespace sqler
{
typedef based::except sql_error;
#define THROW_SQL_EXCEPTION THROW_SQL_EXCEPTION0
#define THROW_SQL_EXCEPTION0() throw(sqler::sql_error((int)get_error_no(),get_error_msg(),__FILE__,__LINE__))
#define THROW_SQL_EXCEPTION2(ERROR_NO,ERROR_STR) throw(sqler::sql_error(ERROR_NO,ERROR_STR,__FILE__,__LINE__))
class session
{
protected:
struct mysql_lib_init
{
mysql_lib_init()
{
if (init_state())
return;
ENSURE(mysql_library_init(0,NULL,NULL) == 0).warn(-1, "mysql lib init fail");
init_state() = true;
}
~mysql_lib_init()
{
mysql_library_end();
}
bool& init_state()
{
static bool init_ok = false;
return init_ok;
}
};
mysql_lib_init& lib_init_dummy()
{
static mysql_lib_init dummy;
return dummy;
}
public:
session()
{
//mysql_init()函数在第一次初始化的时候,不是线程安全的,但是之后是线程安全的。c++11标准规定,局部静态对象初始化是线程安全的,此处确保mysql_init安全调用一次。
//mysql_init安全调用一次后,后续的mysql_init调用都是线程安全的。
//不对mysql_init直接传NULL,而用lib_init_dummy().init_state()的原因,1、此时!init_state一定是false 2、防止release下对lib_init_dummy的调用被优化掉
my_sql_ = mysql_init((MYSQL*)(!lib_init_dummy().init_state()));
ENSURE(my_sql_ != NULL).warn(-1, "Mysql init fail, maybe memory insufficient.");
type_conv_.set_quote_when_characters_to_str('\'');
}
session(MYSQL* my_sql)
:my_sql_(my_sql),
not_destroy_(lib_init_dummy().init_state())
{
//不对not_destroy_直接初始化为true,而用lib_init_dummy().init_state()的原因,1、此时init_state一定是true 2、防止release下对lib_init_dummy的调用被优化掉
my_sql_ = mysql_init(my_sql_);
ENSURE(my_sql_ != NULL).warn(-1, "Mysql init fail, maybe memory insufficient.");
type_conv_.set_quote_when_characters_to_str('\'');
}
//从连接池中构造,连接池中无可用连接,则等待timeout_second秒
session(session_pool* sp, unsigned timeout_second = (unsigned)-1)
{
index_in_pool_ = lib_init_dummy().init_state(); //给index_in_pool_赋值没有实际作用,只是防止release下对lib_init_dummy的调用被优化掉
my_sql_ = (sp_=sp)->get(&index_in_pool_, timeout_second);
ENSURE(my_sql_ != NULL).warn(-1, "Mysql init fail, maybe memory insufficient.");
type_conv_.set_quote_when_characters_to_str('\'');
}
//从连接池中构造,则还给连接池;否则关闭连接
~session()
{
free_all_result();
if (sp_ && index_in_pool_ != -1)
sp_->release(index_in_pool_);
else if (!not_destroy_)
close();
}
//取最近一次sql query的错误描述
const char* get_error_msg()
{
return mysql_error(my_sql_);
}
//取最近一次sql query的错误码
unsigned get_error_no()
{
return mysql_errno(my_sql_);
}
//取列的数目
unsigned get_field_count()
{
return mysql_field_count(my_sql_);
}
//取得数据库后台
MYSQL* get_backend_impl()
{
return my_sql_;
}
//取得结果集
MYSQL_RES* get_result_set()
{
return res_;
}
//连接数据库
void open(const char* host, unsigned port, const char* user, const char* passwd, const char* database,
unsigned long client_flag = CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS)
{
ENSURE(mysql_real_connect(my_sql_, host, user, passwd, database, port, NULL, client_flag) != NULL).warn(get_error_no(), get_error_msg());
}
void set_option(const int option_type, const char* option_value_ptr)
{
mysql_options(my_sql_, (mysql_option)option_type, option_value_ptr);
}
//传递sql语句。
//sql_str,要执行的sql语句,需要参数的时候,使用'?'做占位符。可以传递多条sql语句,以';'分隔。
//args...,真实的参数,个数与sql_str中的'?'一样,否则会抛出异常。 函数内部会将'?'字符替换为args...的真实值,并执行查询。
//demo:
//int my_id = 1;
//s.query("select * from table_a where id=? and name=?",my_id,"my_name");
template<typename... Args>
unsigned long long query(const char* sql_str, const Args&... args)
{
ENSURE(sql_str != NULL && strlen(sql_str) != 0)(sql_str)(strlen(sql_str)).warn(-1, "sql statement passed can not be empty.");
free_all_result();
std::string formated_sql = sql_str;
int place_holders_count = 0;
int args_count = sizeof...(args);
for (auto& ele : formated_sql)
if (ele == '?')
++place_holders_count;
ENSURE(place_holders_count == args_count)(place_holders_count)(args_count).warn(-1,"arguments passed should be compatiable with placeholders' count in sql.");
formated_sql.reserve(256);
int last_read_pos = formated_sql.length()-1;
parameter_pack_dummy_wrapper(format_sql_str(formated_sql, last_read_pos, args)...);
ENSURE(mysql_real_query(my_sql_, formated_sql.c_str(), formated_sql.size()) == 0)(formated_sql).warn(get_error_no(), get_error_msg());
return next_result();
}
template<typename... Args>
unsigned long long query(const std::string& sql_str, const Args&... args)
{
return query(sql_str.c_str(), args...);
}
//存储结果集,并返回当前结果集的行数。
//返回值:结果集行数。不产生结果集,或结果集内没有数据为0;结果集内有数据的为数据的行数;取结果集过程出错的抛出异常。
unsigned long long next_result()
{
free_former_result();
if (!has_next_result_)
return 0;
res_ = mysql_store_result(my_sql_);
if (mysql_next_result(my_sql_) != 0) //预判下一个结果集是否存在
has_next_result_ = false;
if (res_ == NULL)
{
unsigned error_no = get_error_no();
ENSURE(error_no == 0).warn(error_no, get_error_msg()); //之前的sql语句产生结果集,但store result 发生错误
return 0; //之前的sql语句不产生结果集
}
return mysql_num_rows(res_); //返回结果行数,0表示语句产生结果集,但结果集里没有结果
}
void free_former_result()
{
if (res_ != NULL)
{
mysql_free_result(res_);
res_ = NULL;
}
}
void free_all_result()
{
free_former_result();
while (has_next_result_ || mysql_next_result(my_sql_) == 0)
{
has_next_result_ = false;
res_ = mysql_store_result(my_sql_);
free_former_result();
}
has_next_result_ = true; //复位has_next_result_,假设后续的query会有结果集
}
//使用此函数接收"先参与表达式后解包"出来的参数,绕开编译错误
template <typename ... Args>
void parameter_pack_dummy_wrapper(const Args&... t) {};
//取结果集的一行到args中
//返回值:true成功取出,false没有结果可取。传入的本地参数数目,必须小于等于sql语句中查询出的列数目,否则抛出异常。
template<typename... Args>
bool fetch_row(Args&... args)
{
ENSURE(res_ != NULL).warn(-1, "be sure to successfully store result first");
MYSQL_ROW row = mysql_fetch_row(res_);
if (row == NULL) //res_里的结果集已取完
return false;
int field_count = mysql_num_fields(res_);
int args_count = sizeof...(args);
ENSURE(args_count <= field_count)(args_count)(field_count).warn(-1, "arguments you passed should be less or equal than fields count selected in sql.");
unsigned long* field_length = mysql_fetch_lengths(res_);
ENSURE(field_length != NULL).warn(get_error_no(), get_error_msg());
parameter_pack_dummy_wrapper(_fetch_row(row, --args_count, field_length, args)...);
return true;
}
protected:
void close()
{
if (my_sql_ != NULL)
{
free_all_result();
mysql_close(my_sql_);
}
}
//fetch_row的具体实现函数。
template<typename Arg>
int _fetch_row(MYSQL_ROW& row, int field_index, unsigned long* field_len_array, Arg& dest)
{
ENSURE(field_index>=0)(field_index)(field_len_array).warn(-1,"field_index is negative...");
long field_len = field_len_array[field_index];
const char* src;
field_len == 0 ? src = NULL : src = row[field_index];
type_conv_.to_type(dest, src, field_len);
return 0;
}
//格式化sql str。为无需参数的sql str所准备。
template<typename int=0>
int format_sql_str(std::string& sql_str, int last_read_pos) { return 0; }
//格式化sql str,将'?'替换为arg的值。 '?'的数目必须与传入的本地参数数目一致,否则抛出异常。
template<typename Arg>
int format_sql_str(std::string& sql_str, int& last_read_pos, const Arg& arg)
{
size_t pos = sql_str.rfind("?", last_read_pos);
ENSURE(pos != sql_str.npos)(sql_str)(last_read_pos).warn(-1, "can not reverse find '?' from last_read_pos in sql statement.");
const char* sql_param = type_conv_.to_str(arg);
sql_str.replace(pos, 1, sql_param);
last_read_pos = pos-1;
return 0;
}
protected:
based::str_type_convert type_conv_;
session_pool* sp_;
int index_in_pool_ = -1;
bool not_destroy_ = false;
MYSQL* my_sql_ = NULL;
MYSQL_RES* res_ = NULL;
bool has_next_result_ = true;
};
}
//演示:
//#include "session.h"
//int main()
//{
// sqler::session s;
// try {
// s.open("host_ip", 3306, "user", "password", "db_name");
//
// int id = 10;
// std::string cfg_type = "cfg_back";
// double charge_rate;
// std::string short_msg;
// //查询所有id<10且类型为"cfg_back"的记录,保存到本地变量charge_rate,short_msg中。
// //表中,id为整数型,type为字符串型,charge_rate为浮点型,short_msg为字符串型
// s.query("select charge_rate,short_msg from system_config where id < ? and type = ?", id, cfg_type);
// while (s.fetch_row(charge_rate, short_msg))
// {
// //do something..
// std::cout << charge_rate << short_msg;
// }
// }
// catch (sqler::sql_error& er)
// {
// std::cout << er.what();
// }
//}
| [
"jianpanlanyue@163.com"
] | jianpanlanyue@163.com |
23ca02cbeef3522f46e425f715091dc2d546dcfd | b80cc60b780b7e4ca65432d02a0af5a1e7a3153e | /Pacifica.h | 3efc8e903993559c1770fc32be1ca3779b1fc4fe | [
"MIT"
] | permissive | JoaDick/EyeCandy | 567729afdbeaecf6af584bc78859523070a5deec | 9639f9da437a8ddf0ce2cbd8ea7c2d3ae4b48c87 | refs/heads/master | 2022-11-24T09:43:04.960587 | 2020-08-02T20:10:19 | 2020-08-02T20:10:19 | 276,486,297 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,565 | h | #pragma once
/*******************************************************************************
MIT License
Copyright (c) 2019 Mark Kriegsman and Mary Corey March
Copyright (c) 2020 Joachim Dick - Ported to EyeCandy Animation
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 "AnimationBaseFL.h"
//------------------------------------------------------------------------------
namespace EC
{
/** "Pacifica"
* Gentle, blue-green ocean waves.
* December 2019, Mark Kriegsman and Mary Corey March.
* For Dan.
* https://github.com/FastLED/FastLED/blob/master/examples/Pacifica/Pacifica.ino
*/
class Pacifica
: public AnimationBaseFL
{
public:
/** Constructor
* @param ledStrip The LED strip.
* @param ledCount Number of LEDs.
*/
Pacifica(CRGB *ledStrip,
uint16_t ledCount)
: AnimationBaseFL(false, ledStrip, ledCount)
{
patternDelay = 20;
}
private:
/// @see AnimationBase::showPattern()
void showPattern(uint32_t currentMillis) override
{
pacifica_loop(currentMillis);
}
//////////////////////////////////////////////////////////////////////////
//
// The code for this animation is more complicated than other examples, and
// while it is "ready to run", and documented in general, it is probably not
// the best starting point for learning. Nevertheless, it does illustrate some
// useful techniques.
//
//////////////////////////////////////////////////////////////////////////
//
// In this animation, there are four "layers" of waves of light.
//
// Each layer moves independently, and each is scaled separately.
//
// All four wave layers are added together on top of each other, and then
// another filter is applied that adds "whitecaps" of brightness where the
// waves line up with each other more. Finally, another pass is taken
// over the led array to 'deepen' (dim) the blues and greens.
//
// The speed and scale and motion each layer varies slowly within independent
// hand-chosen ranges, which is why the code has a lot of low-speed 'beatsin8' functions
// with a lot of oddly specific numeric ranges.
//
// These three custom blue-green color palettes were inspired by the colors found in
// the waters off the southern coast of California, https://goo.gl/maps/QQgd97jjHesHZVxQ7
//
const CRGBPalette16 pacifica_palette_1 =
{0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x14554B, 0x28AA50};
const CRGBPalette16 pacifica_palette_2 =
{0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x0C5F52, 0x19BE5F};
const CRGBPalette16 pacifica_palette_3 =
{0x000208, 0x00030E, 0x000514, 0x00061A, 0x000820, 0x000927, 0x000B2D, 0x000C33,
0x000E39, 0x001040, 0x001450, 0x001860, 0x001C70, 0x002080, 0x1040BF, 0x2060FF};
void pacifica_loop(uint32_t currentMillis)
{
// Increment the four "color index start" counters, one for each wave layer.
// Each is incremented at a different speed, and the speeds vary over time.
static uint16_t sCIStart1, sCIStart2, sCIStart3, sCIStart4;
static uint32_t sLastms = 0;
uint32_t ms = currentMillis;
uint32_t deltams = ms - sLastms;
sLastms = ms;
uint16_t speedfactor1 = beatsin16(3, 179, 269);
uint16_t speedfactor2 = beatsin16(4, 179, 269);
uint32_t deltams1 = (deltams * speedfactor1) / 256;
uint32_t deltams2 = (deltams * speedfactor2) / 256;
uint32_t deltams21 = (deltams1 + deltams2) / 2;
sCIStart1 += (deltams1 * beatsin88(1011, 10, 13));
sCIStart2 -= (deltams21 * beatsin88(777, 8, 11));
sCIStart3 -= (deltams1 * beatsin88(501, 5, 7));
sCIStart4 -= (deltams2 * beatsin88(257, 4, 6));
// Clear out the LED array to a dim background blue-green
fill_solid(ledStrip, ledCount, CRGB(2, 6, 10));
// Render each of four layers, with different scales and speeds, that vary over time
pacifica_one_layer(pacifica_palette_1, sCIStart1, beatsin16(3, 11 * 256, 14 * 256), beatsin8(10, 70, 130), 0 - beat16(301));
pacifica_one_layer(pacifica_palette_2, sCIStart2, beatsin16(4, 6 * 256, 9 * 256), beatsin8(17, 40, 80), beat16(401));
pacifica_one_layer(pacifica_palette_3, sCIStart3, 6 * 256, beatsin8(9, 10, 38), 0 - beat16(503));
pacifica_one_layer(pacifica_palette_3, sCIStart4, 5 * 256, beatsin8(8, 10, 28), beat16(601));
// Add brighter 'whitecaps' where the waves lines up more
pacifica_add_whitecaps();
// Deepen the blues and greens a bit
pacifica_deepen_colors();
}
// Add one layer of waves into the led array
void pacifica_one_layer(const CRGBPalette16 &p, uint16_t cistart, uint16_t wavescale, uint8_t bri, uint16_t ioff)
{
uint16_t ci = cistart;
uint16_t waveangle = ioff;
uint16_t wavescale_half = (wavescale / 2) + 20;
for (uint16_t i = 0; i < ledCount; i++)
{
waveangle += 250;
uint16_t s16 = sin16(waveangle) + 32768;
uint16_t cs = scale16(s16, wavescale_half) + wavescale_half;
ci += cs;
uint16_t sindex16 = sin16(ci) + 32768;
uint8_t sindex8 = scale16(sindex16, 240);
CRGB c = ColorFromPalette(p, sindex8, bri, LINEARBLEND);
pixel(i) += c;
}
}
// Add extra 'white' to areas where the four layers of light have lined up brightly
void pacifica_add_whitecaps()
{
uint8_t basethreshold = beatsin8(9, 55, 65);
uint8_t wave = beat8(7);
for (uint16_t i = 0; i < ledCount; i++)
{
uint8_t threshold = scale8(sin8(wave), 20) + basethreshold;
wave += 7;
uint8_t l = pixel(i).getAverageLight();
if (l > threshold)
{
uint8_t overage = l - threshold;
uint8_t overage2 = qadd8(overage, overage);
pixel(i) += CRGB(overage, overage2, qadd8(overage2, overage2));
}
}
}
// Deepen the blues and greens
void pacifica_deepen_colors()
{
for (uint16_t i = 0; i < ledCount; i++)
{
pixel(i).blue = scale8(pixel(i).blue, 145);
pixel(i).green = scale8(pixel(i).green, 200);
pixel(i) |= CRGB(2, 5, 7);
}
}
};
} // namespace EC
| [
"62520542+JoaDick@users.noreply.github.com"
] | 62520542+JoaDick@users.noreply.github.com |
e5c5591ababa26ab585b3a27436a124f3d222f2f | f028fe2e47a783fee500cac10ff101eed509627f | /grab_display/imageclipper_read.hpp | a60b370cfb9c2f904e4344b1a0e628b730f2866f | [] | no_license | ltinphan/2017VisionCode | cc25251fc8dc7fbfc3e4d7991038cc2912845317 | 350be74f46a0cb5b860627155b0eb7fd82d09145 | refs/heads/master | 2021-07-04T00:59:28.577461 | 2017-09-25T19:57:27 | 2017-09-25T19:57:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | hpp | #pragma once
#include <string>
#include <opencv2/opencv.hpp>
// Using the data encoded in filename, read the frame
// the image was originally clipped from. Generate a bounding
// rect starting with the original image location, then
// adjust it to the correct aspect ratio.
// Return true if successful, false if an error happens
bool getFrameAndRect(const std::string &filename, const std::string &srcPath,
const double AR,
std::string &origName, int &frame, cv::Mat &mat, cv::Rect &rect);
| [
"admin@altechcode.com"
] | admin@altechcode.com |
4d4a78c7ccca4467a2d584cc41204d69a5658e0c | 77586f17d8c6f0f7b48f798e6f70026421e7587d | /include/tcpsocket.h | 57dfe21b263544b7503f9c1680cfb69d65317b73 | [
"MIT"
] | permissive | yangwei10723/sandbox | e8461db8d16f2bfcd384654a71e670d2dc27d861 | 184bc7d1198076489c2178f0c80d76791b77dad9 | refs/heads/master | 2020-12-02T22:12:27.001269 | 2017-06-21T01:11:27 | 2017-06-21T01:11:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,091 | h | //
// some tcp/ip socket code useful for reference
//
#pragma once
#ifndef TCP_SOCKET_CONVENIENCE_WRAPPER
#define TCP_SOCKET_CONVENIENCE_WRAPPER
#include <vector>
#include <exception>
#include "misc.h"
#define NOMINMAX
#include <winsock.h>
#pragma comment(lib,"ws2_32.lib")
#define MSG_WAITALL 0x8 // omg, MS forgot to define MSG_WAITALL in winsock.h (http://www.windows-tech.info/14/89f04a075d8e9df7.php):
inline bool reporterror(const char *file, int line, std::string e)
{
std::string s = std::string(file) + ":" + std::to_string(line) + " " + e;
std::cerr << "FAIL: " << s << "\n";
throw(std::exception(s.c_str()));
return 0;
}
#define RESOURCE_ERROR(m) reporterror(__FILE__,__LINE__,m)
inline void perror(char *) { printf("%d is the error", WSAGetLastError()); }
# define DEFAULT_PORT 80
inline SOCKET ConnectTCP(const char *machine = "localhost", int port = DEFAULT_PORT)
{
// On WINDOWS be sure to call WSAStartup winsock before calling this routine
struct hostent *phe;
SOCKADDR_IN addr; /* DESTination Socket INternet */
SOCKET sock = INVALID_SOCKET;
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
RESOURCE_ERROR("socket creation");
// todo: add somthing here that when destructed will close this socket if we throw before we return
addr.sin_family = AF_INET;
if (isdigit(machine[0]))
{
unsigned int address = inet_addr(machine);
phe = gethostbyaddr((char *)&address, 4, AF_INET);
if (phe) {
memcpy((char *)&(addr.sin_addr), phe->h_addr, phe->h_length);
}
else {
// just hack it in
memcpy((char *)&(addr.sin_addr), (char *)&address, 4);
}
}
else
{
(phe = gethostbyname(machine)) || RESOURCE_ERROR(std::string("unable to get hostbyname ") + machine + "error: " + std::to_string(WSAGetLastError())); // note need to closesocket(sock);
memcpy((char FAR *)&(addr.sin_addr), phe->h_addr, phe->h_length);
}
addr.sin_port = htons(port); /* Convert to network ordering */
if (connect(sock, (PSOCKADDR)&addr, sizeof(addr)) < 0) RESOURCE_ERROR("connect() failed"); // note need to closesocket(sock);
return sock;
}
inline int PollRead(SOCKET s,long usec_timeout=0)
{
if (s == INVALID_SOCKET) return 0;
fd_set re, wr, ex;
struct timeval tm;
tm.tv_sec = 0;
tm.tv_usec = usec_timeout;
FD_ZERO(&re);
FD_ZERO(&wr);
FD_ZERO(&ex);
FD_SET(s, &re);
int rc = select(s + 1, &re, &wr, &ex, &tm);
if (rc == SOCKET_ERROR) return 0;
//printf("select: rc=%d readfdset=%d\n",rc,FD_ISSET(s,&re));
return (rc && FD_ISSET(s, &re));
}
inline void read(void *dst, int n, SOCKET s) { int r; (r = recv(s, (char*)dst, n, MSG_WAITALL)) == n || RESOURCE_ERROR(std::string("recv error ") + std::to_string(WSAGetLastError()) + " wanted:" + std::to_string(n) + " rv:" + std::to_string(r)); }
template<class T>
T read(SOCKET s) { T t; read(&t, sizeof(t), s); return t; }
template<class T>
std::vector<T> readarray(SOCKET s)
{
auto n = read<int32_t>(s); // should be 32 bit
std::vector<T> a(n);
read(a.data(), n * sizeof(T), s);
return a;
}
inline std::vector<char> testserver(const char* a="GET foo")
{
std::vector<char> testimage(32 * 32*3, 0);
auto s = ConnectTCP("localhost", 21212); // on some systems, low numbered ports are reserved.
send(s, a, strlen(a), 0);
read(testimage.data(), 32*32*3, s);
return testimage;
}
// WSADATA wsdata;
// if (int status = WSAStartup(MAKEWORD(1, 1), &wsdata)) RESOURCE_ERROR(std::to_string(status) + " error from wsastartup");
//
inline SOCKET start_server(int port = 80)
{
// On WINDOWS be sure to call WSAStartup winsock before calling this routine
int status;
WSADATA whatever;
if ((status = WSAStartup(MAKEWORD(1, 1), &whatever)) != 0)
{
throw(std::exception("FAIL: WSAStartup socket startup"));
return INVALID_SOCKET;
}
SOCKADDR_IN listen_addr; /* Local socket - internet style */
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = INADDR_ANY;
listen_addr.sin_port = htons(port); /* Convert to network ordering */
auto listen_sock = socket(AF_INET, SOCK_STREAM, 0);
if (listen_sock == INVALID_SOCKET)
{
throw(std::exception((std::string("FAIL: socket create: ")+std::to_string(WSAGetLastError())).c_str()));
return INVALID_SOCKET;
}
if (bind(listen_sock, (struct sockaddr FAR *) &listen_addr, sizeof(listen_addr)) == -1) {
perror("ERROR: bind: ");
throw(std::exception((std::string("FAIL: socket bind: ") + std::to_string(WSAGetLastError())).c_str()));
return INVALID_SOCKET;
}
if (listen(listen_sock, 4) < 0)
{
perror("listen: ");
// printf("%d is the error", WSAGetLastError());
WSACleanup();
throw(std::exception((std::string("FAIL: socket listen: ") + std::to_string(WSAGetLastError())).c_str()));
return INVALID_SOCKET;
}
return listen_sock;
}
inline void http_reply_text(SOCKET s, std::string reply, const char *type = "plain")
{
std::string http_header = ToString() << "HTTP/1.0 200 OK\nAccess-Control-Allow-Origin: *\nContent-Length: " << reply.length() << "\nContent Type: text/" << type << "\n\n";
int rc = send(s, http_header.c_str(), http_header.length(), 0);
rc = send(s, reply.c_str(), reply.length(), 0);
}
inline std::pair<SOCKET,std::string> serverside_get_request(SOCKET listen_sock)
{
if (listen_sock == INVALID_SOCKET)
{
return{ INVALID_SOCKET,"" };
}
if (!PollRead(listen_sock))
return{ INVALID_SOCKET,"" };
std::cout << "listen_sock polled for read\n";
// SOCKET s = Accept();
SOCKADDR_IN accept_addr; // Accept socket address - internet style
int accept_addr_len; // Accept socket address length
accept_addr_len = sizeof(accept_addr);
SOCKET s = accept(listen_sock, (struct sockaddr FAR *) &accept_addr,
(int FAR *) &accept_addr_len);
if (s == INVALID_SOCKET)
{
std::cout << "error "<< s << "on accept listen_sock\n";
perror("accept: \n");
// printf("%d is the error", WSAGetLastError());
//WSACleanup(); // should we throw?
return{ INVALID_SOCKET,"" };// INVALID_SOCKET;
}
if (!PollRead(s,1000))
{
int i=10;
while (!PollRead(s,100000) && --i)
std::cout << '.';
std::cout << " \ngot an accepted socket but nothing to read when poll select "<< i << " attempts remain\n";
if (i == 0)
{
http_reply_text(s, "wtf - no request??");
closesocket(s);
return{ INVALID_SOCKET,"" };
}
}
char buf[2048];
int rc = 0;
buf[rc] = '\0';
int bc = 0;
while (PollRead(s,1000) && (bc = recv(s, buf + rc, 1024 - rc, 0)) >0) {
rc = rc + bc;
}
buf[rc] = '\0';
if (bc < 0)
int k = 3;
return{ s,std::string(buf) };
}
inline void do_server_thing(SOCKET listen_sock,std::string reply)
{
auto request = serverside_get_request(listen_sock);
if (request.first == INVALID_SOCKET)
return;
std::string http_header = ToString() << "HTTP/1.0 200 OK\nAccess-Control-Allow-Origin: *\nContent-Length: "<< reply.length() << "\nContent Type: text/plain\n\n";
int rc = send(request.first, http_header.c_str(), http_header.length(), 0);
rc = send(request.first, reply.c_str(), reply.length(), 0);
closesocket(request.first);
}
#endif TCP_SOCKET_CONVENIENCE_WRAPPER
| [
"stan@melax.com"
] | stan@melax.com |
44dd1793b7d2ec05a874788dce1100649dfaef62 | be9adc136d1ca10b834633cb03905c4b6c211999 | /Lab3/waves/waves/src/Window.cpp | d4a33c3e9b1d58f0e9e542197e16c517c89ac2f0 | [] | no_license | Coguar/ComputerGraphics | 1d8f67995b1f214440fce0aa4116380d6aae2a07 | 65e4d350bddfcd87ab4d350820be692c80a899bc | refs/heads/master | 2020-04-15T02:27:51.342897 | 2016-11-28T16:13:42 | 2016-11-28T16:13:42 | 68,028,885 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,183 | cpp | #include "Window.h"
#include "AbstractWindowClient.h"
#include "Utils.h"
#include "libchapter3_private.h"
#include <SDL2/SDL.h>
namespace
{
glm::vec2 GetMousePosition(const SDL_MouseButtonEvent &event)
{
return { event.x, event.y };
}
glm::vec2 GetMousePosition(const SDL_MouseMotionEvent &event)
{
return { event.x, event.y };
}
void DispatchEvent(const SDL_Event &event, IWindowClient &acceptor)
{
switch (event.type)
{
case SDL_KEYDOWN:
acceptor.OnKeyDown(event.key);
break;
case SDL_KEYUP:
acceptor.OnKeyUp(event.key);
break;
case SDL_MOUSEBUTTONDOWN:
acceptor.OnDragBegin(GetMousePosition(event.button));
break;
case SDL_MOUSEBUTTONUP:
acceptor.OnDragEnd(GetMousePosition(event.button));
break;
case SDL_MOUSEMOTION:
acceptor.OnDragMotion(GetMousePosition(event.motion));
break;
}
}
void SetupProfileAttributes(ContextProfile profile, ContextMode mode)
{
// Включаем режим сглаживания с помощью субпиксельного рендеринга.
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
// Выбираем версию и параметры совместимости контекста
bool makeRobust = true;
switch (profile)
{
case ContextProfile::Compatibility:
makeRobust = false;
break;
case ContextProfile::RobustOpenGL_3_1:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
break;
case ContextProfile::RobustOpenGL_3_2:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
break;
case ContextProfile::RobustOpenGL_4_0:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
break;
}
unsigned flags = 0;
if (mode == ContextMode::Debug)
{
// Включаем поддержку отладочных средств
// в создаваемом контексте OpenGL.
flags |= SDL_GL_CONTEXT_DEBUG_FLAG;
}
if (makeRobust)
{
// Отключаем поддержку старых средств из старых версий OpenGL
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
flags |= SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG;
}
else
{
// Включаем поддержку расширений для обратной совместимости
// со старыми версиями OpenGL.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
}
}
void GLAPIENTRY DebugOutputCallback(
GLenum /*source*/,
GLenum type,
GLuint id,
GLenum /*severity*/,
GLsizei /*length*/,
const GLchar* message,
const void* /*userParam*/)
{
// Отсекаем все сообщения, кроме ошибок
if (type != GL_DEBUG_TYPE_ERROR)
{
return;
}
std::string formatted = "OpenGL error #" + std::to_string(id) + ": " + message;
std::cerr << formatted << std::endl;
}
void SetupDebugOutputCallback()
{
if (!GLEW_ARB_debug_output)
{
throw std::runtime_error("Cannot use debug output:"
" it isn't supported by videodriver");
}
glEnable(GL_DEBUG_OUTPUT);
// Синхронный режим позволяет узнать в отладчике контекст,
// в котором произошла ошибка.
// Режим может понизить производительность, но на фоне
// других потерь Debug-сборки это несущественно.
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(DebugOutputCallback, nullptr);
// Указываем видеодрайверу выдать только один тип сообщений,
// GL_DEBUG_TYPE_ERROR.
glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
}
}
class CWindow::Impl
{
public:
Impl(ContextProfile profile, ContextMode mode)
: m_profile(profile)
, m_contextMode(mode)
{
}
void Show(const std::string &title, const glm::ivec2 &size)
{
m_size = size;
CUtils::InitOnceSDL2();
// Выбираем версию и параметры совместимости OpenGL.
SetupProfileAttributes(m_profile, m_contextMode);
// Специальное значение SDL_WINDOWPOS_CENTERED вместо x и y заставит SDL2
// разместить окно в центре монитора по осям x и y.
// Для использования OpenGL вы ДОЛЖНЫ указать флаг SDL_WINDOW_OPENGL.
m_pWindow.reset(SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
size.x, size.y, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE));
if (!m_pWindow)
{
const std::string reason = SDL_GetError();
throw std::runtime_error("Cannot create window: " + reason);
}
// Создаём контекст OpenGL, связанный с окном.
m_pGLContext.reset(SDL_GL_CreateContext(m_pWindow.get()));
if (!m_pGLContext)
{
CUtils::ValidateSDL2Errors();
}
CUtils::InitOnceGLEW();
// Устанавливаем функцию обработки отладочных сообщений.
if (m_contextMode == ContextMode::Debug)
{
SetupDebugOutputCallback();
}
}
glm::ivec2 GetWindowSize() const
{
return m_size;
}
void SetClient(IWindowClient *pClient)
{
m_pClient = pClient;
}
void DoMainLoop()
{
const std::chrono::milliseconds FRAME_PERIOD(16);
SDL_Event event;
CChronometer chronometer;
while (true)
{
while (SDL_PollEvent(&event) != 0)
{
if (!ConsumeEvent(event) && m_pClient)
{
DispatchEvent(event, *m_pClient);
}
}
if (m_isTerminated)
{
break;
}
// Очистка буфера кадра, обновление и рисование сцены, вывод буфера кадра.
Clear();
if (m_pClient)
{
const float deltaSeconds = chronometer.GrabDeltaTime();
m_pClient->OnUpdateWindow(deltaSeconds);
}
CUtils::ValidateOpenGLErrors();
SwapBuffers();
chronometer.WaitNextFrameTime(FRAME_PERIOD);
}
}
void SetBackgroundColor(const glm::vec4 &color)
{
m_clearColor = color;
}
void Clear()const
{
// Заливка кадра цветом фона средствами OpenGL
glClearColor(m_clearColor.x, m_clearColor.y, m_clearColor.z, m_clearColor.w);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void SwapBuffers()const
{
// Вывод нарисованного кадра в окно на экране.
// При этом система отдаёт старый буфер для рисования нового кадра.
// Обмен двух буферов вместо создания новых позволяет не тратить ресурсы впустую.
SDL_GL_SwapWindow(m_pWindow.get());
}
bool ConsumeEvent(const SDL_Event &event)
{
bool consumed = false;
if (event.type == SDL_QUIT)
{
m_isTerminated = true;
consumed = true;
}
else if (event.type == SDL_WINDOWEVENT)
{
OnWindowEvent(event.window);
consumed = true;
}
return consumed;
}
private:
void OnWindowEvent(const SDL_WindowEvent &event)
{
if (event.event == SDL_WINDOWEVENT_RESIZED)
{
m_size = {event.data1, event.data2};
}
}
bool m_isTerminated = false;
ContextProfile m_profile;
ContextMode m_contextMode;
IWindowClient *m_pClient = nullptr;
SDLWindowPtr m_pWindow;
SDLGLContextPtr m_pGLContext;
glm::ivec2 m_size;
glm::vec4 m_clearColor;
};
CWindow::CWindow(ContextProfile profile, ContextMode mode)
: m_pImpl(new Impl(profile, mode))
{
}
CWindow::~CWindow()
{
}
void CWindow::Show(const std::string &title, const glm::ivec2 &size)
{
m_pImpl->Show(title, size);
}
void CWindow::SetBackgroundColor(const glm::vec4 &color)
{
m_pImpl->SetBackgroundColor(color);
}
void CWindow::SetClient(IWindowClient *pClient)
{
m_pImpl->SetClient(pClient);
}
glm::ivec2 CWindow::GetWindowSize() const
{
return m_pImpl->GetWindowSize();
}
void CWindow::DoMainLoop()
{
m_pImpl->DoMainLoop();
}
| [
"Cogucc@mail.ru"
] | Cogucc@mail.ru |
d4895aa0290df4d602a41ea56f59545863369407 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/skia/tests/ReadPixelsTest.cpp | 008781ca0600abeb197906b5eb4a4be91668406d | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 17,240 | cpp | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkMathPriv.h"
#include "SkSurface.h"
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "SkGr.h"
#endif
#include <initializer_list>
static const int DEV_W = 100, DEV_H = 100;
static const SkIRect DEV_RECT = SkIRect::MakeWH(DEV_W, DEV_H);
static const SkRect DEV_RECT_S = SkRect::MakeWH(DEV_W * SK_Scalar1,
DEV_H * SK_Scalar1);
static SkPMColor get_src_color(int x, int y) {
SkASSERT(x >= 0 && x < DEV_W);
SkASSERT(y >= 0 && y < DEV_H);
U8CPU r = x;
U8CPU g = y;
U8CPU b = 0xc;
U8CPU a = 0xff;
switch ((x+y) % 5) {
case 0:
a = 0xff;
break;
case 1:
a = 0x80;
break;
case 2:
a = 0xCC;
break;
case 4:
a = 0x01;
break;
case 3:
a = 0x00;
break;
}
return SkPremultiplyARGBInline(a, r, g, b);
}
static SkPMColor get_dst_bmp_init_color(int x, int y, int w) {
int n = y * w + x;
U8CPU b = n & 0xff;
U8CPU g = (n >> 8) & 0xff;
U8CPU r = (n >> 16) & 0xff;
return SkPackARGB32(0xff, r, g , b);
}
static SkPMColor convert_to_pmcolor(SkColorType ct, SkAlphaType at, const uint32_t* addr,
bool* doUnpremul) {
*doUnpremul = (kUnpremul_SkAlphaType == at);
const uint8_t* c = reinterpret_cast<const uint8_t*>(addr);
U8CPU a,r,g,b;
switch (ct) {
case kBGRA_8888_SkColorType:
b = static_cast<U8CPU>(c[0]);
g = static_cast<U8CPU>(c[1]);
r = static_cast<U8CPU>(c[2]);
a = static_cast<U8CPU>(c[3]);
break;
case kRGBA_8888_SkColorType:
r = static_cast<U8CPU>(c[0]);
g = static_cast<U8CPU>(c[1]);
b = static_cast<U8CPU>(c[2]);
a = static_cast<U8CPU>(c[3]);
break;
default:
SkDEBUGFAIL("Unexpected colortype");
return 0;
}
if (*doUnpremul) {
r = SkMulDiv255Ceiling(r, a);
g = SkMulDiv255Ceiling(g, a);
b = SkMulDiv255Ceiling(b, a);
}
return SkPackARGB32(a, r, g, b);
}
static SkBitmap make_src_bitmap() {
static SkBitmap bmp;
if (bmp.isNull()) {
bmp.allocN32Pixels(DEV_W, DEV_H);
intptr_t pixels = reinterpret_cast<intptr_t>(bmp.getPixels());
for (int y = 0; y < DEV_H; ++y) {
for (int x = 0; x < DEV_W; ++x) {
SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bmp.rowBytes() + x * bmp.bytesPerPixel());
*pixel = get_src_color(x, y);
}
}
}
return bmp;
}
static void fill_src_canvas(SkCanvas* canvas) {
canvas->save();
canvas->setMatrix(SkMatrix::I());
canvas->clipRect(DEV_RECT_S, SkCanvas::kReplace_Op);
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrc);
canvas->drawBitmap(make_src_bitmap(), 0, 0, &paint);
canvas->restore();
}
#if SK_SUPPORT_GPU
static void fill_src_texture(GrTexture* texture) {
SkBitmap bmp = make_src_bitmap();
bmp.lockPixels();
texture->writePixels(0, 0, DEV_W, DEV_H, kSkia8888_GrPixelConfig, bmp.getPixels(),
bmp.rowBytes());
bmp.unlockPixels();
}
#endif
static void fill_dst_bmp_with_init_data(SkBitmap* bitmap) {
SkAutoLockPixels alp(*bitmap);
int w = bitmap->width();
int h = bitmap->height();
intptr_t pixels = reinterpret_cast<intptr_t>(bitmap->getPixels());
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bitmap->rowBytes() + x * bitmap->bytesPerPixel());
*pixel = get_dst_bmp_init_color(x, y, w);
}
}
}
static bool check_read_pixel(SkPMColor a, SkPMColor b, bool didPremulConversion) {
if (!didPremulConversion) {
return a == b;
}
int32_t aA = static_cast<int32_t>(SkGetPackedA32(a));
int32_t aR = static_cast<int32_t>(SkGetPackedR32(a));
int32_t aG = static_cast<int32_t>(SkGetPackedG32(a));
int32_t aB = SkGetPackedB32(a);
int32_t bA = static_cast<int32_t>(SkGetPackedA32(b));
int32_t bR = static_cast<int32_t>(SkGetPackedR32(b));
int32_t bG = static_cast<int32_t>(SkGetPackedG32(b));
int32_t bB = static_cast<int32_t>(SkGetPackedB32(b));
return aA == bA &&
SkAbs32(aR - bR) <= 1 &&
SkAbs32(aG - bG) <= 1 &&
SkAbs32(aB - bB) <= 1;
}
// checks the bitmap contains correct pixels after the readPixels
// if the bitmap was prefilled with pixels it checks that these weren't
// overwritten in the area outside the readPixels.
static bool check_read(skiatest::Reporter* reporter,
const SkBitmap& bitmap,
int x, int y,
bool checkCanvasPixels,
bool checkBitmapPixels) {
SkASSERT(4 == bitmap.bytesPerPixel());
SkASSERT(!bitmap.isNull());
SkASSERT(checkCanvasPixels || checkBitmapPixels);
const SkColorType ct = bitmap.colorType();
const SkAlphaType at = bitmap.alphaType();
int bw = bitmap.width();
int bh = bitmap.height();
SkIRect srcRect = SkIRect::MakeXYWH(x, y, bw, bh);
SkIRect clippedSrcRect = DEV_RECT;
if (!clippedSrcRect.intersect(srcRect)) {
clippedSrcRect.setEmpty();
}
SkAutoLockPixels alp(bitmap);
for (int by = 0; by < bh; ++by) {
for (int bx = 0; bx < bw; ++bx) {
int devx = bx + srcRect.fLeft;
int devy = by + srcRect.fTop;
const uint32_t* pixel = bitmap.getAddr32(bx, by);
if (clippedSrcRect.contains(devx, devy)) {
if (checkCanvasPixels) {
SkPMColor canvasPixel = get_src_color(devx, devy);
bool didPremul;
SkPMColor pmPixel = convert_to_pmcolor(ct, at, pixel, &didPremul);
if (!check_read_pixel(pmPixel, canvasPixel, didPremul)) {
ERRORF(reporter, "Expected readback pixel (%d, %d) value 0x%08x, got 0x%08x. "
"Readback was unpremul: %d", bx, by, canvasPixel, pmPixel, didPremul);
return false;
}
}
} else if (checkBitmapPixels) {
uint32_t origDstPixel = get_dst_bmp_init_color(bx, by, bw);
if (origDstPixel != *pixel) {
ERRORF(reporter, "Expected clipped out area of readback to be unchanged. "
"Expected 0x%08x, got 0x%08x", origDstPixel, *pixel);
return false;
}
}
}
}
return true;
}
enum BitmapInit {
kFirstBitmapInit = 0,
kNoPixels_BitmapInit = kFirstBitmapInit,
kTight_BitmapInit,
kRowBytes_BitmapInit,
kRowBytesOdd_BitmapInit,
kLastAligned_BitmapInit = kRowBytes_BitmapInit,
#if 0 // THIS CAUSES ERRORS ON WINDOWS AND SOME ANDROID DEVICES
kLast_BitmapInit = kRowBytesOdd_BitmapInit
#else
kLast_BitmapInit = kLastAligned_BitmapInit
#endif
};
static BitmapInit nextBMI(BitmapInit bmi) {
int x = bmi;
return static_cast<BitmapInit>(++x);
}
static void init_bitmap(SkBitmap* bitmap, const SkIRect& rect, BitmapInit init, SkColorType ct,
SkAlphaType at) {
SkImageInfo info = SkImageInfo::Make(rect.width(), rect.height(), ct, at);
size_t rowBytes = 0;
bool alloc = true;
switch (init) {
case kNoPixels_BitmapInit:
alloc = false;
case kTight_BitmapInit:
break;
case kRowBytes_BitmapInit:
rowBytes = (info.width() + 16) * sizeof(SkPMColor);
break;
case kRowBytesOdd_BitmapInit:
rowBytes = (info.width() * sizeof(SkPMColor)) + 3;
break;
default:
SkASSERT(0);
break;
}
if (alloc) {
bitmap->allocPixels(info, rowBytes);
} else {
bitmap->setInfo(info, rowBytes);
}
}
static const struct {
SkColorType fColorType;
SkAlphaType fAlphaType;
} gReadPixelsConfigs[] = {
{ kRGBA_8888_SkColorType, kPremul_SkAlphaType },
{ kRGBA_8888_SkColorType, kUnpremul_SkAlphaType },
{ kBGRA_8888_SkColorType, kPremul_SkAlphaType },
{ kBGRA_8888_SkColorType, kUnpremul_SkAlphaType },
};
const SkIRect gReadPixelsTestRects[] = {
// entire thing
DEV_RECT,
// larger on all sides
SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H + 10),
// fully contained
SkIRect::MakeLTRB(DEV_W / 4, DEV_H / 4, 3 * DEV_W / 4, 3 * DEV_H / 4),
// outside top left
SkIRect::MakeLTRB(-10, -10, -1, -1),
// touching top left corner
SkIRect::MakeLTRB(-10, -10, 0, 0),
// overlapping top left corner
SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H / 4),
// overlapping top left and top right corners
SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H / 4),
// touching entire top edge
SkIRect::MakeLTRB(-10, -10, DEV_W + 10, 0),
// overlapping top right corner
SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H / 4),
// contained in x, overlapping top edge
SkIRect::MakeLTRB(DEV_W / 4, -10, 3 * DEV_W / 4, DEV_H / 4),
// outside top right corner
SkIRect::MakeLTRB(DEV_W + 1, -10, DEV_W + 10, -1),
// touching top right corner
SkIRect::MakeLTRB(DEV_W, -10, DEV_W + 10, 0),
// overlapping top left and bottom left corners
SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H + 10),
// touching entire left edge
SkIRect::MakeLTRB(-10, -10, 0, DEV_H + 10),
// overlapping bottom left corner
SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W / 4, DEV_H + 10),
// contained in y, overlapping left edge
SkIRect::MakeLTRB(-10, DEV_H / 4, DEV_W / 4, 3 * DEV_H / 4),
// outside bottom left corner
SkIRect::MakeLTRB(-10, DEV_H + 1, -1, DEV_H + 10),
// touching bottom left corner
SkIRect::MakeLTRB(-10, DEV_H, 0, DEV_H + 10),
// overlapping bottom left and bottom right corners
SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
// touching entire left edge
SkIRect::MakeLTRB(0, DEV_H, DEV_W, DEV_H + 10),
// overlapping bottom right corner
SkIRect::MakeLTRB(3 * DEV_W / 4, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
// overlapping top right and bottom right corners
SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H + 10),
};
static void test_readpixels(skiatest::Reporter* reporter, const sk_sp<SkSurface>& surface,
BitmapInit lastBitmapInit) {
SkCanvas* canvas = surface->getCanvas();
fill_src_canvas(canvas);
for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
const SkIRect& srcRect = gReadPixelsTestRects[rect];
for (BitmapInit bmi = kFirstBitmapInit; bmi <= lastBitmapInit; bmi = nextBMI(bmi)) {
for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
SkBitmap bmp;
init_bitmap(&bmp, srcRect, bmi,
gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
// if the bitmap has pixels allocated before the readPixels,
// note that and fill them with pattern
bool startsWithPixels = !bmp.isNull();
if (startsWithPixels) {
fill_dst_bmp_with_init_data(&bmp);
}
uint32_t idBefore = surface->generationID();
bool success = canvas->readPixels(&bmp, srcRect.fLeft, srcRect.fTop);
uint32_t idAfter = surface->generationID();
// we expect to succeed when the read isn't fully clipped
// out.
bool expectSuccess = SkIRect::Intersects(srcRect, DEV_RECT);
// determine whether we expected the read to succeed.
REPORTER_ASSERT(reporter, success == expectSuccess);
// read pixels should never change the gen id
REPORTER_ASSERT(reporter, idBefore == idAfter);
if (success || startsWithPixels) {
check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop,
success, startsWithPixels);
} else {
// if we had no pixels beforehand and the readPixels
// failed then our bitmap should still not have pixels
REPORTER_ASSERT(reporter, bmp.isNull());
}
}
// check the old webkit version of readPixels that clips the
// bitmap size
SkBitmap wkbmp;
bool success = canvas->readPixels(srcRect, &wkbmp);
SkIRect clippedRect = DEV_RECT;
if (clippedRect.intersect(srcRect)) {
REPORTER_ASSERT(reporter, success);
REPORTER_ASSERT(reporter, kN32_SkColorType == wkbmp.colorType());
REPORTER_ASSERT(reporter, kPremul_SkAlphaType == wkbmp.alphaType());
check_read(reporter, wkbmp, clippedRect.fLeft,
clippedRect.fTop, true, false);
} else {
REPORTER_ASSERT(reporter, !success);
}
}
}
}
DEF_TEST(ReadPixels, reporter) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
auto surface(SkSurface::MakeRaster(info));
// SW readback fails a premul check when reading back to an unaligned rowbytes.
test_readpixels(reporter, surface, kLastAligned_BitmapInit);
}
#if SK_SUPPORT_GPU
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Gpu, reporter, ctxInfo) {
const SkImageInfo ii = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
for (auto& origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctxInfo.grContext(), SkBudgeted::kNo,
ii, 0, origin, nullptr));
test_readpixels(reporter, surface, kLast_BitmapInit);
}
}
#endif
#if SK_SUPPORT_GPU
static void test_readpixels_texture(skiatest::Reporter* reporter, GrTexture* texture) {
fill_src_texture(texture);
for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
const SkIRect& srcRect = gReadPixelsTestRects[rect];
for (BitmapInit bmi = kFirstBitmapInit; bmi <= kLast_BitmapInit; bmi = nextBMI(bmi)) {
for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
SkBitmap bmp;
init_bitmap(&bmp, srcRect, bmi,
gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
// if the bitmap has pixels allocated before the readPixels,
// note that and fill them with pattern
bool startsWithPixels = !bmp.isNull();
// Try doing the read directly from a non-renderable texture
if (startsWithPixels) {
fill_dst_bmp_with_init_data(&bmp);
GrPixelConfig dstConfig =
SkImageInfo2GrPixelConfig(gReadPixelsConfigs[c].fColorType,
gReadPixelsConfigs[c].fAlphaType,
nullptr,
*texture->getContext()->caps());
uint32_t flags = 0;
if (gReadPixelsConfigs[c].fAlphaType == kUnpremul_SkAlphaType) {
flags = GrContext::kUnpremul_PixelOpsFlag;
}
bmp.lockPixels();
bool success = texture->readPixels(srcRect.fLeft, srcRect.fTop, bmp.width(),
bmp.height(), dstConfig, bmp.getPixels(),
bmp.rowBytes(), flags);
bmp.unlockPixels();
check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop,
success, true);
}
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Texture, reporter, ctxInfo) {
// On the GPU we will also try reading back from a non-renderable texture.
for (auto& origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
SkAutoTUnref<GrTexture> texture;
GrSurfaceDesc desc;
desc.fFlags = kRenderTarget_GrSurfaceFlag;
desc.fWidth = DEV_W;
desc.fHeight = DEV_H;
desc.fConfig = kSkia8888_GrPixelConfig;
desc.fOrigin = origin;
desc.fFlags = kNone_GrSurfaceFlags;
texture.reset(ctxInfo.grContext()->textureProvider()->createTexture(desc,
SkBudgeted::kNo));
test_readpixels_texture(reporter, texture);
}
}
#endif
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
d4bf4092dc6b927bd944da1e57931d6c74821fae | e31b324949391f561a79d4e16bf2944fcd09c1a8 | /src/cascadia/UnitTests_TerminalCore/TerminalBufferTests.cpp | e46360818032230799848bf5f45387a1bb9f1b2d | [
"LGPL-2.1-or-later",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-object-form-exception-to-mit",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | Duui3111/terminal | 44b26d2bdc2886294b2535da2f3bf30d1c26cdd6 | d02812d699993a0cffdba828f1e6017326e4e6bb | refs/heads/main | 2023-01-30T23:55:43.473438 | 2020-12-11T21:34:57 | 2020-12-11T21:47:10 | 321,221,606 | 3 | 0 | MIT | 2020-12-14T03:27:42 | 2020-12-14T03:27:41 | null | UTF-8 | C++ | false | false | 8,094 | cpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include <WexTestClass.h>
#include "../renderer/inc/DummyRenderTarget.hpp"
#include "../cascadia/TerminalCore/Terminal.hpp"
#include "MockTermSettings.h"
#include "consoletaeftemplates.hpp"
#include "TestUtils.h"
using namespace winrt::Microsoft::Terminal::TerminalControl;
using namespace Microsoft::Terminal::Core;
using namespace WEX::Common;
using namespace WEX::Logging;
using namespace WEX::TestExecution;
namespace TerminalCoreUnitTests
{
class TerminalBufferTests;
};
using namespace TerminalCoreUnitTests;
class TerminalCoreUnitTests::TerminalBufferTests final
{
// !!! DANGER: Many tests in this class expect the Terminal buffer
// to be 80x32. If you change these, you'll probably inadvertently break a
// bunch of tests !!!
static const SHORT TerminalViewWidth = 80;
static const SHORT TerminalViewHeight = 32;
static const SHORT TerminalHistoryLength = 100;
TEST_CLASS(TerminalBufferTests);
TEST_METHOD(TestSimpleBufferWriting);
TEST_METHOD(TestWrappingCharByChar);
TEST_METHOD(TestWrappingALongString);
TEST_METHOD(DontSnapToOutputTest);
TEST_METHOD_SETUP(MethodSetup)
{
// STEP 1: Set up the Terminal
term = std::make_unique<Terminal>();
term->Create({ TerminalViewWidth, TerminalViewHeight }, TerminalHistoryLength, emptyRT);
return true;
}
TEST_METHOD_CLEANUP(MethodCleanup)
{
term = nullptr;
return true;
}
private:
DummyRenderTarget emptyRT;
std::unique_ptr<Terminal> term;
};
void TerminalBufferTests::TestSimpleBufferWriting()
{
auto& termTb = *term->_buffer;
auto& termSm = *term->_stateMachine;
const auto initialView = term->GetViewport();
VERIFY_ARE_EQUAL(0, initialView.Top());
VERIFY_ARE_EQUAL(32, initialView.BottomExclusive());
termSm.ProcessString(L"Hello World");
const auto secondView = term->GetViewport();
VERIFY_ARE_EQUAL(0, secondView.Top());
VERIFY_ARE_EQUAL(32, secondView.BottomExclusive());
TestUtils::VerifyExpectedString(termTb, L"Hello World", { 0, 0 });
}
void TerminalBufferTests::TestWrappingCharByChar()
{
auto& termTb = *term->_buffer;
auto& termSm = *term->_stateMachine;
const auto initialView = term->GetViewport();
auto& cursor = termTb.GetCursor();
const auto charsToWrite = gsl::narrow_cast<short>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(0, initialView.Top());
VERIFY_ARE_EQUAL(32, initialView.BottomExclusive());
for (auto i = 0; i < charsToWrite; i++)
{
// This is a handy way of just printing the printable characters that
// _aren't_ the space character.
const wchar_t wch = static_cast<wchar_t>(33 + (i % 94));
termSm.ProcessCharacter(wch);
}
const auto secondView = term->GetViewport();
VERIFY_ARE_EQUAL(0, secondView.Top());
VERIFY_ARE_EQUAL(32, secondView.BottomExclusive());
// Verify the cursor wrapped to the second line
VERIFY_ARE_EQUAL(charsToWrite % initialView.Width(), cursor.GetPosition().X);
VERIFY_ARE_EQUAL(1, cursor.GetPosition().Y);
// Verify that we marked the 0th row as _wrapped_
const auto& row0 = termTb.GetRowByOffset(0);
VERIFY_IS_TRUE(row0.GetCharRow().WasWrapForced());
const auto& row1 = termTb.GetRowByOffset(1);
VERIFY_IS_FALSE(row1.GetCharRow().WasWrapForced());
TestUtils::VerifyExpectedString(termTb, TestUtils::Test100CharsString, { 0, 0 });
}
void TerminalBufferTests::TestWrappingALongString()
{
auto& termTb = *term->_buffer;
auto& termSm = *term->_stateMachine;
const auto initialView = term->GetViewport();
auto& cursor = termTb.GetCursor();
const auto charsToWrite = gsl::narrow_cast<short>(TestUtils::Test100CharsString.size());
VERIFY_ARE_EQUAL(100, charsToWrite);
VERIFY_ARE_EQUAL(0, initialView.Top());
VERIFY_ARE_EQUAL(32, initialView.BottomExclusive());
termSm.ProcessString(TestUtils::Test100CharsString);
const auto secondView = term->GetViewport();
VERIFY_ARE_EQUAL(0, secondView.Top());
VERIFY_ARE_EQUAL(32, secondView.BottomExclusive());
// Verify the cursor wrapped to the second line
VERIFY_ARE_EQUAL(charsToWrite % initialView.Width(), cursor.GetPosition().X);
VERIFY_ARE_EQUAL(1, cursor.GetPosition().Y);
// Verify that we marked the 0th row as _wrapped_
const auto& row0 = termTb.GetRowByOffset(0);
VERIFY_IS_TRUE(row0.GetCharRow().WasWrapForced());
const auto& row1 = termTb.GetRowByOffset(1);
VERIFY_IS_FALSE(row1.GetCharRow().WasWrapForced());
TestUtils::VerifyExpectedString(termTb, TestUtils::Test100CharsString, { 0, 0 });
}
void TerminalBufferTests::DontSnapToOutputTest()
{
auto& termTb = *term->_buffer;
auto& termSm = *term->_stateMachine;
const auto initialView = term->GetViewport();
VERIFY_ARE_EQUAL(0, initialView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight, initialView.BottomExclusive());
VERIFY_ARE_EQUAL(0, term->_scrollOffset);
// -1 so that we don't print the last \n
for (int i = 0; i < TerminalViewHeight + 8 - 1; i++)
{
termSm.ProcessString(L"x\n");
}
const auto secondView = term->GetViewport();
VERIFY_ARE_EQUAL(8, secondView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight + 8, secondView.BottomExclusive());
VERIFY_ARE_EQUAL(0, term->_scrollOffset);
Log::Comment(L"Scroll up one line");
term->_scrollOffset = 1;
const auto thirdView = term->GetViewport();
VERIFY_ARE_EQUAL(7, thirdView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight + 7, thirdView.BottomExclusive());
VERIFY_ARE_EQUAL(1, term->_scrollOffset);
Log::Comment(L"Print a few lines, to see that the viewport stays where it was");
for (int i = 0; i < 8; i++)
{
termSm.ProcessString(L"x\n");
}
const auto fourthView = term->GetViewport();
VERIFY_ARE_EQUAL(7, fourthView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight + 7, fourthView.BottomExclusive());
VERIFY_ARE_EQUAL(1 + 8, term->_scrollOffset);
Log::Comment(L"Print enough lines to get the buffer just about ready to "
L"circle (on the next newline)");
auto viewBottom = term->_mutableViewport.BottomInclusive();
do
{
termSm.ProcessString(L"x\n");
viewBottom = term->_mutableViewport.BottomInclusive();
} while (viewBottom < termTb.GetSize().BottomInclusive());
const auto fifthView = term->GetViewport();
VERIFY_ARE_EQUAL(7, fifthView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight + 7, fifthView.BottomExclusive());
VERIFY_ARE_EQUAL(TerminalHistoryLength - 7, term->_scrollOffset);
Log::Comment(L"Print 3 more lines, and see that we stick to where the old "
L"rows now are in the buffer (after circling)");
for (int i = 0; i < 3; i++)
{
termSm.ProcessString(L"x\n");
Log::Comment(NoThrowString().Format(
L"_scrollOffset: %d", term->_scrollOffset));
}
const auto sixthView = term->GetViewport();
VERIFY_ARE_EQUAL(4, sixthView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight + 4, sixthView.BottomExclusive());
VERIFY_ARE_EQUAL(TerminalHistoryLength - 4, term->_scrollOffset);
Log::Comment(L"Print 8 more lines, and see that we're now just stuck at the"
L"top of the buffer");
for (int i = 0; i < 8; i++)
{
termSm.ProcessString(L"x\n");
Log::Comment(NoThrowString().Format(
L"_scrollOffset: %d", term->_scrollOffset));
}
const auto seventhView = term->GetViewport();
VERIFY_ARE_EQUAL(0, seventhView.Top());
VERIFY_ARE_EQUAL(TerminalViewHeight, seventhView.BottomExclusive());
VERIFY_ARE_EQUAL(TerminalHistoryLength, term->_scrollOffset);
}
| [
"noreply@github.com"
] | noreply@github.com |
f9b5cd40a99193a9842c104da23ab83a350e6449 | ccddd8c891bcd0587d2bca69ebad42d1b9d57094 | /libuvccamera/src/main/jni/UVCCamera/UVCButtonCallback.cpp | 76fa288a8111e9c5aed897c15f8b64dfc0172220 | [
"Apache-2.0"
] | permissive | ShiKe-And-His-Friends/Connrot | 5ddbf8d3f73f4becca94dbf0e4504b3d649d47bd | d19c878d99ae85eca3663c11897fc4de1772fbff | refs/heads/master | 2021-06-26T04:27:03.452739 | 2021-02-04T06:44:55 | 2021-02-04T06:44:55 | 188,572,899 | 1 | 1 | Apache-2.0 | 2020-05-17T02:33:24 | 2019-05-25T14:00:03 | C | UTF-8 | C++ | false | false | 2,192 | cpp | #include <stdlib.h>
#include <linux/time.h>
#include <unistd.h>
#include "utilbase.h"
#include "UVCButtonCallback.h"
#include "libuvc_internal.h"
#define LOCAL_DEBUG 0
UVCButtonCallback::UVCButtonCallback(uvc_device_handle_t *devh)
: mDeviceHandle(devh),
mButtonCallbackObj(NULL) {
ENTER();
pthread_mutex_init(&button_mutex, NULL);
uvc_set_button_callback(mDeviceHandle, uvc_button_callback, (void *)this);
EXIT();
}
UVCButtonCallback::~UVCButtonCallback() {
ENTER();
pthread_mutex_destroy(&button_mutex);
EXIT();
}
int UVCButtonCallback::setCallback(JNIEnv *env, jobject button_callback_obj) {
ENTER();
pthread_mutex_lock(&button_mutex);
{
if (!env->IsSameObject(mButtonCallbackObj, button_callback_obj)) {
ibuttoncallback_fields.onButton = NULL;
if (mButtonCallbackObj) {
env->DeleteGlobalRef(mButtonCallbackObj);
}
mButtonCallbackObj = button_callback_obj;
if (button_callback_obj) {
// get method IDs of Java object for callback
jclass clazz = env->GetObjectClass(button_callback_obj);
if (LIKELY(clazz)) {
ibuttoncallback_fields.onButton = env->GetMethodID(clazz,
"onButton", "(II)V");
} else {
LOGW("failed to get object class");
}
env->ExceptionClear();
if (!ibuttoncallback_fields.onButton) {
LOGE("Can't find IButtonCallback#onButton");
env->DeleteGlobalRef(button_callback_obj);
mButtonCallbackObj = button_callback_obj = NULL;
}
}
}
}
pthread_mutex_unlock(&button_mutex);
RETURN(0, int);
}
void UVCButtonCallback::notifyButtonCallback(JNIEnv* env, int button, int state) {
pthread_mutex_lock(&button_mutex);
{
if (mButtonCallbackObj) {
env->CallVoidMethod(mButtonCallbackObj, ibuttoncallback_fields.onButton, button, state);
env->ExceptionClear();
}
}
pthread_mutex_unlock(&button_mutex);
}
void UVCButtonCallback::uvc_button_callback(int button, int state, void *user_ptr) {
UVCButtonCallback *buttonCallback = reinterpret_cast<UVCButtonCallback *>(user_ptr);
JavaVM *vm = getVM();
JNIEnv *env;
// attach to JavaVM
vm->AttachCurrentThread(&env, NULL);
buttonCallback->notifyButtonCallback(env, button, state);
vm->DetachCurrentThread();
}
| [
"shike951128"
] | shike951128 |
9e61bf477e4fb8658e5f0cf0ff4903a539caacde | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /include/Pothos/serialization/impl/smart_ptr/detail/sp_counted_base_spin.hpp | 8914b4394473f2ba604d4dc20d2fb3b1c61a1b06 | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,828 | hpp | #ifndef POTHOS_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
#define POTHOS_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// detail/sp_counted_base_spin.hpp - spinlock pool atomic emulation
//
// Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd.
// Copyright 2004-2008 Peter Dimov
//
// 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 <Pothos/serialization/impl/detail/sp_typeinfo.hpp>
#include <Pothos/serialization/impl/smart_ptr/detail/spinlock_pool.hpp>
namespace Pothos
{
namespace detail
{
inline int atomic_exchange_and_add( int * pw, int dv )
{
spinlock_pool<1>::scoped_lock lock( pw );
int r = *pw;
*pw += dv;
return r;
}
inline void atomic_increment( int * pw )
{
spinlock_pool<1>::scoped_lock lock( pw );
++*pw;
}
inline int atomic_conditional_increment( int * pw )
{
spinlock_pool<1>::scoped_lock lock( pw );
int rv = *pw;
if( rv != 0 ) ++*pw;
return rv;
}
class sp_counted_base
{
private:
sp_counted_base( sp_counted_base const & );
sp_counted_base & operator= ( sp_counted_base const & );
int use_count_; // #shared
int weak_count_; // #weak + (#shared != 0)
public:
sp_counted_base(): use_count_( 1 ), weak_count_( 1 )
{
}
virtual ~sp_counted_base() // nothrow
{
}
// dispose() is called when use_count_ drops to zero, to release
// the resources managed by *this.
virtual void dispose() = 0; // nothrow
// destroy() is called when weak_count_ drops to zero.
virtual void destroy() // nothrow
{
delete this;
}
virtual void * get_deleter( sp_typeinfo const & ti ) = 0;
virtual void * get_untyped_deleter() = 0;
void add_ref_copy()
{
atomic_increment( &use_count_ );
}
bool add_ref_lock() // true on success
{
return atomic_conditional_increment( &use_count_ ) != 0;
}
void release() // nothrow
{
if( atomic_exchange_and_add( &use_count_, -1 ) == 1 )
{
dispose();
weak_release();
}
}
void weak_add_ref() // nothrow
{
atomic_increment( &weak_count_ );
}
void weak_release() // nothrow
{
if( atomic_exchange_and_add( &weak_count_, -1 ) == 1 )
{
destroy();
}
}
long use_count() const // nothrow
{
spinlock_pool<1>::scoped_lock lock( &use_count_ );
return use_count_;
}
};
} // namespace detail
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
| [
"josh@joshknows.com"
] | josh@joshknows.com |
8f7b76a68cd5fce4bdb0e63f46a4b0e632ced89b | 55903a9564931b4579e5c5030376f0989d15b00e | /P2pNet/BufferMap.cpp | 02a9a337371a3b127f70c139577fa255e9d3696f | [] | no_license | zhenyouluo/liveshow_r2 | 04b391fd9ba4e809a88aa1e4eed1477ac4e9ef88 | 300441c14ed31cfa10ec0459bac5a67693f592ea | refs/heads/master | 2020-12-26T00:35:26.403288 | 2012-09-10T02:28:22 | 2012-09-10T02:28:22 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,434 | cpp | #include "StdAfx.h"
#include "BufferMap.h"
#include "ace/Thread_Mutex.h"
#include "ace/Guard_T.h"
#include "ace/OS.h"
#include "ace/Log_Msg.h"
BufferMap::BufferMap(void):start_seg_id_(0),bits_(),mutex_()
{
}
BufferMap::~BufferMap(void)
{
}
int BufferMap::set_bit( SEGMENT_ID segId )
{
if (segId < start_seg_id_ || segId >= start_seg_id_ + MAX_SEGMENT_COUNT)//out of range
{
return -1;
}
else
{
ACE_Guard<ACE_Thread_Mutex> guard(mutex_);
bits_.set(segId - start_seg_id_);
return 0;
}
}
bool BufferMap::get_bit( SEGMENT_ID segId )
{
if (segId < start_seg_id_ || segId >= start_seg_id_ + MAX_SEGMENT_COUNT) // out of range
{
return false;
}
else
{
return bits_.at(segId - start_seg_id_);
}
}
const char* BufferMap::get_bytes()
{
char* p;
ACE_NEW_NORETURN(p,char[BM_SIZE]);
int loc_ = 0; //位置指针
ACE_Guard<ACE_Thread_Mutex> guard(mutex_);
ACE_OS::memcpy(p+loc_,&start_seg_id_,sizeof(SEGMENT_ID));
loc_ += sizeof(SEGMENT_ID);
bitset<8> bs_t;
for(int i =0;i < MAX_SEGMENT_COUNT ;i+=8)
{
bs_t.reset();
for(int j=0;j<8;j++)
{
bs_t[j] = bits_[i];
}
u_char v = static_cast<u_char>(bs_t.to_ulong());
ACE_OS::memcpy(p+loc_,&v,1);
loc_ ++;
}
return p;
}
void BufferMap::from_bytes( const char* p )
{
int loc_ =0;
ACE_Guard<ACE_Thread_Mutex> guard(mutex_);
ACE_OS::memcpy(&start_seg_id_ ,p + loc_,sizeof(SEGMENT_ID));
loc_ = sizeof(SEGMENT_ID);
bits_.reset();
for(int i =0;i < BM_SIZE - sizeof(SEGMENT_ID) ; i++ )
{
u_char c ;
ACE_OS::memcpy(&c,p+loc_,1);
loc_++;
bitset<8> bs_t(c);
for(int j = 0; j < 8 ;j++)
{
bits_[i*8 +j ] = bs_t[j];
}
}
}
void BufferMap::time_step()
{
ACE_Guard<ACE_Thread_Mutex> guard(mutex_);
start_seg_id_ ++; //向前移动一秒
//ACE_DEBUG ((LM_DEBUG, "********************\n"));
//ACE_DEBUG ((LM_DEBUG, "bufer time_step called\n"));
if (bits_[0])
{
//ACE_DEBUG ((LM_DEBUG, "%s = %b\n", "start_id:", start_seg_id_ - 1));
}
else
{
ACE_DEBUG ((LM_DEBUG, "%s = %b BUT HAS NO DATA!!!\n", "start_id:", start_seg_id_ - 1));
}
//ACE_DEBUG ((LM_DEBUG, "********************\n"));
for(int i = 0; i < MAX_SEGMENT_COUNT - 1;i++)
{
bits_[i] = bits_[i+1];
}
bits_.reset(MAX_SEGMENT_COUNT -1 );
}
void BufferMap::init( SEGMENT_ID seqId )
{
start_seg_id_ = seqId;
bits_.reset();
} | [
"ankh2008@hotmail.com"
] | ankh2008@hotmail.com |
ddbecdc11c7b33280aac9d06944f9f22ba0f470c | 0a9a614314f9bb804b33b011fdcb297929b2c896 | /CTest16(ConnectTofile.xsl)/CTest16(ConnectTofile.xsl)/MainFrm.cpp | bb72fe13b9f21ed8a9e257c92d25520f4dc037df | [] | no_license | WSJ-github/MFC | f217d6bb0881c6ec8d0091eb9406823be1da513d | 64d264f183f6f1fda5d4d3f42d4385b8780b40fa | refs/heads/master | 2021-03-26T16:18:26.672169 | 2020-06-08T16:16:26 | 2020-06-08T16:16:26 | 247,721,744 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,787 | cpp |
// MainFrm.cpp : CMainFrame 类的实现
//
#include "stdafx.h"
#include "CTest16(ConnectTofile.xsl).h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // 状态行指示器
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame 构造/析构
CMainFrame::CMainFrame()
{
// TODO: 在此添加成员初始化代码
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("未能创建工具栏\n");
return -1; // 未能创建
}
if (!m_wndStatusBar.Create(this))
{
TRACE0("未能创建状态栏\n");
return -1; // 未能创建
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: 如果不需要可停靠工具栏,则删除这三行
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return TRUE;
}
// CMainFrame 诊断
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 消息处理程序
| [
"963013061@qq.com"
] | 963013061@qq.com |
ca2f85a49307522c1ed8aaf5564db18d5f70583e | 245afd9f4adb8d868fa1228ac5898083e4140d4a | /Calculator ver 0.02/App.h | 907b418e30ceaa7af29a1ef2ca630f1c2c9e5b36 | [] | no_license | Ars-eniy-Cheis/ProgramLanguages | 3e50c5eaa7d0f2c2bcdda7651d873484c912c78e | 3b79cef726a347188bb25d468b092e0c59ef6ecf | refs/heads/master | 2021-01-01T11:29:51.555886 | 2020-12-21T16:58:16 | 2020-12-21T16:58:16 | 239,254,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50 | h | #pragma once
class App
{
public:
void Run();
};
| [
"mr.4eis@yandex.ru"
] | mr.4eis@yandex.ru |
b2c8157c7b99658a757db40542e43c4d7463a615 | 1333c64d3426b7c30f638d94c2699c6687a20d16 | /LeetCode/58-Length of Last Word.cpp | 69147068d90d7d58c4f77e09c9bfe698b1ce95b3 | [] | no_license | soar1234/LeetCodeAlgorithms | 44ffbfc25e621ed04f508203f58bef271a80eab8 | d2bfd31cf11b63dbdf685f150852890042aa3b8c | refs/heads/master | 2021-01-24T08:49:43.508672 | 2017-06-05T10:17:52 | 2017-06-05T10:17:52 | 93,390,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_STRING_LEN 80
int lengthOfLastWord(char* s) {
int length=0;
int lastwordlength=0;
int i=0;
char now,pre;
now=s[0];
pre=s[0];
while(now!='\0')
{
printf("%c",now);
if(now!=' ')
{
length++;
printf("\n");
lastwordlength=length;
}
else if(now==' ' && pre!=' ')
{
length=0;
}
i++;
pre=now;
now=s[i];
}
return lastwordlength;
}
int main()
{
char s[]=" a ";
printf("\nLast Word Length is %d",lengthOfLastWord(s));
return 0;
}
| [
"herosaul@gmail.com"
] | herosaul@gmail.com |
71dbcb7df39b42050af80c48142a9949daacdaed | eaf359735e2a12c30949fcec7d811916290dac65 | /FrostScene.cpp | 8cfa32c74a4ab44ed3048c5c204a3900199b0e95 | [
"MIT"
] | permissive | demoscene-source-archive/blitzgewitter | abbe6c23a3d4de4b94112d673425f4309e992e94 | 7a306f73d3cbf4f0d1be5817bc636a14703983b2 | refs/heads/master | 2022-12-04T17:57:17.735244 | 2020-06-02T18:39:12 | 2020-08-22T07:37:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,754 | cpp |
#include "Engine.hpp"
#include "Bezier.hpp"
#include "Ran.hpp"
#include "Particles.hpp"
#include "Tower.hpp"
#include <list>
extern tower::Tower* platonic2_tower;
static inline Real frand()
{
static Ran rnd(643);
return rnd.doub();
}
static long int lrand()
{
static Ran rnd(112);
return rnd.int32();
}
static Vec3 normalize(const Vec3& v)
{
Real rl=Real(1)/std::sqrt(v.lengthSquared());
return v*rl;
}
static const float open_time=5.7f;
static double g_ltime=0;
static const float net_ball_radius = 0.1f;
static const float net_cell_width = 2.0f;
static const float net_cell_height = 1.0f;
static const float net_cell_x_shift = 1.0f;
static const float net_core_radius = 0.02f;
static const float net_coil_outer_radius = 0.05f;
static const float net_coil_inner_radius = 0.01f;
static const int net_core_coil_count = 5;
static const float square_root_of_two = 1.4142135623730951f;
static const float net_core_length = square_root_of_two - net_ball_radius * 2.0f;
static const int net_width = 5, net_height = 5;
static const int net_ball_count = net_width * net_height;
static const int net_ball_grid_size = 8;
static const int net_core_divisions = 8;
static const int net_coil_outer_divisions = 8;
static const int net_coil_inner_divisions = 8;
static const int net_pylon_count = (net_height - 1) * net_width + (net_width - 1) * (net_height - 1);
static const int net_ball_vertex_count = 8 + (net_ball_grid_size - 2) * (net_ball_grid_size - 2) * 6 + (net_ball_grid_size - 2) * 12;
static const int net_core_vertex_count = net_core_divisions * 2;
static const int net_coil_vertex_count = net_core_coil_count * net_coil_outer_divisions * net_coil_inner_divisions;
static const int net_pylon_vertex_count = net_core_vertex_count + net_coil_vertex_count;
static const int net_max_vertices = net_ball_count * net_ball_vertex_count + net_pylon_count * net_pylon_vertex_count;
static const int net_ball_index_count = (net_ball_grid_size - 1) * 4 * (net_ball_grid_size - 1) * 2 + (net_ball_grid_size - 1) * net_ball_grid_size * 2 * 2; // TRIANGLE_STRIPs
static const int net_core_index_count = net_core_divisions * 2; // TRIANGLE_STRIPs
static const int net_coil_index_count = net_core_coil_count * net_coil_outer_divisions * 2 * net_coil_inner_divisions; // TRIANGLE_STRIPs
static const int net_pylon_index_count = net_core_index_count + net_coil_index_count; // TRIANGLE_STRIPs
static const int net_max_indices = net_ball_count * net_ball_index_count + net_pylon_count * net_pylon_index_count;
static const int net_ball_strip_count = (net_ball_grid_size - 1) * 3;
static const int net_core_strip_count = 1;
static const int net_coil_strip_count = net_core_coil_count * net_coil_inner_divisions;
static const int net_pylon_strip_count = net_core_strip_count + net_coil_strip_count;
static const int net_max_strips = net_ball_count * net_ball_strip_count + net_pylon_count * net_pylon_strip_count;
namespace lightning
{
float base_branch_length = 160;
float large_noise_warp = 50;
float small_noise_warp = 40;
float grow_shrink_rate = 0.15f;
float grow_shrink_exp = 1.1f;
float max_depth = 5.0f;
float angle_distribution = 0.7f;
float branch_shorten_factor = 0.8f;
float roll_rate_factor = 1.0f;
float noise2(float x,float y=0,float z=0)
{
static bool init=true;
static const int size=64;
static float values[size*size*size];
if(init)
{
Ran lrnd(4343);
for(int z=0;z<size;++z)
for(int y=0;y<size;++y)
for(int x=0;x<size;++x)
{
values[x+(y+z*size)*size]=lrnd.doub();
}
init=false;
}
const int ix=int(x) & (size-1);
const int iy=int(y) & (size-1);
const int iz=int(z) & (size-1);
const float fx=x-floor(x);
const float fy=y-floor(y);
const float fz=z-floor(z);
float vs[8];
for(int w=0;w<2;++w)
for(int v=0;v<2;++v)
for(int u=0;u<2;++u)
{
vs[u+(v+w*2)*2]=values[((ix+u)&(size-1))+(((iy+v)&(size-1))+((iz+w)&(size-1))*size)*size];
}
float a=(vs[0]*(1.0f-fx)+vs[1]*fx)*(1.0f-fy)+
(vs[2]*(1.0f-fx)+vs[3]*fx)*fy;
float b=(vs[4]*(1.0f-fx)+vs[5]*fx)*(1.0f-fy)+
(vs[6]*(1.0f-fx)+vs[7]*fx)*fy;
return a*(1.0f-fz)+b*fz;
}
float noise(float x,float y=0,float z=0)
{
float f=0;
for(int i=0;i<3;++i)
{
float s=float(1<<i);
f+=noise2(x*s,y*s,z*s)*0.5f/s;
}
return f;
}
int fc=0;
int id_counter = 0;
struct Node
{
Node(Node* parent, float angle)
{
id = id_counter++;
pos = Vec2(0,0);
this->angle = angle;
this->parent = parent;
}
void grow(int depth, int grow_by)
{
if (depth > 0)
{
for(std::vector<Node>::iterator it=subnodes.begin();it!=subnodes.end();++it)
it->grow(depth - 1, grow_by);
}
else
createSubnodes(grow_by);
}
void createSubnodes(int depth)
{
if (depth <= 0)
return;
subnodes.clear();
for (int i = 0; i < 2; ++i)
{
Node sn(this, angle);
sn.angle += angle_distribution * (i * 2 - 1) + (noise(sn.id) - 0.5) * 2;
sn.l = l * branch_shorten_factor;
sn.createSubnodes(depth - 1);
subnodes.push_back(sn);
}
}
void render(int depth, Vec2 org, float depthf, int depthc, GLushort& num_vertices, GLfloat* vertices, GLfloat* colours)
{
if (depth < 0)
return;
float tween = 1.0f - (float(depthc) - depthf);
Vec2 dir=Vec2(cos(angle)*l, sin(angle)*l);
Vec2 end=org + dir;
float ti = fc * 0.03 * roll_rate_factor;
float sx = 0.04, sy = 0.02;
float ss = 0.3f;
static const int n = 64;
//Vec2* prev = 0;
num_vertices=0;
if(parent)
{
for (int i = 0; i <= n; ++i)
{
float t = std::min(float(i) / float(n), tween);
//Vec3 col= lerpColor(color(50, 50, 255), color(200, 200, 255), 1.0 / (t + float(1 + depthc))));
Vec3 col= mix(Vec3(50, 50, 255), Vec3(200, 200, 255), 1.0 / (t + float(1 + depthc)));
Vec2 mid = ((org * (1.0f - t)) + (end * t));
Vec2 disp = Vec2(noise(mid.x * sx, mid.y * sy, ti), noise(mid.x * sx, mid.y * sy, ti * 2)) * small_noise_warp;
mid = mid + disp;
disp = Vec2(noise(mid.x * sx * ss, mid.y * sy * ss, ti * 1.3),
noise(mid.x * sx * ss, mid.y * sy * ss, 10 + ti * 1.2)) * large_noise_warp;
mid = mid + disp;
colours[num_vertices*3+0]=col.x/255.0f;
colours[num_vertices*3+1]=col.y/255.0f;
colours[num_vertices*3+2]=col.z/255.0f;
vertices[num_vertices*2+0]=mid.x*0.005;
vertices[num_vertices*2+1]=mid.y*0.005;
++num_vertices;
//if (prev != 0)
// line(prev.x, prev.y, mid.x, mid.y);
//prev = mid;
}
glDrawArrays(GL_LINE_STRIP, 0, num_vertices);
}
//line(org.x, org.y, end.x, end.y);
//for (Node sn : subnodes)
for(std::vector<Node>::iterator it=subnodes.begin();it!=subnodes.end();++it)
it->render(depth - 1, end, depthf, depthc + 1, num_vertices, vertices, colours);
}
float l;
int id;
Node* parent;
float angle;
Vec2 pos;
std::vector<Node> subnodes;
};
struct Tree
{
Tree(const Vec2& origin): root(0, 0)
{
this->origin = origin;
root.l = base_branch_length;
}
void shrinkOrGrow(float to_depthf)
{
int to_depth = ceil(to_depthf);
depthf = to_depthf;
if (to_depth < depth)
depth = to_depth;
else if (to_depth > depth)
{
root.grow(depth, to_depth - depth);
depth = to_depth;
}
}
void render(GLushort& num_vertices, GLfloat* vertices, GLfloat* colours)
{
root.render(depth, origin, depthf, 0, num_vertices, vertices, colours);
}
Vec2 origin;
Node root;
float depthf;
int depth;
};
}
class FrostScene: public Scene
{
struct Worm
{
std::list<Vec3> position_history;
Vec3 position;
Vec3 direction;
Real step_count;
Worm()
{
step_count=0;
position=Vec3(0,0,0);
direction=Vec3(0,0,0);
}
};
struct Box
{
Vec3 size;
Mat4 xfrm, xfrm_inv;
};
static const int num_boxes = 8;
static const int num_worms = 10;
Box boxes[num_boxes];
Worm worms[num_worms];
static const int random_grid_w = 256;
static const int random_grid_h = 256;
float random_grid[random_grid_w*random_grid_h];
void initRandomGrid();
float randomGridLookup(float u, float v) const;
GLfloat spiral_vertices[4096 * 3];
GLushort spiral_indices[4096];
GLushort spiral_num_vertices, spiral_num_indices;
static const GLushort lightning_max_vertices=2048;
GLfloat lightning_vertices[lightning_max_vertices*2];
GLfloat lightning_colours[lightning_max_vertices*3];
Shader forrest_shader, bokeh_shader, bokeh2_shader;
Shader gaussbokeh_shader, composite_shader;
Shader mb_accum_shader;
Shader screendisplay_shader;
Shader bgfg_shader;
Shader lightning_shader;
Shader forrest2_shader;
Mesh scene_mesh;
Mesh icosahedron_mesh;
bool drawing_view_for_background;
int num_subframes;
float subframe_scale;
float lltime;
GLuint net_strip_offsets[net_max_strips];
GLuint net_indices[net_max_indices];
GLfloat net_vertices[net_max_vertices*3];
void initNet();
static const int num_fbos = 16, num_texs = 16;
GLuint fbos[num_fbos], texs[num_texs], renderbuffers[num_fbos];
GLuint bokeh_temp_fbo;
GLuint bokeh_temp_tex_1, bokeh_temp_tex_2;
GLuint noise_tex_2d;
lightning::Tree litree0,litree1;
void initializeTextures();
void initializeShaders();
void initializeBuffers();
void initWorms();
void initBoxes();
void drawView(float ltime);
void createSpiral();
void gaussianBlur(Real tint_r, Real tint_g, Real tint_b, Real radx, Real rady, GLuint fbo0, GLuint fbo1, GLuint src_tex, GLuint tex0);
void drawLightning(float ltime);
void drawHangingBalls(float ltime);
void drawTower(tower::Tower& twr, const Mat4& modelview, Real camheight);
void step();
void addHistory(Worm& w);
double sceneDistance(const Vec3& p);
Vec3 sceneGradient(const Vec3& p);
void stepWorm(Worm& w,int i);
public:
FrostScene(): scene_mesh(256, 256), litree0(Vec2(-200, 0)), litree1(Vec2(-200, 0)), icosahedron_mesh(32, 32)
{
}
~FrostScene()
{
free();
}
void slowInitialize();
void initialize();
void render();
void update();
void free();
};
Scene* frostScene = new FrostScene();
void FrostScene::initNet()
{
// cores
static const float core_t0=net_ball_radius;
static const float core_t1=net_core_length-net_ball_radius;
for(int i=0;i<net_pylon_count;++i)
{
const int x=i%(net_width*2-1);
const int y=i/(net_width*2-1);
for(int j=0;j<net_core_divisions;++j)
{
const float angle=float(j)/float(net_core_divisions)*2*M_PI;
const float s=std::sin(angle);
const float c=std::cos(angle);
{
int k = i * net_core_vertex_count + j * 2 + 0;
net_vertices[k * 3 + 0] = (x / 2) * net_cell_width + (y & 1) * net_cell_x_shift + square_root_of_two * s * net_core_radius + ((x & 1) ? -square_root_of_two : +square_root_of_two) * core_t0;
net_vertices[k * 3 + 1] = (y / 2) * net_cell_height - ((x & 1) ? +square_root_of_two : -square_root_of_two) * s * net_core_radius + square_root_of_two * core_t0;
net_vertices[k * 3 + 2] = c * net_core_radius;
}
{
int k = i * net_core_vertex_count + j * 2 + 1;
net_vertices[k * 3 + 0] = (x / 2) * net_cell_width + (y & 1) * net_cell_x_shift + square_root_of_two * s * net_core_radius + ((x & 1) ? -square_root_of_two : +square_root_of_two) * core_t1;
net_vertices[k * 3 + 1] = (y / 2) * net_cell_height - ((x & 1) ? +square_root_of_two : -square_root_of_two) * s * net_core_radius + square_root_of_two * core_t1;
net_vertices[k * 3 + 2] = c * net_core_radius;
}
}
}
}
void FrostScene::step()
{
for(int i=0;i<num_worms;++i)
stepWorm(worms[i],i);
}
void FrostScene::addHistory(Worm& w)
{
w.position_history.push_back(w.position);
if(w.position_history.size()>4000)
w.position_history.pop_front();
}
template<typename T>
static T smin(T a,T b,T k)
{
return -std::log(std::exp(-k*a)+std::exp(-k*b))/k;
}//from iq
double FrostScene::sceneDistance(const Vec3& p)
{
static const double k = 10.0;
double dist = 1e3;
for(int i=0;i<num_boxes;++i)
{
const Box& b=boxes[i];
const Vec3 pt = b.xfrm_inv * p;
double dx=std::max(0.0f, std::abs(pt.x) - b.size.x);
double dy=std::max(0.0f, std::abs(pt.y) - b.size.y);
double dz=std::max(0.0f, std::abs(pt.z) - b.size.z);
dist=smin(dist,std::sqrt(dx*dx+dy*dy+dz*dz) - 0.1,k);
}
return dist;
//return std::sqrt(p.lengthSquared()) - 1.0;
}
Vec3 FrostScene::sceneGradient(const Vec3& p)
{
static const double eps=1e-3;
double c = sceneDistance(p);
return Vec3(sceneDistance(p + Vec3(eps, 0.0, 0.0)) - c,
sceneDistance(p + Vec3(0.0, eps, 0.0)) - c,
sceneDistance(p + Vec3(0.0, 0.0, eps)) - c) * (1.0 / eps);
}
void FrostScene::stepWorm(Worm& w, int i)
{
addHistory(w);
Vec3 target=w.position+w.direction*1.0;
const double d = sceneDistance(target);
Vec3 n = sceneGradient(target);
normalize(n);
target -= n * d;
w.direction = target - w.position;
normalize(w.direction);
w.position = target;
Vec3 tang=n.cross(w.direction);
normalize(tang);
w.direction+=tang*0.2*randomGridLookup(i,w.step_count*0.02);
normalize(w.direction);
++w.step_count;
}
void FrostScene::initWorms()
{
for(int i=0;i<num_worms;++i)
{
worms[i].position=Vec3(frand()-0.5,frand()-0.5,frand()-0.5);
worms[i].direction=Vec3(frand()-0.5,frand()-0.5,frand()-0.5);
}
}
void FrostScene::initBoxes()
{
Ran lrnd(639);
for(int i=0;i<num_boxes;++i)
{
/*
boxes[i].size = Vec3(1.0,0.2,1.0);
boxes[i].xfrm = Mat4::translation(Vec3((frand()-0.5)*7.0,(frand()-0.5),(frand()-0.5)*7.0));
*/
boxes[i].size = Vec3(0.5,0.2,0.5);
boxes[i].xfrm = Mat4::rotation(lrnd.doub()*M_PI*2,Vec3(0,1,0)) * Mat4::rotation(lrnd.doub()*M_PI*2,Vec3(1,0,0)) * Mat4::translation(Vec3((frand()-0.5)*3.0,(frand()-0.5),(frand()-0.5)*3.0));
boxes[i].xfrm_inv = boxes[i].xfrm.inverse();
}
}
void FrostScene::initRandomGrid()
{
for(int y=0;y<random_grid_h;++y)
for(int x=0;x<random_grid_w;++x)
{
random_grid[x+y*random_grid_w]=(frand()-0.5)*2.0;
}
}
float FrostScene::randomGridLookup(float u, float v) const
{
u=fmodf(u,float(random_grid_w));
v=fmodf(v,float(random_grid_h));
if(u<0)
u+=random_grid_w;
if(v<0)
v+=random_grid_h;
const int iu=int(u);
const int iv=int(v);
const float fu=u-float(iu);
const float fv=v-float(iv);
const float a=random_grid[iu+iv*random_grid_w];
const float b=random_grid[((iu+1)%random_grid_w)+iv*random_grid_w];
const float c=random_grid[((iu+1)%random_grid_w)+((iv+1)%random_grid_h)*random_grid_w];
const float d=random_grid[iu+((iv+1)%random_grid_h)*random_grid_w];
return (1.0-fv)*((1.0-fu)*a+fu*b) + fv*((1.0-fu)*d+fu*c);
}
void FrostScene::slowInitialize()
{
initRandomGrid();
initWorms();
initBoxes();
for(int i=0;i<num_boxes;++i)
{
Mesh cube;
cube.generateCube();
cube.transform(Mat4::scale(boxes[i].size));
scene_mesh.addInstance(cube, boxes[i].xfrm);
}
icosahedron_mesh.generateIcosahedron();
initializeShaders();
}
void FrostScene::initializeTextures()
{
glGenTextures(num_texs, texs);
createWindowTexture(texs[0], GL_RGBA16F);
createWindowTexture(texs[2], GL_RGBA16F);
createWindowTexture(texs[4], GL_RGBA16F, 4);
createWindowTexture(texs[5], GL_RGBA16F, 4);
createWindowTexture(texs[6], GL_RGBA16F);
createWindowTexture(texs[9], GL_RGBA16F, 4);
createWindowTexture(texs[12], GL_RGBA16F, 2);
createWindowTexture(texs[13], GL_RGBA16F, 2);
CHECK_FOR_ERRORS;
glBindTexture(GL_TEXTURE_2D, 0);
noise_tex_2d = texs[11];
bokeh_temp_tex_1 = texs[12];
bokeh_temp_tex_2 = texs[13];
{
uint w = 128, h = 128;
uint pix[w*h];
for(uint y = 0; y < h; ++y)
for(uint x=0;x<w;++x)
{
pix[x+y*w]=(lrand()&255) | ((lrand()&255) <<8)|((lrand()&255))<<16;
}
glBindTexture(GL_TEXTURE_2D, noise_tex_2d);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, w, h);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pix);
CHECK_FOR_ERRORS;
}
}
void FrostScene::initializeBuffers()
{
glGenFramebuffers(num_fbos, fbos);
glGenRenderbuffers(num_fbos, renderbuffers);
bokeh_temp_fbo = fbos[12];
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffers[1]);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, window_width, window_height);
CHECK_FOR_ERRORS;
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[0]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[0], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[3]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[2], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[4]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[4], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[5]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[5], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[6]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[6], 0);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderbuffers[1]);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[9]);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texs[9], 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bokeh_temp_fbo);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, bokeh_temp_tex_1, 0);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, bokeh_temp_tex_2, 0);
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
CHECK_FOR_ERRORS;
}
void FrostScene::initializeShaders()
{
lightning_shader.load(SHADERS_PATH "lines_lightning_v.glsl", SHADERS_PATH "lines_lightning_g.glsl", SHADERS_PATH "lines_lightning_f.glsl");
forrest_shader.load(SHADERS_PATH "forrest_v.glsl", NULL, SHADERS_PATH "forrest4_f.glsl");
forrest2_shader.load(SHADERS_PATH "forrest2_v.glsl", NULL, SHADERS_PATH "forrest2_f.glsl");
bokeh_shader.load(SHADERS_PATH "generic_v.glsl", NULL, SHADERS_PATH "bokeh_f.glsl");
bokeh_shader.uniform1i("tex0", 0);
bokeh_shader.uniform1f("aspect_ratio", float(window_height) / float(window_width));
bokeh2_shader.load(SHADERS_PATH "generic_v.glsl", NULL,SHADERS_PATH "bokeh2_f.glsl");
bokeh2_shader.uniform1i("tex1", 0);
bokeh2_shader.uniform1i("tex2", 1);
bokeh2_shader.uniform1f("aspect_ratio", float(window_height) / float(window_width));
gaussbokeh_shader.load(SHADERS_PATH "generic_v.glsl", NULL, SHADERS_PATH "gaussblur_f.glsl");
gaussbokeh_shader.uniform1i("tex0", 0);
mb_accum_shader.load(SHADERS_PATH "generic_v.glsl", NULL, SHADERS_PATH "mb_accum_f.glsl");
mb_accum_shader.uniform1i("tex0", 0);
composite_shader.load(SHADERS_PATH "generic_v.glsl", NULL, SHADERS_PATH "cubes_composite_f.glsl");
composite_shader.uniform1i("tex0", 0);
composite_shader.uniform1i("tex1", 1);
composite_shader.uniform1i("bloom_tex", 4);
composite_shader.uniform1i("bloom2_tex", 5);
screendisplay_shader.load(SHADERS_PATH "lines_frost_v.glsl", SHADERS_PATH "lines_frost_g.glsl", SHADERS_PATH "lines_frost_f.glsl");
bgfg_shader.load(SHADERS_PATH "generic_v.glsl", NULL, SHADERS_PATH "bgfg_f.glsl");
bgfg_shader.uniform1i("tex0", 0);
bgfg_shader.uniform1i("tex1", 1);
}
void FrostScene::initialize()
{
if(initialized)
return;
initialized = true;
initializeTextures();
initializeBuffers();
assert(platonic2_tower);
}
void FrostScene::update()
{
using namespace lightning;
++g_ltime;
step();
litree0.shrinkOrGrow(-0.5f + pow(noise(0 + fc * grow_shrink_rate), grow_shrink_exp) * max_depth);
litree1.shrinkOrGrow(-0.5f + pow(noise(10 + fc * grow_shrink_rate), grow_shrink_exp) * max_depth);
}
void FrostScene::drawTower(tower::Tower& twr, const Mat4& modelview, Real camheight)
{
const Real camheightrange = drawing_view_for_background ? 40 : 10;
const Real tscale=cubic(clamp((lltime+11.5f)/5.5f,0.0f,1.0f));
forrest2_shader.bind();
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(2);
lltime+=open_time; // HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACK
unsigned int piece_index=0;
for(std::vector<tower::PieceInstance>::iterator p=twr.instances.begin();p!=twr.instances.end();++p,++piece_index)
{
std::map<std::string,Real>& ps=p->parameters;
if((ps["background"]>0.5)!=drawing_view_for_background)
continue;
if(camheight < (p->section->height1 - camheightrange) || camheight > (p->section->height0 + camheightrange))
continue;
Mesh* mesh=&icosahedron_mesh;
mesh->bind();
forrest2_shader.uniform1f("time", lltime*ps["time_scale"]+ps["time_offset"]);
forrest2_shader.uniform1f("ptn_thickness",ps["ptn_thickness"]);
forrest2_shader.uniform1f("ptn_brightness",ps["ptn_brightness"]);
forrest2_shader.uniform1f("ptn_scroll",ps["ptn_scroll"]);
forrest2_shader.uniform1f("ptn_frequency",ps["ptn_frequency"]);
forrest2_shader.uniform1f("shimmer",ps["shimmer"]);
forrest2_shader.uniform1f("l0_scroll",ps["l0_scroll"]);
forrest2_shader.uniform1f("l0_brightness",ps["l0_brightness"]);
forrest2_shader.uniform1f("l1_scroll",ps["l1_scroll"]);
forrest2_shader.uniform1f("l1_brightness",ps["l1_brightness"]);
forrest2_shader.uniform1f("l2_scroll",ps["l2_scroll"]);
forrest2_shader.uniform1f("l2_brightness",ps["l2_brightness"]);
forrest2_shader.uniform1f("ambient",ps["ambient"]);
const float upwards=(piece_index == 27) ? 0.0f : std::pow(std::max(0.0f,(lltime-15.0f-piece_index*0.1f)),2.0f)*0.9f;
const float rs=(piece_index == 27) ? 0.96f : 1.0f;
Mat4 modelview2 = modelview * Mat4::rotation(lltime * ps["section_rot_spd"], Vec3(0,1,0)) *
Mat4::translation(Vec3(Vec3(std::cos(ps["angle"])*ps["distance"], ps["height"]-upwards, std::sin(ps["angle"])*ps["distance"]) * tscale)) *
Mat4::rotation(ps["rot_z"]+lltime*ps["rot_spd_z"]*rs,Vec3(0,0,1)) * Mat4::rotation(ps["rot_y"]+lltime*ps["rot_spd_y"]*rs,Vec3(0,1,0)) * Mat4::rotation(ps["rot_x"]+lltime*ps["rot_spd_x"]*rs,Vec3(1,0,0)) *
Mat4::scale(Vec3(ps["sca_x"],ps["sca_y"],ps["sca_z"]));
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->getVertexCount() * sizeof(GLfloat) * 3));
forrest2_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, modelview2.e);
//// 011011
//if(piece_index==27)
glDrawRangeElements(GL_TRIANGLES, 0, mesh->getVertexCount() - 1, mesh->getTriangleCount() * 3, GL_UNSIGNED_INT, 0);
CHECK_FOR_ERRORS;
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(2);
}
void FrostScene::createSpiral()
{
const double s = drawing_view_for_background ? 1.1 : 1;
if(drawing_view_for_background)
screendisplay_shader.uniform4f("colour", 0.5 * 0.6 * 0.5, 0.7 * 0.8 * 0.5, 1 * 0.6 * 0.5, 1);
else
screendisplay_shader.uniform4f("colour", 0.5, 0.7, 1, 1);
for(int i=0;i<num_worms;++i)
{
spiral_num_vertices = 0;
spiral_num_indices = 0;
for(std::list<Vec3>::const_iterator it=worms[i].position_history.begin();it!=worms[i].position_history.end();++it)
{
spiral_indices[spiral_num_indices++] = spiral_num_vertices;
spiral_vertices[spiral_num_vertices * 3 + 0] = it->x * s;
spiral_vertices[spiral_num_vertices * 3 + 1] = it->y * s;
spiral_vertices[spiral_num_vertices * 3 + 2] = it->z * s;
++spiral_num_vertices;
}
glDrawRangeElements(GL_LINE_STRIP, 0, spiral_num_vertices - 1, spiral_num_indices, GL_UNSIGNED_SHORT, spiral_indices);
}
}
void FrostScene::drawLightning(float ltime)
{
using namespace lightning;
fc = ltime*1000.0/20.0;
GLushort num_vertices=0;
const float flup=std::pow(std::max(0.0f,ltime-open_time)*0.4f,2.0f);
Mat4 projection = Mat4::identity();
Mat4 modelview = Mat4::translation(Vec3(0,-flup*0.5f,0)) * Mat4::scale(Vec3(float(window_height)/float(window_width),1.0f,1.0f));
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE,GL_ONE);
lightning_shader.bind();
lightning_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, modelview.e);
lightning_shader.uniformMatrix4fv("projection", 1, GL_FALSE, projection.e);
lightning_shader.uniform1f("time",ltime);
lightning_shader.uniform2f("radii", 0.01, 0.01);
lightning_shader.uniform4f("colour", 1,1,1,1);
lightning_shader.uniform1f("aspect_ratio",float(window_height)/float(window_width));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, lightning_vertices);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, lightning_colours);
litree0.render(num_vertices, lightning_vertices, lightning_colours);
lightning_shader.uniformMatrix4fv("projection", 1, GL_FALSE, (projection*Mat4::scale(Vec3(-1,1,1))).e);
litree1.render(num_vertices, lightning_vertices, lightning_colours);
assert(num_vertices<=lightning_max_vertices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void FrostScene::drawView(float ltime)
{
lltime = ltime;
const float aspect_ratio = float(window_height) / float(window_width);
const float jitter_x = frand() / window_width * 3;
const float jitter_y = frand() / window_height * aspect_ratio * 3;
const float fov = (drawing_view_for_background ? M_PI * 0.145f : M_PI * 0.15f) * mix(2.0f,1.0f,ltime/(ltime+1.0f));
const float znear = 1.0f / tan(fov * 0.5f), zfar = 1024.0f;
Mat4 projection = Mat4::frustum(-1.0f + jitter_x, +1.0f + jitter_x, -aspect_ratio + jitter_y, +aspect_ratio + jitter_y, znear, zfar);
const float move_back = drawing_view_for_background ? 0 : 0;
const float flup=std::pow(std::max(0.0f,ltime-open_time)*0.5f,2.0f);
Mat4 modelview = Mat4::rotation(cos(ltime * 15.0) * 0.01 / 128, Vec3(0.0f, 1.0f, 0.0f));
modelview = modelview * Mat4::rotation(sin(ltime * 17.0) * 0.01 / 128, Vec3(1.0f, 0.0f, 0.0f)) * Mat4::translation(Vec3(0, -10 - flup, -15 - move_back + ltime * 0.02));
modelview = Mat4::rotation(0.6, Vec3(1.0f,0.0f, 0.0f)) * modelview * Mat4::rotation(-0.5f+ltime*0.04, Vec3(0.0f, 1.0f, 0.0f));
glViewport(0, 0, window_width, window_height);
CHECK_FOR_ERRORS;
glDepthMask(GL_TRUE);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
CHECK_FOR_ERRORS;
forrest_shader.uniformMatrix4fv("projection", 1, GL_FALSE, projection.e);
screendisplay_shader.uniformMatrix4fv("projection", 1, GL_FALSE, projection.e);
CHECK_FOR_ERRORS;
glUseProgram(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
if(!drawing_view_for_background)
{
drawLightning(ltime);
}
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
//if(!drawing_view_for_background)
{
static const float pivot_distance=-3.0f;
static const float pivot_speed=0.6f;
const float pivot_amount=std::pow(clamp((ltime-open_time)*0.3f,0.0f,1.0f),0.5f);
forrest_shader.bind();
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(2);
Mesh* mesh=&scene_mesh;
mesh->bind();
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(mesh->getVertexCount() * sizeof(GLfloat) * 3));
//forrest_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, modelview.e);
forrest_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, (modelview * Mat4::translation(Vec3(0,0,+pivot_distance)) * Mat4::rotation(+pivot_amount*pivot_speed,Vec3(0,1,0)) * Mat4::translation(Vec3(0,0,-pivot_distance))).e);
forrest_shader.uniform1f("clip_side", +1.0f);
glDrawRangeElements(GL_TRIANGLES, 0, mesh->getVertexCount() - 1, mesh->getTriangleCount() * 3, GL_UNSIGNED_INT, 0);
forrest_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, (modelview * Mat4::translation(Vec3(0,0,+pivot_distance)) * Mat4::rotation(-pivot_amount*pivot_speed,Vec3(0,1,0)) * Mat4::translation(Vec3(0,0,-pivot_distance))).e);
forrest_shader.uniform1f("clip_side", -1.0f);
glDrawRangeElements(GL_TRIANGLES, 0, mesh->getVertexCount() - 1, mesh->getTriangleCount() * 3, GL_UNSIGNED_INT, 0);
glEnable(GL_BLEND);
glEnable(GL_CULL_FACE);
glDepthMask(GL_FALSE);
CHECK_FOR_ERRORS;
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(2);
//glEnable( GL_CLIP_PLANE0 );
glEnable(GL_CLIP_DISTANCE0);
screendisplay_shader.bind();
screendisplay_shader.uniform1f("brightness", 1);
screendisplay_shader.uniform1f("time", ltime);
screendisplay_shader.uniform2f("radii", 0.005, 0.005);
glDepthMask(GL_FALSE);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, spiral_vertices);
screendisplay_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, (modelview * Mat4::translation(Vec3(0,0,+pivot_distance)) * Mat4::rotation(+pivot_amount*pivot_speed,Vec3(0,1,0)) * Mat4::translation(Vec3(0,0,-pivot_distance))).e);
screendisplay_shader.uniform1f("clip_side", +1.0f);
createSpiral();
screendisplay_shader.uniformMatrix4fv("modelview", 1, GL_FALSE, (modelview * Mat4::translation(Vec3(0,0,+pivot_distance)) * Mat4::rotation(-pivot_amount*pivot_speed,Vec3(0,1,0)) * Mat4::translation(Vec3(0,0,-pivot_distance))).e);
screendisplay_shader.uniform1f("clip_side", -1.0f);
createSpiral();
glDisableVertexAttribArray(0);
glDisable(GL_CLIP_DISTANCE0);
//glDisable(GL_CLIP_PLANE0);
glDisable(GL_BLEND);
}
if(!drawing_view_for_background && ltime > open_time)
{
drawHangingBalls(ltime - open_time);
}
glDepthMask(GL_TRUE);
CHECK_FOR_ERRORS;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void FrostScene::drawHangingBalls(float ltime)
{
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
ltime-=11.5f;
lltime = ltime;
const float aspect_ratio = float(window_height) / float(window_width);
const float jitter_x = frand() / window_width * 3;
const float jitter_y = frand() / window_height * aspect_ratio * 3;
const float fov = M_PI * 0.3f;
const float znear = 1.0f / tan(fov * 0.5f), zfar = 256.0f;
const float frustum_scale = 1.0f/512.0f;
Mat4 projection = Mat4::frustum((-1.0f + jitter_x)*frustum_scale, (+1.0f + jitter_x)*frustum_scale, (-aspect_ratio + jitter_y)*frustum_scale, (+aspect_ratio + jitter_y)*frustum_scale, znear*frustum_scale, zfar);
const float move_back = drawing_view_for_background ? 10 : 0;
forrest2_shader.uniformMatrix4fv("projection", 1, GL_FALSE, projection.e);
ltime+=open_time; // HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACK
Mat4 modelview = Mat4::rotation(cos(ltime * 15.0) * 0.01 / 128, Vec3(0.0f, 1.0f, 0.0f)) * Mat4::rotation(sin(ltime * 17.0) * 0.01 / 128, Vec3(1.0f, 0.0f, 0.0f)) *
Mat4::translation(Vec3(0, 0, -45 - move_back + ltime * 0.2));
drawTower(*platonic2_tower, modelview, 0);
}
void FrostScene::gaussianBlur(Real tint_r, Real tint_g, Real tint_b, Real radx, Real rady, GLuint fbo0, GLuint fbo1, GLuint src_tex, GLuint tex0)
{
static const GLfloat vertices[] = { -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f };
static const GLfloat coords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f };
static const GLubyte indices[] = { 3, 0, 2, 1 };
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glViewport(0, 0, window_width / 4, window_height / 4);
// gaussian blur pass 1
{
gaussbokeh_shader.uniform4f("tint", tint_r, tint_g, tint_b, 1.0f);
}
const float gauss_radx = radx;
const float gauss_rady = rady;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo0);
{
GLenum buffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(sizeof(buffers) / sizeof(buffers[0]), buffers);
}
CHECK_FOR_ERRORS;
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
gaussbokeh_shader.bind();
gaussbokeh_shader.uniform2f("direction", gauss_radx * float(window_height) / float(window_width), 0.0f);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, src_tex);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
// gaussian blur pass 2
gaussbokeh_shader.uniform4f("tint", 1, 1, 1, 1);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo1);
{
GLenum buffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(sizeof(buffers) / sizeof(buffers[0]), buffers);
}
CHECK_FOR_ERRORS;
gaussbokeh_shader.uniform2f("direction", 0.0f, gauss_rady);
glBindTexture(GL_TEXTURE_2D, tex0);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
CHECK_FOR_ERRORS;
}
void FrostScene::render()
{
static const GLfloat vertices[] = { -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f };
static const GLfloat coords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f };
static const GLubyte indices[] = { 3, 0, 2, 1 };
const float aspect_ratio = float(window_height) / float(window_width);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
for(int nn = 0; nn < 2; ++nn)
{
//if(drawing_view_for_background) continue; // **********************************************************************************
drawing_view_for_background = !nn;
// ----- motion blur ------
const float cc=(1.0f-cubic(clamp((time-9.5f)/2.0f,0.0f,1.0f)))*1.5f;
glClearColor(0.0006f*cc, 0.0012f*cc, 0.003f*cc, 0.0f);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[3]);
glClear(GL_COLOR_BUFFER_BIT);
num_subframes = drawing_view_for_background ? 1 : 7;
subframe_scale = 1.0/35.0;
for(int subframe = 0;subframe<num_subframes;++subframe)
{
// draw the view
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[6]);
{
GLenum buffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(sizeof(buffers) / sizeof(buffers[0]), buffers);
}
glDisable(GL_BLEND);
drawView(time + subframe_scale * float(subframe) / float(num_subframes));
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[3]);
mb_accum_shader.bind();
mb_accum_shader.uniform1f("time", float(subframe) / float(num_subframes));
mb_accum_shader.uniform1f("scale", 1.0f / float(num_subframes));
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texs[6]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
CHECK_FOR_ERRORS;
if(drawing_view_for_background)
{
// ----- aperture ------
const float CoC = 0.02;// + sin(time) * 0.05;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bokeh_temp_fbo);
{
GLenum buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(sizeof(buffers) / sizeof(buffers[0]), buffers);
}
glViewport(0, 0, window_width / 2, window_height / 2);
bokeh_shader.bind();
bokeh_shader.uniform2f("CoC", CoC / aspect_ratio, CoC);
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texs[2]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
CHECK_FOR_ERRORS;
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[0]);
glViewport(0, 0, window_width, window_height);
{
GLenum buffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(sizeof(buffers) / sizeof(buffers[0]), buffers);
}
bokeh2_shader.bind();
bokeh2_shader.uniform2f("CoC", CoC / aspect_ratio, CoC);
bokeh2_shader.uniform1f("brightness", 0.2);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, bokeh_temp_tex_2);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, bokeh_temp_tex_1);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
else
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[0]);
glViewport(0, 0, window_width, window_height);
glDisable(GL_BLEND);
//glEnable(GL_BLEND);
//glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
bgfg_shader.bind();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texs[2]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texs[0]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
//glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]);
//glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[0]);
//glViewport(0, 0, window_width, window_height);
//glBlitFramebuffer(0, 0, window_width, window_height, 0, 0, window_width, window_height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
CHECK_FOR_ERRORS;
}
// ----- bloom ------
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
downsample8x(texs[0], fbos[3], texs[2], fbos[4], window_width, window_height);
gaussianBlur(1, 1, 1, 0.5, 0.5, fbos[5], fbos[9], texs[4], texs[5]);
gaussianBlur(1, 1, 1, 0.1, 0.1, fbos[5], fbos[4], texs[4], texs[5]);
CHECK_FOR_ERRORS;
// ----- composite ------
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, window_width, window_height);
composite_shader.bind();
composite_shader.uniform1f("time", time);
composite_shader.uniform1i("frame_num", frame_num);
composite_shader.uniform4f("tint", 1, 1, 1, 1);
{
float s=std::pow(1.0f-clamp(time,0.0f,1.0f),2.0f);
composite_shader.uniform3f("addcolour", s,s,s);
}
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_2D, texs[9]);
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, texs[4]);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, texs[13]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, noise_tex_2d);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texs[0]);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, coords);
glDrawRangeElements(GL_TRIANGLE_STRIP, 0, 3, 4, GL_UNSIGNED_BYTE, indices);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
CHECK_FOR_ERRORS;
}
void FrostScene::free()
{
glDeleteTextures(num_texs, texs);
glDeleteFramebuffers(num_fbos, fbos);
}
| [
"kusmabite@gmail.com"
] | kusmabite@gmail.com |
ac1de68c85d875004f51e2f790f87d90d4196a49 | 52ae54922e083863b0e1265e97d1d60e5bf22120 | /demos/demo_tileimage/demo_tileimage.cpp | dd4c470c8774183360ce3966a6d841b596fe76cb | [
"BSD-3-Clause"
] | permissive | borisblizzard/aprilui | e3d3014ca7e571e3241ed77a8f41bd56489ee727 | 88520e16ee24a15572c6e1f1b36eead2036997f2 | refs/heads/master | 2023-08-19T08:30:41.393829 | 2023-08-17T12:52:09 | 2023-08-17T12:52:09 | 219,540,570 | 0 | 0 | null | 2019-11-04T16:01:08 | 2019-11-04T16:01:08 | null | UTF-8 | C++ | false | false | 4,845 | cpp | /// @file
/// @version 6.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#ifndef __ANDROID__
#ifndef _UWP
#define RESOURCE_PATH "../../demos/media/"
#else
#define RESOURCE_PATH "media/"
#endif
#elif defined(__APPLE__)
#define RESOURCE_PATH "media/"
#else
#define RESOURCE_PATH "./"
#endif
#include <stdio.h>
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#endif
#define __APRIL_SINGLE_INSTANCE_NAME "demo_tileimage"
#include <april/april.h>
#include <april/Cursor.h>
#include <april/main.h>
#include <april/Platform.h>
#include <april/RenderSystem.h>
#include <april/UpdateDelegate.h>
#include <april/Window.h>
#include <aprilui/aprilui.h>
#include <aprilui/Dataset.h>
#include <aprilui/Objects.h>
#include <aprilui/TileImage.h>
#include <atres/atres.h>
#include <atres/Renderer.h>
#include <atres/atres.h>
#include <atresttf/atresttf.h>
#include <atresttf/FontTtf.h>
#include <gtypes/Vector2.h>
#define LOG_TAG "demo_tileimage"
#define SCROLL_SPEED gvec2f(50.0f, -50.0f)
grectf drawRect(0.0f, 0.0f, 800.0f, 600.0f);
grectf viewport = drawRect;
april::Cursor* cursor = NULL;
aprilui::Dataset* dataset = NULL;
class UpdateDelegate : public april::UpdateDelegate
{
public:
bool onUpdate(float timeDelta) override
{
april::rendersys->clear();
aprilui::updateViewports(drawRect, viewport);
aprilui::updateCursorPosition();
aprilui::processEvents();
aprilui::TileImage* image = (aprilui::TileImage*)dataset->getImage("texture/tile");
image->setScroll(image->getScroll() + SCROLL_SPEED * timeDelta); // manual scrolling
dataset->draw();
dataset->update(timeDelta);
return true;
}
};
static UpdateDelegate* updateDelegate = NULL;
void __aprilApplicationInit()
{
#ifdef __APPLE__
// On MacOSX, the current working directory is not set by
// the Finder, since you are expected to use Core Foundation
// or ObjC APIs to find files.
// So, when porting you probably want to set the current working
// directory to something sane (e.g. .../Resources/ in the app
// bundle).
// In this case, we set it to parent of the .app bundle.
{ // curly braces in order to localize variables
CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
// let's hope chdir() will be happy with utf8 encoding
const char* cpath = CFStringGetCStringPtr(path, kCFStringEncodingUTF8);
char* cpath_alloc = NULL;
if (cpath == NULL)
{
// CFStringGetCStringPtr is allowed to return NULL. bummer.
// we need to use CFStringGetCString instead.
cpath_alloc = (char*)malloc(CFStringGetLength(path) + 1);
CFStringGetCString(path, cpath_alloc, CFStringGetLength(path) + 1, kCFStringEncodingUTF8);
}
else
{
// even though it didn't return NULL, we still want to slice off bundle name.
cpath_alloc = (char*)malloc(CFStringGetLength(path) + 1);
strcpy(cpath_alloc, cpath);
}
// just in case / is appended to .app path for some reason
if (cpath_alloc[CFStringGetLength(path) - 1] == '/')
{
cpath_alloc[CFStringGetLength(path) - 1] = 0;
}
// replace pre-.app / with a null character, thus
// cutting off .app's name and getting parent of .app.
strrchr(cpath_alloc, '/')[0] = 0;
// change current dir using posix api
chdir(cpath_alloc);
free(cpath_alloc); // even if null, still ok
CFRelease(path);
CFRelease(url);
}
#endif
updateDelegate = new UpdateDelegate();
try
{
hlog::setLevelDebug(true);
#if defined(__ANDROID__) || defined(_IOS)
drawRect.setSize(april::getSystemInfo().displayResolution);
#endif
april::init(april::RenderSystemType::Default, april::WindowType::Default);
april::createRenderSystem();
april::createWindow((int)drawRect.w, (int)drawRect.h, false, "demo_tileimage");
atres::init();
atresttf::init();
aprilui::init();
#ifdef _UWP
april::window->setParam("cursor_mappings", "101 " RESOURCE_PATH "cursor\n102 " RESOURCE_PATH "simple");
#endif
april::window->setUpdateDelegate(updateDelegate);
cursor = april::window->createCursorFromResource(RESOURCE_PATH "cursor");
april::window->setCursor(cursor);
aprilui::setViewport(viewport);
aprilui::setLocalization("en");
dataset = new aprilui::Dataset(RESOURCE_PATH "demo_tileimage.dts");
dataset->load();
}
catch (hexception& e)
{
hlog::error(LOG_TAG, e.getMessage().cStr());
}
}
void __aprilApplicationDestroy()
{
try
{
april::window->setCursor(NULL);
april::window->destroyCursor(cursor);
delete dataset;
aprilui::destroy();
atresttf::destroy();
atres::destroy();
april::destroy();
}
catch (hexception& e)
{
hlog::error(LOG_TAG, e.getMessage().cStr());
}
delete updateDelegate;
updateDelegate = NULL;
}
| [
"boris.blizzard@gmail.com"
] | boris.blizzard@gmail.com |
ade8ae1c91f2b6460d28ee32e820cd9600bdf7bd | fd5596cc45f0972da19e3b79fc2329026cd3c085 | /掌握金钱/SetPos.cpp | c98bb2229d04d7d068b2badb983dfe8bee4e4cd8 | [] | no_license | VinsentY/Mastery-of-money | 9fadcdc6a0d0844278b0c2abae34d7f915fd20c6 | 465715f1bb616a7905d312df04e39f37157dcc15 | refs/heads/master | 2020-03-26T03:35:08.788701 | 2018-08-12T11:49:40 | 2018-08-12T11:49:40 | 142,649,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | cpp | #include "main.h"
void SetPos(int x,int y)
{
COORD pos;
HANDLE handle;
pos.X=x;
pos.Y=y;
handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(handle,pos);
} | [
"Yikai@outlool.com"
] | Yikai@outlool.com |
ed65defdc9580c8fb061bbfe523312da1f455d82 | 8c10c441660c03dec7481610c0ba325db1245c97 | /src/walletdb.cpp | e3e5f441253ad4ce52d5088133f3905dea1706e6 | [
"MIT"
] | permissive | NodeCash/NodeCash-Core | 74bb74498c8b8ba7bf1bdc5063a6bf77e0fe5a4e | b9b312c12e0c8ca8190cde73efb08d61151ec74c | refs/heads/master | 2020-03-20T07:41:05.233375 | 2018-06-14T01:47:50 | 2018-06-14T01:47:50 | 136,683,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,640 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "base58.h"
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
using namespace boost;
static uint64_t nAccountingEntryNumber = 0;
extern bool fWalletUnlockStakingOnly;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("tx"), hash), wtx);
}
bool CWalletDB::EraseTx(uint256 hash)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CWalletDB::WriteStealthKeyMeta(const CKeyID& keyId, const CStealthKeyMetadata& sxKeyMeta)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("sxKeyMeta"), keyId), sxKeyMeta, true);
}
bool CWalletDB::EraseStealthKeyMeta(const CKeyID& keyId)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("sxKeyMeta"), keyId));
}
bool CWalletDB::WriteStealthAddress(const CStealthAddress& sxAddr)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("sxAddr"), sxAddr.scan_pubkey), sxAddr, true);
}
bool CWalletDB::ReadStealthAddress(CStealthAddress& sxAddr)
{
// -- set scan_pubkey before reading
return Read(std::make_pair(std::string("sxAddr"), sxAddr.scan_pubkey), sxAddr);
}
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta, false))
return false;
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
const bool fEraseUnencryptedKey = true;
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta))
return false;
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
return false;
if (fEraseUnencryptedKey)
{
Erase(std::make_pair(std::string("key"), vchPubKey));
Erase(std::make_pair(std::string("wkey"), vchPubKey));
}
return true;
}
bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
bool CWalletDB::WriteWatchOnly(const CScript &dest)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("watchs"), dest), '1');
}
bool CWalletDB::EraseWatchOnly(const CScript &dest)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("watchs"), dest));
}
bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
return Write(std::string("bestblock"), locator);
}
bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
{
return Read(std::string("bestblock"), locator);
}
bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
{
nWalletDBUpdated++;
return Write(std::string("orderposnext"), nOrderPosNext);
}
bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
{
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::ErasePool(int64_t nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
bool CWalletDB::WriteMinVersion(int nVersion)
{
return Write(std::string("minversion"), nVersion);
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
}
bool CWalletDB::WriteAccountingEntry_Backend(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64_t nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors
CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CNodeCashAddress(strAddress).Get()];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
if (!(wtx.CheckTransaction() && (wtx.GetHash() == hash)))
return false;
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
pwallet->AddToWallet(wtx, true);
//// debug print
//LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString());
//LogPrintf(" %12d %s %s %s\n",
// wtx.vout[0].nValue,
// DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()),
// wtx.hashBlock.ToString(),
// wtx.mapValue["message"]);
}
else if (strType == "sxAddr")
{
if (fDebug)
printf("WalletDB ReadKeyValue sxAddr\n");
CStealthAddress sxAddr;
ssValue >> sxAddr;
pwallet->stealthAddresses.insert(sxAddr);
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "watchs")
{
CScript script;
ssKey >> script;
char fYes;
ssValue >> fYes;
if (fYes == '1')
pwallet->LoadWatchOnly(script);
// Watch-only addresses have no birthday information for now,
// so set the wallet birthday to the beginning of time.
pwallet->nTimeFirstKey = 1;
}
else if (strType == "key" || strType == "wkey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash = 0;
if (strType == "key")
{
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try
{
ssValue >> hash;
}
catch(...){}
bool fSkipCheck = false;
if (hash != 0)
{
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash)
{
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
wss.nCKeys++;
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
}
else if (strType == "sxKeyMeta")
{
if (fDebug)
printf("WalletDB ReadKeyValue sxKeyMeta\n");
CKeyID keyId;
ssKey >> keyId;
CStealthKeyMetadata sxKeyMeta;
ssValue >> sxKeyMeta;
pwallet->mapStealthKeyMeta[keyId] = sxKeyMeta;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
} catch (...)
{
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
}
catch (boost::thread_interrupted) {
throw;
}
catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
pwallet->laccentries.clear();
ListAccountCreditDebit("*", pwallet->laccentries);
BOOST_FOREACH(CAccountingEntry& entry, pwallet->laccentries) {
pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair((CWalletTx*)0, &entry)));
}
return result;
}
void ThreadFlushWalletDB(const string& strFile)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("nodecash-wallet");
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (true)
{
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
LogPrint("db", "Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (true)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch(const filesystem::filesystem_error &e) {
LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%d.bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
{
if (fOnlyKeys)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
if (!IsKeyType(strType))
continue;
if (!fReadOK)
{
LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
delete pdbCopy;
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
| [
"team@nodecash.org"
] | team@nodecash.org |
7ba061d5ad101d3b9ccdcc0947008cb337b41d6a | b2527b0256448bba1795c3b3c766089b9e818c11 | /training/2015.8.5/DD.cpp | 110c544cb15336c6dfc6b4d408f1799b6f7da9ec | [] | no_license | zxok365/melody-of-canon | 0befe10647f2db88d852a2a9c7157578fea44e55 | 646b2df65cdeaa5aca28759dc0db4e1348b80a71 | refs/heads/master | 2016-09-16T17:03:47.020659 | 2016-03-29T12:13:46 | 2016-03-29T12:13:46 | 40,532,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstring>
using namespace std;
const double eps = 1e-8;
const int maxn = 1000;
const int maxf = maxn * 10;
inline int Sign(double a) {
return a < -eps ? -1 : a > eps;
}
inline double Sqrt(double a) {
return a <= 0 ? 0 :sqrt(a);
}
inline double Sqr(double a){
return a * a;
}
struct Point}{
double x, y ,;
Point(){
}
Point (double x, double y, double z) : x(x), y(y), z(z){
}
void Input(){
scanf("%lf %lf %lf", &x, &y, &z);
}
}
| [
"zxjszy@126.com"
] | zxjszy@126.com |
5b104de0ba016fd0eaebb2f01ac8d69d88c39fd9 | 210d757836216b1a1d491564ef9c7e6d84ee947e | /library/cuckoo/src/mean_miner.hpp | b056b8066107c8e405580cdb5aee9397ec2e4681 | [
"MIT",
"GPL-2.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later"
] | permissive | sunnymiesta/adina | 85a77ed48795cdd67793b645db9f9958b59ed361 | 5b77f6248ef1cb75bd0451b1e4884c5f2c89ecee | refs/heads/master | 2020-03-19T15:56:02.554698 | 2018-06-11T04:10:43 | 2018-06-11T04:10:43 | 136,007,337 | 0 | 0 | MIT | 2018-06-04T21:54:24 | 2018-06-04T10:10:26 | C++ | UTF-8 | C++ | false | false | 52,957 | hpp | // Cuckoo Cycle, a memory-hard proof-of-work
// Copyright (c) 2013-2018 John Tromp
// The edge-trimming memory optimization is due to Dave Andersen
// http://da-data.blogspot.com/2014/03/a-public-review-of-cuckoo-cycle.html
// xenoncat demonstrated at https://github.com/xenoncat/cuckoo_pow
// how bucket sorting avoids random memory access latency
// my own cycle finding is run single threaded to avoid losing cycles
// to race conditions (typically takes under 1% of runtime)
#include "cuckoo.h"
#include "siphashxN.h"
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <x86intrin.h>
#include <assert.h>
#include <vector>
#include <bitset>
#ifdef __APPLE__
#include "osx_barrier.h"
#endif
// algorithm/performance parameters
// EDGEBITS/NEDGES/EDGEMASK defined in cuckoo.h
// The node bits are logically split into 3 groups:
// XBITS 'X' bits (most significant), YBITS 'Y' bits, and ZBITS 'Z' bits (least significant)
// Here we have the default XBITS=YBITS=7, ZBITS=15 summing to EDGEBITS=29
// nodebits XXXXXXX YYYYYYY ZZZZZZZZZZZZZZZ
// bit%10 8765432 1098765 432109876543210
// bit/10 2222222 2111111 111110000000000
// The matrix solver stores all edges in a matrix of NX * NX buckets,
// where NX = 2^XBITS is the number of possible values of the 'X' bits.
// Edge i between nodes ui = siphash24(2*i) and vi = siphash24(2*i+1)
// resides in the bucket at (uiX,viX)
// In each trimming round, either a matrix row or a matrix column (NX buckets)
// is bucket sorted on uY or vY respectively, and then within each bucket
// uZ or vZ values are counted and edges with a count of only one are eliminated,
// while remaining edges are bucket sorted back on vX or uX respectively.
// When sufficiently many edges have been eliminated, a pair of compression
// rounds remap surviving Y,Z values in each row or column into 15 bit
// combined YZ values, allowing the remaining rounds to avoid the sorting on Y,
// and directly count YZ values in a cache friendly 32KB.
// A final pair of compression rounds remap YZ values from 15 into 11 bits.
#ifndef XBITS
// 7 seems to give best performance
#define XBITS 7
#endif
#define YBITS XBITS
// size in bytes of a big bucket entry
#ifndef BIGSIZE
#if EDGEBITS <= 15
#define BIGSIZE 4
// no compression needed
#define COMPRESSROUND 0
#else
#define BIGSIZE 5
// YZ compression round; must be even
#ifndef COMPRESSROUND
#define COMPRESSROUND 14
#endif
#endif
#endif
// size in bytes of a small bucket entry
#define SMALLSIZE BIGSIZE
// initial entries could be smaller at percent or two slowdown
#ifndef BIGSIZE0
#if EDGEBITS < 30 && !defined SAVEEDGES
#define BIGSIZE0 4
#else
#define BIGSIZE0 BIGSIZE
#endif
#endif
// but they may need syncing entries
#if BIGSIZE0 == 4 && EDGEBITS > 27
#define NEEDSYNC
#endif
typedef uint8_t u8;
typedef uint16_t u16;
#if EDGEBITS >= 30
typedef u64 offset_t;
#else
typedef u32 offset_t;
#endif
#if BIGSIZE0 > 4
typedef u64 BIGTYPE0;
#else
typedef u32 BIGTYPE0;
#endif
// node bits have two groups of bucketbits (X for big and Y for small) and a remaining group Z of degree bits
const static u32 NX = 1 << XBITS;
const static u32 XMASK = NX - 1;
const static u32 NY = 1 << YBITS;
const static u32 YMASK = NY - 1;
const static u32 XYBITS = XBITS + YBITS;
const static u32 NXY = 1 << XYBITS;
const static u32 ZBITS = EDGEBITS - XYBITS;
const static u32 NZ = 1 << ZBITS;
const static u32 ZMASK = NZ - 1;
const static u32 YZBITS = EDGEBITS - XBITS;
const static u32 NYZ = 1 << YZBITS;
const static u32 YZMASK = NYZ - 1;
const static u32 YZ1BITS = YZBITS < 15 ? YZBITS : 15; // compressed YZ bits
const static u32 NYZ1 = 1 << YZ1BITS;
const static u32 YZ1MASK = NYZ1 - 1;
const static u32 Z1BITS = YZ1BITS - YBITS;
const static u32 NZ1 = 1 << Z1BITS;
const static u32 Z1MASK = NZ1 - 1;
const static u32 YZ2BITS = YZBITS < 11 ? YZBITS : 11; // more compressed YZ bits
const static u32 NYZ2 = 1 << YZ2BITS;
const static u32 YZ2MASK = NYZ2 - 1;
const static u32 Z2BITS = YZ2BITS - YBITS;
const static u32 NZ2 = 1 << Z2BITS;
const static u32 Z2MASK = NZ2 - 1;
const static u32 YZZBITS = YZBITS + ZBITS;
const static u32 YZZ1BITS = YZ1BITS + ZBITS;
const static u32 BIGSLOTBITS = BIGSIZE * 8;
const static u32 SMALLSLOTBITS = SMALLSIZE * 8;
const static u64 BIGSLOTMASK = (1ULL << BIGSLOTBITS) - 1ULL;
const static u64 SMALLSLOTMASK = (1ULL << SMALLSLOTBITS) - 1ULL;
const static u32 BIGSLOTBITS0 = BIGSIZE0 * 8;
const static u64 BIGSLOTMASK0 = (1ULL << BIGSLOTBITS0) - 1ULL;
const static u32 NONYZBITS = BIGSLOTBITS0 - YZBITS;
const static u32 NNONYZ = 1 << NONYZBITS;
// for p close to 0, Pr(X>=k) < e^{-n*p*eps^2} where k=n*p*(1+eps)
// see https://en.wikipedia.org/wiki/Binomial_distribution#Tail_bounds
// eps should be at least 1/sqrt(n*p/64)
// to give negligible bad odds of e^-64.
// 1/32 reduces odds of overflowing z bucket on 2^30 nodes to 2^14*e^-32
// (less than 1 in a billion) in theory. not so in practice (fails first at mean30 -n 1549)
#ifndef BIGEPS
#define BIGEPS 3/64
#endif
// 176/256 is safely over 1-e(-1) ~ 0.63 trimming fraction
#ifndef TRIMFRAC256
#define TRIMFRAC256 176
#endif
const static u32 NTRIMMEDZ = NZ * TRIMFRAC256 / 256;
const static u32 ZBUCKETSLOTS = NZ + NZ * BIGEPS;
#ifdef SAVEEDGES
const static u32 ZBUCKETSIZE = NTRIMMEDZ * (BIGSIZE + sizeof(u32)); // assumes EDGEBITS <= 32
#else
const static u32 ZBUCKETSIZE = ZBUCKETSLOTS * BIGSIZE0;
#endif
const static u32 TBUCKETSIZE = ZBUCKETSLOTS * BIGSIZE;
/*
// make 128 byte waves
#ifndef WAVESIZE
#define WAVESIZE 25
#endif
struct wave {
u32 words[WAVESIZE];
u8 bytes[WAVESIZE];
}*/;
template<u32 BUCKETSIZE>
struct zbucket {
u32 size;
const static u32 RENAMESIZE = 2*NZ2 + 2*(COMPRESSROUND ? NZ1 : 0);
union alignas(16) {
u8 bytes[BUCKETSIZE];
// wave waves[BUCKETSIZE/sizeof(wave)];
struct {
#ifdef SAVEEDGES
u32 words[BUCKETSIZE/sizeof(u32) - RENAMESIZE - NTRIMMEDZ];
#else
u32 words[BUCKETSIZE/sizeof(u32) - RENAMESIZE];
#endif
u32 renameu1[NZ2];
u32 renamev1[NZ2];
u32 renameu[COMPRESSROUND ? NZ1 : 0];
u32 renamev[COMPRESSROUND ? NZ1 : 0];
#ifdef SAVEEDGES
u32 edges[NTRIMMEDZ];
#endif
};
};
u32 setsize(u8 const *end) {
size = end - bytes;
assert(size <= BUCKETSIZE);
return size;
}
};
template<u32 BUCKETSIZE>
using yzbucket = zbucket<BUCKETSIZE>[NY];
template <u32 BUCKETSIZE>
using matrix = yzbucket<BUCKETSIZE>[NX];
template<u32 BUCKETSIZE>
struct indexer {
offset_t index[NX];
void matrixv(const u32 y) {
const yzbucket<BUCKETSIZE> *foo = 0;
for (u32 x = 0; x < NX; x++)
index[x] = foo[x][y].bytes - (u8 *)foo;
}
offset_t storev(yzbucket<BUCKETSIZE> *buckets, const u32 y) {
u8 const *base = (u8 *)buckets;
offset_t sumsize = 0;
for (u32 x = 0; x < NX; x++)
sumsize += buckets[x][y].setsize(base+index[x]);
return sumsize;
}
void matrixu(const u32 x) {
const yzbucket<BUCKETSIZE> *foo = 0;
for (u32 y = 0; y < NY; y++)
index[y] = foo[x][y].bytes - (u8 *)foo;
}
offset_t storeu(yzbucket<BUCKETSIZE> *buckets, const u32 x) {
u8 const *base = (u8 *)buckets;
offset_t sumsize = 0;
for (u32 y = 0; y < NY; y++)
sumsize += buckets[x][y].setsize(base+index[y]);
return sumsize;
}
};
#define likely(x) __builtin_expect((x)!=0, 1)
#define unlikely(x) __builtin_expect((x), 0)
class edgetrimmer; // avoid circular references
typedef struct {
u32 id;
pthread_t thread;
edgetrimmer *et;
} thread_ctx;
typedef u8 zbucket8[2*NYZ1];
typedef u16 zbucket16[NTRIMMEDZ];
typedef u32 zbucket32[NTRIMMEDZ];
// maintains set of trimmable edges
class edgetrimmer {
public:
siphash_keys sip_keys;
yzbucket<ZBUCKETSIZE> *buckets;
yzbucket<TBUCKETSIZE> *tbuckets;
zbucket32 *tedges;
zbucket16 *tzs;
zbucket8 *tdegs;
offset_t *tcounts;
u32 ntrims;
u32 nthreads;
bool showall;
pthread_barrier_t barry;
#if NSIPHASH > 4
void* operator new(size_t size) noexcept {
void* newobj;
int tmp = posix_memalign(&newobj, NSIPHASH * sizeof(u32), sizeof(edgetrimmer));
if (tmp != 0) {
return nullptr;
}
return newobj;
}
#endif
void touch(u8 *p, const offset_t n) {
for (offset_t i=0; i<n; i+=4096)
*(u32 *)(p+i) = 0;
}
edgetrimmer(const u32 n_threads, const u32 n_trims, const bool show_all) {
assert(sizeof(matrix<ZBUCKETSIZE>) == NX * sizeof(yzbucket<ZBUCKETSIZE>));
assert(sizeof(matrix<TBUCKETSIZE>) == NX * sizeof(yzbucket<TBUCKETSIZE>));
nthreads = n_threads;
ntrims = n_trims;
showall = show_all;
buckets = new yzbucket<ZBUCKETSIZE>[NX];
touch((u8 *)buckets, sizeof(matrix<ZBUCKETSIZE>));
tbuckets = new yzbucket<TBUCKETSIZE>[nthreads];
touch((u8 *)tbuckets, nthreads * sizeof(yzbucket<TBUCKETSIZE>));
#ifdef SAVEEDGES
tedges = 0;
#else
tedges = new zbucket32[nthreads];
#endif
tdegs = new zbucket8[nthreads];
tzs = new zbucket16[nthreads];
tcounts = new offset_t[nthreads];
int err = pthread_barrier_init(&barry, NULL, nthreads);
assert(err == 0);
}
~edgetrimmer() {
delete[] buckets;
delete[] tbuckets;
delete[] tedges;
delete[] tdegs;
delete[] tzs;
delete[] tcounts;
}
offset_t count() const {
offset_t cnt = 0;
for (u32 t = 0; t < nthreads; t++)
cnt += tcounts[t];
return cnt;
}
void genUnodes(const u32 id, const u32 uorv) {
u64 rdtsc0, rdtsc1;
#ifdef NEEDSYNC
u32 last[NX];;
#endif
rdtsc0 = __rdtsc();
u8 const *base = (u8 *)buckets;
indexer<ZBUCKETSIZE> dst;
const u32 starty = NY * id / nthreads;
const u32 endy = NY * (id+1) / nthreads;
u32 edge = starty << YZBITS, endedge = edge + NYZ;
#if NSIPHASH == 4
static const __m128i vxmask = {XMASK, XMASK};
static const __m128i vyzmask = {YZMASK, YZMASK};
__m128i v0, v1, v2, v3, v4, v5, v6, v7;
const u32 e2 = 2 * edge + uorv;
__m128i vpacket0 = _mm_set_epi64x(e2+2, e2+0);
__m128i vpacket1 = _mm_set_epi64x(e2+6, e2+4);
static const __m128i vpacketinc = {8, 8};
u64 e1 = edge;
__m128i vhi0 = _mm_set_epi64x((e1+1)<<YZBITS, (e1+0)<<YZBITS);
__m128i vhi1 = _mm_set_epi64x((e1+3)<<YZBITS, (e1+2)<<YZBITS);
static const __m128i vhiinc = {4<<YZBITS, 4<<YZBITS};
#elif NSIPHASH == 8
static const __m256i vxmask = {XMASK, XMASK, XMASK, XMASK};
static const __m256i vyzmask = {YZMASK, YZMASK, YZMASK, YZMASK};
const __m256i vinit = _mm256_load_si256((__m256i *)&sip_keys);
__m256i v0, v1, v2, v3, v4, v5, v6, v7;
const u32 e2 = 2 * edge + uorv;
__m256i vpacket0 = _mm256_set_epi64x(e2+6, e2+4, e2+2, e2+0);
__m256i vpacket1 = _mm256_set_epi64x(e2+14, e2+12, e2+10, e2+8);
static const __m256i vpacketinc = {16, 16, 16, 16};
u64 e1 = edge;
__m256i vhi0 = _mm256_set_epi64x((e1+3)<<YZBITS, (e1+2)<<YZBITS, (e1+1)<<YZBITS, (e1+0)<<YZBITS);
__m256i vhi1 = _mm256_set_epi64x((e1+7)<<YZBITS, (e1+6)<<YZBITS, (e1+5)<<YZBITS, (e1+4)<<YZBITS);
static const __m256i vhiinc = {8<<YZBITS, 8<<YZBITS, 8<<YZBITS, 8<<YZBITS};
#endif
offset_t sumsize = 0;
for (u32 my = starty; my < endy; my++, endedge += NYZ) {
dst.matrixv(my);
#ifdef NEEDSYNC
for (u32 x=0; x < NX; x++)
last[x] = edge;
#endif
for (; edge < endedge; edge += NSIPHASH) {
// bit 28..21 20..13 12..0
// node XXXXXX YYYYYY ZZZZZ
#if NSIPHASH == 1
const u32 node = sipnode(&sip_keys, edge, uorv);
const u32 ux = node >> YZBITS;
const BIGTYPE0 zz = (BIGTYPE0)edge << YZBITS | (node & YZMASK);
#ifndef NEEDSYNC
// bit 39..21 20..13 12..0
// write edge YYYYYY ZZZZZ
*(BIGTYPE0 *)(base+dst.index[ux]) = zz;
dst.index[ux] += BIGSIZE0;
#else
if (zz) {
for (; unlikely(last[ux] + NNONYZ <= edge); last[ux] += NNONYZ, dst.index[ux] += BIGSIZE0)
*(u32 *)(base+dst.index[ux]) = 0;
*(u32 *)(base+dst.index[ux]) = zz;
dst.index[ux] += BIGSIZE0;
last[ux] = edge;
}
#endif
#elif NSIPHASH == 4
v7 = v3 = _mm_set1_epi64x(sip_keys.k3);
v4 = v0 = _mm_set1_epi64x(sip_keys.k0);
v5 = v1 = _mm_set1_epi64x(sip_keys.k1);
v6 = v2 = _mm_set1_epi64x(sip_keys.k2);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2, _mm_set1_epi64x(0xffLL));
v6 = XOR(v6, _mm_set1_epi64x(0xffLL));
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
vpacket0 = _mm_add_epi64(vpacket0, vpacketinc);
vpacket1 = _mm_add_epi64(vpacket1, vpacketinc);
v1 = _mm_srli_epi64(v0, YZBITS) & vxmask;
v5 = _mm_srli_epi64(v4, YZBITS) & vxmask;
v0 = (v0 & vyzmask) | vhi0;
v4 = (v4 & vyzmask) | vhi1;
vhi0 = _mm_add_epi64(vhi0, vhiinc);
vhi1 = _mm_add_epi64(vhi1, vhiinc);
u32 ux;
#ifndef __SSE41__
#define extract32(x, imm) _mm_cvtsi128_si32(_mm_srli_si128((x), 4 * (imm)))
#else
#define extract32(x, imm) _mm_extract_epi32(x, imm)
#endif
#ifndef NEEDSYNC
#define STORE0(i,v,x,w) \
ux = extract32(v,x);\
*(u64 *)(base+dst.index[ux]) = _mm_extract_epi64(w,i%2);\
dst.index[ux] += BIGSIZE0;
#else
u32 zz;
#define STORE0(i,v,x,w) \
zz = extract32(w,x);\
if (i || likely(zz)) {\
ux = extract32(v,x);\
for (; unlikely(last[ux] + NNONYZ <= edge+i); last[ux] += NNONYZ, dst.index[ux] += BIGSIZE0)\
*(u32 *)(base+dst.index[ux]) = 0;\
*(u32 *)(base+dst.index[ux]) = zz;\
dst.index[ux] += BIGSIZE0;\
last[ux] = edge+i;\
}
#endif
STORE0(0,v1,0,v0); STORE0(1,v1,2,v0);
STORE0(2,v5,0,v4); STORE0(3,v5,2,v4);
#elif NSIPHASH == 8
v7 = v3 = _mm256_permute4x64_epi64(vinit, 0xFF);
v4 = v0 = _mm256_permute4x64_epi64(vinit, 0x00);
v5 = v1 = _mm256_permute4x64_epi64(vinit, 0x55);
v6 = v2 = _mm256_permute4x64_epi64(vinit, 0xAA);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2,_mm256_set1_epi64x(0xffLL));
v6 = XOR(v6,_mm256_set1_epi64x(0xffLL));
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
vpacket0 = _mm256_add_epi64(vpacket0, vpacketinc);
vpacket1 = _mm256_add_epi64(vpacket1, vpacketinc);
v1 = _mm256_srli_epi64(v0, YZBITS) & vxmask;
v5 = _mm256_srli_epi64(v4, YZBITS) & vxmask;
v0 = (v0 & vyzmask) | vhi0;
v4 = (v4 & vyzmask) | vhi1;
vhi0 = _mm256_add_epi64(vhi0, vhiinc);
vhi1 = _mm256_add_epi64(vhi1, vhiinc);
u32 ux;
#ifndef NEEDSYNC
#define STORE0(i,v,x,w) \
ux = _mm256_extract_epi32(v,x);\
*(u64 *)(base+dst.index[ux]) = _mm256_extract_epi64(w,i%4);\
dst.index[ux] += BIGSIZE0;
#else
u32 zz;
#define STORE0(i,v,x,w) \
zz = _mm256_extract_epi32(w,x);\
if (i || likely(zz)) {\
ux = _mm256_extract_epi32(v,x);\
for (; unlikely(last[ux] + NNONYZ <= edge+i); last[ux] += NNONYZ, dst.index[ux] += BIGSIZE0)\
*(u32 *)(base+dst.index[ux]) = 0;\
*(u32 *)(base+dst.index[ux]) = zz;\
dst.index[ux] += BIGSIZE0;\
last[ux] = edge+i;\
}
#endif
STORE0(0,v1,0,v0); STORE0(1,v1,2,v0); STORE0(2,v1,4,v0); STORE0(3,v1,6,v0);
STORE0(4,v5,0,v4); STORE0(5,v5,2,v4); STORE0(6,v5,4,v4); STORE0(7,v5,6,v4);
#else
#error not implemented
#endif
}
#ifdef NEEDSYNC
for (u32 ux=0; ux < NX; ux++) {
for (; last[ux]<endedge-NNONYZ; last[ux]+=NNONYZ) {
*(u32 *)(base+dst.index[ux]) = 0;
dst.index[ux] += BIGSIZE0;
}
}
#endif
sumsize += dst.storev(buckets, my);
}
rdtsc1 = __rdtsc();
if (!id) printf("genUnodes round %2d size %u rdtsc: %lu\n", uorv, sumsize/BIGSIZE0, rdtsc1-rdtsc0);
tcounts[id] = sumsize/BIGSIZE0;
}
void genVnodes(const u32 id, const u32 uorv) {
u64 rdtsc0, rdtsc1;
#if NSIPHASH == 4
static const __m128i vxmask = {XMASK, XMASK};
static const __m128i vyzmask = {YZMASK, YZMASK};
const __m128i ff = _mm_set1_epi64x(0xffLL);
__m128i v0, v1, v2, v3, v4, v5, v6, v7;
__m128i vpacket0, vpacket1, vhi0, vhi1;
#elif NSIPHASH == 8
static const __m256i vxmask = {XMASK, XMASK, XMASK, XMASK};
static const __m256i vyzmask = {YZMASK, YZMASK, YZMASK, YZMASK};
const __m256i vinit = _mm256_load_si256((__m256i *)&sip_keys);
__m256i vpacket0, vpacket1, vhi0, vhi1;
__m256i v0, v1, v2, v3, v4, v5, v6, v7;
#endif
static const u32 NONDEGBITS = std::min(BIGSLOTBITS, 2 * YZBITS) - ZBITS;
static const u32 NONDEGMASK = (1 << NONDEGBITS) - 1;
indexer<ZBUCKETSIZE> dst;
indexer<TBUCKETSIZE> small;
rdtsc0 = __rdtsc();
offset_t sumsize = 0;
u8 const *base = (u8 *)buckets;
u8 const *small0 = (u8 *)tbuckets[id];
const u32 startux = NX * id / nthreads;
const u32 endux = NX * (id+1) / nthreads;
for (u32 ux = startux; ux < endux; ux++) { // matrix x == ux
small.matrixu(0);
for (u32 my = 0 ; my < NY; my++) {
u32 edge = my << YZBITS;
u8 *readbig = buckets[ux][my].bytes;
u8 const *endreadbig = readbig + buckets[ux][my].size;
// printf("id %d x %d y %d size %u read %d\n", id, ux, my, buckets[ux][my].size, readbig-base);
for (; readbig < endreadbig; readbig += BIGSIZE0) {
// bit 39/31..21 20..13 12..0
// read edge UYYYYY UZZZZ within UX partition
BIGTYPE0 e = *(BIGTYPE0 *)readbig;
#if BIGSIZE0 > 4
e &= BIGSLOTMASK0;
#elif defined NEEDSYNC
if (unlikely(!e)) { edge += NNONYZ; continue; }
#endif
edge += ((u32)(e >> YZBITS) - edge) & (NNONYZ-1);
// if (ux==78 && my==243) printf("id %d ux %d my %d e %08x prefedge %x edge %x\n", id, ux, my, e, e >> YZBITS, edge);
const u32 uy = (e >> ZBITS) & YMASK;
// bit 39..13 12..0
// write edge UZZZZ within UX UY partition
*(u64 *)(small0+small.index[uy]) = ((u64)edge << ZBITS) | (e & ZMASK);
// printf("id %d ux %d y %d e %010lx e' %010x\n", id, ux, my, e, ((u64)edge << ZBITS) | (e >> YBITS));
small.index[uy] += SMALLSIZE;
}
if (unlikely(edge >> NONYZBITS != (((my+1) << YZBITS) - 1) >> NONYZBITS))
{ printf("OOPS1: id %d ux %d y %d edge %x vs %x\n", id, ux, my, edge, ((my+1)<<YZBITS)-1); exit(0); }
}
u8 *degs = tdegs[id];
small.storeu(tbuckets+id, 0);
dst.matrixu(ux);
for (u32 uy = 0 ; uy < NY; uy++) {
memset(degs, 0xff, NZ);
u8 *readsmall = tbuckets[id][uy].bytes, *endreadsmall = readsmall + tbuckets[id][uy].size;
// if (id==1) printf("id %d ux %d y %d size %u sumsize %u\n", id, ux, uy, tbuckets[id][uy].size/BIGSIZE, sumsize);
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall+=SMALLSIZE)
degs[*(u32 *)rdsmall & ZMASK]++;
u16 *zs = tzs[id];
#ifdef SAVEEDGES
u32 *edges0 = buckets[ux][uy].edges;
#else
u32 *edges0 = tedges[id];
#endif
u32 *edges = edges0, edge = 0;
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall+=SMALLSIZE) {
// bit 39..13 12..0
// read edge UZZZZ sorted by UY within UX partition
const u64 e = *(u64 *)rdsmall;
edge += ((e >> ZBITS) - edge) & NONDEGMASK;
// if (id==0) printf("id %d ux %d uy %d e %010lx pref %4x edge %x mask %x\n", id, ux, uy, e, e>>ZBITS, edge, NONDEGMASK);
*edges = edge;
const u32 z = e & ZMASK;
*zs = z;
const u32 delta = degs[z] ? 1 : 0;
edges += delta;
zs += delta;
}
if (unlikely(edge >> NONDEGBITS != EDGEMASK >> NONDEGBITS))
{ printf("OOPS2: id %d ux %d uy %d edge %x vs %x\n", id, ux, uy, edge, EDGEMASK); exit(0); }
assert(edges - edges0 < NTRIMMEDZ);
const u16 *readz = tzs[id];
const u32 *readedge = edges0;
int64_t uy34 = (int64_t)uy << YZZBITS;
#if NSIPHASH == 4
const __m128i vuy34 = _mm_set1_epi64x(uy34);
const __m128i vuorv = _mm_set1_epi64x(uorv);
for (; readedge <= edges-NSIPHASH; readedge += NSIPHASH, readz += NSIPHASH) {
v4 = v0 = _mm_set1_epi64x(sip_keys.k0);
v5 = v1 = _mm_set1_epi64x(sip_keys.k1);
v6 = v2 = _mm_set1_epi64x(sip_keys.k2);
v7 = v3 = _mm_set1_epi64x(sip_keys.k3);
vpacket0 = _mm_slli_epi64(_mm_cvtepu32_epi64(*(__m128i*) readedge ), 1) | vuorv;
vhi0 = vuy34 | _mm_slli_epi64(_mm_cvtepu16_epi64(_mm_set_epi64x(0,*(u64*)readz)), YZBITS);
vpacket1 = _mm_slli_epi64(_mm_cvtepu32_epi64(*(__m128i*)(readedge + 2)), 1) | vuorv;
vhi1 = vuy34 | _mm_slli_epi64(_mm_cvtepu16_epi64(_mm_set_epi64x(0,*(u64*)(readz + 2))), YZBITS);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2,ff);
v6 = XOR(v6,ff);
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
v1 = _mm_srli_epi64(v0, YZBITS) & vxmask;
v5 = _mm_srli_epi64(v4, YZBITS) & vxmask;
v0 = vhi0 | (v0 & vyzmask);
v4 = vhi1 | (v4 & vyzmask);
u32 vx;
#define STORE(i,v,x,w) \
vx = extract32(v,x);\
*(u64 *)(base+dst.index[vx]) = _mm_extract_epi64(w,i%2);\
dst.index[vx] += BIGSIZE;
STORE(0,v1,0,v0); STORE(1,v1,2,v0);
STORE(2,v5,0,v4); STORE(3,v5,2,v4);
}
#elif NSIPHASH == 8
const __m256i vuy34 = {uy34, uy34, uy34, uy34};
const __m256i vuorv = {uorv, uorv, uorv, uorv};
for (; readedge <= edges-NSIPHASH; readedge += NSIPHASH, readz += NSIPHASH) {
v7 = v3 = _mm256_permute4x64_epi64(vinit, 0xFF);
v4 = v0 = _mm256_permute4x64_epi64(vinit, 0x00);
v5 = v1 = _mm256_permute4x64_epi64(vinit, 0x55);
v6 = v2 = _mm256_permute4x64_epi64(vinit, 0xAA);
vpacket0 = _mm256_slli_epi64(_mm256_cvtepu32_epi64(*(__m128i*) readedge ), 1) | vuorv;
vhi0 = vuy34 | _mm256_slli_epi64(_mm256_cvtepu16_epi64(_mm_set_epi64x(0,*(u64*)readz)), YZBITS);
vpacket1 = _mm256_slli_epi64(_mm256_cvtepu32_epi64(*(__m128i*)(readedge + 4)), 1) | vuorv;
vhi1 = vuy34 | _mm256_slli_epi64(_mm256_cvtepu16_epi64(_mm_set_epi64x(0,*(u64*)(readz + 4))), YZBITS);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2,_mm256_set1_epi64x(0xffLL));
v6 = XOR(v6,_mm256_set1_epi64x(0xffLL));
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
v1 = _mm256_srli_epi64(v0, YZBITS) & vxmask;
v5 = _mm256_srli_epi64(v4, YZBITS) & vxmask;
v0 = vhi0 | (v0 & vyzmask);
v4 = vhi1 | (v4 & vyzmask);
u32 vx;
#define STORE(i,v,x,w) \
vx = _mm256_extract_epi32(v,x);\
*(u64 *)(base+dst.index[vx]) = _mm256_extract_epi64(w,i%4);\
dst.index[vx] += BIGSIZE;
// printf("Id %d ux %d y %d edge %08x e' %010lx vx %d\n", id, ux, uy, readedge[i], _mm256_extract_epi64(w,i%4), vx);
STORE(0,v1,0,v0); STORE(1,v1,2,v0); STORE(2,v1,4,v0); STORE(3,v1,6,v0);
STORE(4,v5,0,v4); STORE(5,v5,2,v4); STORE(6,v5,4,v4); STORE(7,v5,6,v4);
}
#endif
for (; readedge < edges; readedge++, readz++) { // process up to 7 leftover edges if NSIPHASH==8
const u32 node = sipnode(&sip_keys, *readedge, uorv);
const u32 vx = node >> YZBITS; // & XMASK;
// bit 39..34 33..21 20..13 12..0
// write UYYYYY UZZZZZ VYYYYY VZZZZ within VX partition
*(u64 *)(base+dst.index[vx]) = uy34 | ((u64)*readz << YZBITS) | (node & YZMASK);
// printf("id %d ux %d y %d edge %08x e' %010lx vx %d\n", id, ux, uy, *readedge, uy34 | ((u64)(node & YZMASK) << ZBITS) | *readz, vx);
dst.index[vx] += BIGSIZE;
}
}
sumsize += dst.storeu(buckets, ux);
}
rdtsc1 = __rdtsc();
if (!id) printf("genVnodes round %2d size %u rdtsc: %lu\n", uorv, sumsize/BIGSIZE, rdtsc1-rdtsc0);
tcounts[id] = sumsize/BIGSIZE;
}
template <u32 SRCSIZE, u32 DSTSIZE, bool TRIMONV>
void trimedges(const u32 id, const u32 round) {
const u32 SRCSLOTBITS = std::min(SRCSIZE * 8, 2 * YZBITS);
const u64 SRCSLOTMASK = (1ULL << SRCSLOTBITS) - 1ULL;
const u32 SRCPREFBITS = SRCSLOTBITS - YZBITS;
const u32 SRCPREFMASK = (1 << SRCPREFBITS) - 1;
const u32 DSTSLOTBITS = std::min(DSTSIZE * 8, 2 * YZBITS);
const u64 DSTSLOTMASK = (1ULL << DSTSLOTBITS) - 1ULL;
const u32 DSTPREFBITS = DSTSLOTBITS - YZZBITS;
const u32 DSTPREFMASK = (1 << DSTPREFBITS) - 1;
u64 rdtsc0, rdtsc1;
indexer<ZBUCKETSIZE> dst;
indexer<TBUCKETSIZE> small;
rdtsc0 = __rdtsc();
offset_t sumsize = 0;
u8 const *base = (u8 *)buckets;
u8 const *small0 = (u8 *)tbuckets[id];
const u32 startvx = NY * id / nthreads;
const u32 endvx = NY * (id+1) / nthreads;
for (u32 vx = startvx; vx < endvx; vx++) {
small.matrixu(0);
for (u32 ux = 0 ; ux < NX; ux++) {
u32 uxyz = ux << YZBITS;
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
const u8 *readbig = zb.bytes, *endreadbig = readbig + zb.size;
// printf("id %d vx %d ux %d size %u\n", id, vx, ux, zb.size/SRCSIZE);
for (; readbig < endreadbig; readbig += SRCSIZE) {
// bit 39..34 33..21 20..13 12..0
// write UYYYYY UZZZZZ VYYYYY VZZZZ within VX partition
const u64 e = *(u64 *)readbig & SRCSLOTMASK;
uxyz += ((u32)(e >> YZBITS) - uxyz) & SRCPREFMASK;
// if (round==6) printf("id %d vx %d ux %d e %010lx suffUXYZ %05x suffUXY %03x UXYZ %08x UXY %04x mask %x\n", id, vx, ux, e, (u32)(e >> YZBITS), (u32)(e >> YZZBITS), uxyz, uxyz>>ZBITS, SRCPREFMASK);
const u32 vy = (e >> ZBITS) & YMASK;
// bit 41/39..34 33..26 25..13 12..0
// write UXXXXX UYYYYY UZZZZZ VZZZZ within VX VY partition
*(u64 *)(small0+small.index[vy]) = ((u64)uxyz << ZBITS) | (e & ZMASK);
uxyz &= ~ZMASK;
small.index[vy] += DSTSIZE;
}
if (unlikely(uxyz >> YZBITS != ux))
{ printf("OOPS3: id %d vx %d ux %d UXY %x\n", id, vx, ux, uxyz); exit(0); }
}
u8 *degs = tdegs[id];
small.storeu(tbuckets+id, 0);
TRIMONV ? dst.matrixv(vx) : dst.matrixu(vx);
for (u32 vy = 0 ; vy < NY; vy++) {
const u64 vy34 = (u64)vy << YZZBITS;
memset(degs, 0xff, NZ);
u8 *readsmall = tbuckets[id][vy].bytes, *endreadsmall = readsmall + tbuckets[id][vy].size;
// printf("id %d vx %d vy %d size %u sumsize %u\n", id, vx, vy, tbuckets[id][vx].size/BIGSIZE, sumsize);
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall += DSTSIZE)
degs[*(u32 *)rdsmall & ZMASK]++;
u32 ux = 0;
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall += DSTSIZE) {
// bit 41/39..34 33..26 25..13 12..0
// read UXXXXX UYYYYY UZZZZZ VZZZZ within VX VY partition
// bit 39..37 36..30 29..15 14..0 with XBITS==YBITS==7
// read UXXXXX UYYYYY UZZZZZ VZZZZ within VX VY partition
const u64 e = *(u64 *)rdsmall & DSTSLOTMASK;
ux += ((u32)(e >> YZZBITS) - ux) & DSTPREFMASK;
// printf("id %d vx %d vy %d e %010lx suffUX %02x UX %x mask %x\n", id, vx, vy, e, (u32)(e >> YZZBITS), ux, SRCPREFMASK);
// bit 41/39..34 33..21 20..13 12..0
// write VYYYYY VZZZZZ UYYYYY UZZZZ within UX partition
*(u64 *)(base+dst.index[ux]) = vy34 | ((e & ZMASK) << YZBITS) | ((e >> ZBITS) & YZMASK);
dst.index[ux] += degs[e & ZMASK] ? DSTSIZE : 0;
}
if (unlikely(ux >> DSTPREFBITS != XMASK >> DSTPREFBITS))
{ printf("OOPS4: id %d vx %x ux %x vs %x\n", id, vx, ux, XMASK); }
}
sumsize += TRIMONV ? dst.storev(buckets, vx) : dst.storeu(buckets, vx);
}
rdtsc1 = __rdtsc();
if (showall || (!id && !(round & (round+1))))
printf("trimedges id %d round %2d size %u rdtsc: %lu\n", id, round, sumsize/DSTSIZE, rdtsc1-rdtsc0);
tcounts[id] = sumsize/DSTSIZE;
}
template <u32 SRCSIZE, u32 DSTSIZE, bool TRIMONV>
void trimrename(const u32 id, const u32 round) {
const u32 SRCSLOTBITS = std::min(SRCSIZE * 8, (TRIMONV ? YZBITS : YZ1BITS) + YZBITS);
const u64 SRCSLOTMASK = (1ULL << SRCSLOTBITS) - 1ULL;
const u32 SRCPREFBITS = SRCSLOTBITS - YZBITS;
const u32 SRCPREFMASK = (1 << SRCPREFBITS) - 1;
const u32 SRCPREFBITS2 = SRCSLOTBITS - YZZBITS;
const u32 SRCPREFMASK2 = (1 << SRCPREFBITS2) - 1;
u64 rdtsc0, rdtsc1;
indexer<ZBUCKETSIZE> dst;
indexer<TBUCKETSIZE> small;
u32 maxnnid = 0;
rdtsc0 = __rdtsc();
offset_t sumsize = 0;
u8 const *base = (u8 *)buckets;
u8 const *small0 = (u8 *)tbuckets[id];
const u32 startvx = NY * id / nthreads;
const u32 endvx = NY * (id+1) / nthreads;
for (u32 vx = startvx; vx < endvx; vx++) {
small.matrixu(0);
for (u32 ux = 0 ; ux < NX; ux++) {
u32 uyz = 0;
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
const u8 *readbig = zb.bytes, *endreadbig = readbig + zb.size;
// printf("id %d vx %d ux %d size %u\n", id, vx, ux, zb.size/SRCSIZE);
for (; readbig < endreadbig; readbig += SRCSIZE) {
// bit 39..37 36..22 21..15 14..0
// write UYYYYY UZZZZZ VYYYYY VZZZZ within VX partition if TRIMONV
// bit 36...22 21..15 14..0
// write VYYYZZ' UYYYYY UZZZZ within UX partition if !TRIMONV
const u64 e = *(u64 *)readbig & SRCSLOTMASK;
if (TRIMONV)
uyz += ((u32)(e >> YZBITS) - uyz) & SRCPREFMASK;
else uyz = e >> YZBITS;
// if (round==32 && ux==25) printf("id %d vx %d ux %d e %010lx suffUXYZ %05x suffUXY %03x UXYZ %08x UXY %04x mask %x\n", id, vx, ux, e, (u32)(e >> YZBITS), (u32)(e >> YZZBITS), uxyz, uxyz>>ZBITS, SRCPREFMASK);
const u32 vy = (e >> ZBITS) & YMASK;
// bit 39..37 36..30 29..15 14..0
// write UXXXXX UYYYYY UZZZZZ VZZZZ within VX VY partition if TRIMONV
// bit 36...30 29...15 14..0
// write VXXXXXX VYYYZZ' UZZZZ within UX UY partition if !TRIMONV
*(u64 *)(small0+small.index[vy]) = ((u64)(ux << (TRIMONV ? YZBITS : YZ1BITS) | uyz) << ZBITS) | (e & ZMASK);
// if (TRIMONV&&vx==75&&vy==83) printf("id %d vx %d vy %d e %010lx e15 %x ux %x\n", id, vx, vy, ((u64)uxyz << ZBITS) | (e & ZMASK), uxyz, uxyz>>YZBITS);
if (TRIMONV)
uyz &= ~ZMASK;
small.index[vy] += SRCSIZE;
}
}
u16 *degs = (u16 *)tdegs[id];
small.storeu(tbuckets+id, 0);
TRIMONV ? dst.matrixv(vx) : dst.matrixu(vx);
u32 newnodeid = 0;
u32 *renames = TRIMONV ? buckets[0][vx].renamev : buckets[vx][0].renameu;
u32 *endrenames = renames + NZ1;
for (u32 vy = 0 ; vy < NY; vy++) {
memset(degs, 0xff, 2*NZ);
u8 *readsmall = tbuckets[id][vy].bytes, *endreadsmall = readsmall + tbuckets[id][vy].size;
// printf("id %d vx %d vy %d size %u sumsize %u\n", id, vx, vy, tbuckets[id][vx].size/BIGSIZE, sumsize);
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall += SRCSIZE)
degs[*(u32 *)rdsmall & ZMASK]++;
u32 ux = 0;
u32 nrenames = 0;
for (u8 *rdsmall = readsmall; rdsmall < endreadsmall; rdsmall += SRCSIZE) {
// bit 39..37 36..30 29..15 14..0
// read UXXXXX UYYYYY UZZZZZ VZZZZ within VX VY partition if TRIMONV
// bit 36...30 29...15 14..0
// read VXXXXXX VYYYZZ' UZZZZ within UX UY partition if !TRIMONV
const u64 e = *(u64 *)rdsmall & SRCSLOTMASK;
if (TRIMONV)
ux += ((u32)(e >> YZZBITS) - ux) & SRCPREFMASK2;
else ux = e >> YZZ1BITS;
const u32 vz = e & ZMASK;
u16 vdeg = degs[vz];
// if (TRIMONV&&vx==75&&vy==83) printf("id %d vx %d vy %d e %010lx e37 %x ux %x vdeg %d nrenames %d\n", id, vx, vy, e, e>>YZZBITS, ux, vdeg, nrenames);
if (vdeg) {
if (vdeg < 32) {
degs[vz] = vdeg = 32 + nrenames++;
*renames++ = vy << ZBITS | vz;
if (renames == endrenames) {
endrenames += (TRIMONV ? sizeof(yzbucket<ZBUCKETSIZE>) : sizeof(zbucket<ZBUCKETSIZE>)) / sizeof(u32);
renames = endrenames - NZ1;
}
}
// bit 36..22 21..15 14..0
// write VYYZZ' UYYYYY UZZZZ within UX partition if TRIMONV
if (TRIMONV)
*(u64 *)(base+dst.index[ux]) = ((u64)(newnodeid + vdeg-32) << YZBITS ) | ((e >> ZBITS) & YZMASK);
else *(u32 *)(base+dst.index[ux]) = ((newnodeid + vdeg-32) << YZ1BITS) | ((e >> ZBITS) & YZ1MASK);
// if (vx==44&&vy==58) printf(" id %d vx %d vy %d newe %010lx\n", id, vx, vy, vy28 | ((vdeg) << YZBITS) | ((e >> ZBITS) & YZMASK));
dst.index[ux] += DSTSIZE;
}
}
newnodeid += nrenames;
if (TRIMONV && unlikely(ux >> SRCPREFBITS2 != XMASK >> SRCPREFBITS2))
{ printf("OOPS6: id %d vx %d vy %d ux %x vs %x\n", id, vx, vy, ux, XMASK); exit(0); }
}
if (newnodeid > maxnnid)
maxnnid = newnodeid;
sumsize += TRIMONV ? dst.storev(buckets, vx) : dst.storeu(buckets, vx);
}
rdtsc1 = __rdtsc();
if (showall || !id) printf("trimrename id %d round %2d size %u rdtsc: %lu maxnnid %d\n", id, round, sumsize/DSTSIZE, rdtsc1-rdtsc0, maxnnid);
assert(maxnnid < NYZ1);
tcounts[id] = sumsize/DSTSIZE;
}
template <bool TRIMONV>
void trimedges1(const u32 id, const u32 round) {
u64 rdtsc0, rdtsc1;
indexer<ZBUCKETSIZE> dst;
rdtsc0 = __rdtsc();
offset_t sumsize = 0;
u8 *degs = tdegs[id];
u8 const *base = (u8 *)buckets;
const u32 startvx = NY * id / nthreads;
const u32 endvx = NY * (id+1) / nthreads;
for (u32 vx = startvx; vx < endvx; vx++) {
TRIMONV ? dst.matrixv(vx) : dst.matrixu(vx);
memset(degs, 0xff, NYZ1);
for (u32 ux = 0 ; ux < NX; ux++) {
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
u32 *readbig = zb.words, *endreadbig = readbig + zb.size/sizeof(u32);
// printf("id %d vx %d ux %d size %d\n", id, vx, ux, zb.size/SRCSIZE);
for (; readbig < endreadbig; readbig++)
degs[*readbig & YZ1MASK]++;
}
for (u32 ux = 0 ; ux < NX; ux++) {
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
u32 *readbig = zb.words, *endreadbig = readbig + zb.size/sizeof(u32);
for (; readbig < endreadbig; readbig++) {
// bit 29..22 21..15 14..7 6..0
// read UYYYYY UZZZZ' VYYYY VZZ' within VX partition
const u32 e = *readbig;
const u32 vyz = e & YZ1MASK;
// printf("id %d vx %d ux %d e %08lx vyz %04x uyz %04x\n", id, vx, ux, e, vyz, e >> YZ1BITS);
// bit 29..22 21..15 14..7 6..0
// write VYYYYY VZZZZ' UYYYY UZZ' within UX partition
*(u32 *)(base+dst.index[ux]) = (vyz << YZ1BITS) | (e >> YZ1BITS);
dst.index[ux] += degs[vyz] ? sizeof(u32) : 0;
}
}
sumsize += TRIMONV ? dst.storev(buckets, vx) : dst.storeu(buckets, vx);
}
rdtsc1 = __rdtsc();
if (showall || (!id && !(round & (round+1))))
printf("trimedges1 id %d round %2d size %u rdtsc: %lu\n", id, round, sumsize/sizeof(u32), rdtsc1-rdtsc0);
tcounts[id] = sumsize/sizeof(u32);
}
template <bool TRIMONV>
void trimrename1(const u32 id, const u32 round) {
u64 rdtsc0, rdtsc1;
indexer<ZBUCKETSIZE> dst;
u32 maxnnid = 0;
rdtsc0 = __rdtsc();
offset_t sumsize = 0;
u16 *degs = (u16 *)tdegs[id];
u8 const *base = (u8 *)buckets;
const u32 startvx = NY * id / nthreads;
const u32 endvx = NY * (id+1) / nthreads;
for (u32 vx = startvx; vx < endvx; vx++) {
TRIMONV ? dst.matrixv(vx) : dst.matrixu(vx);
memset(degs, 0xff, 2 * NYZ1); // sets each u16 entry to 0xffff
for (u32 ux = 0 ; ux < NX; ux++) {
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
u32 *readbig = zb.words, *endreadbig = readbig + zb.size/sizeof(u32);
// printf("id %d vx %d ux %d size %d\n", id, vx, ux, zb.size/SRCSIZE);
for (; readbig < endreadbig; readbig++)
degs[*readbig & YZ1MASK]++;
}
u32 newnodeid = 0;
u32 *renames = TRIMONV ? buckets[0][vx].renamev1 : buckets[vx][0].renameu1;
u32 *endrenames = renames + NZ2;
for (u32 ux = 0 ; ux < NX; ux++) {
zbucket<ZBUCKETSIZE> &zb = TRIMONV ? buckets[ux][vx] : buckets[vx][ux];
u32 *readbig = zb.words, *endreadbig = readbig + zb.size/sizeof(u32);
for (; readbig < endreadbig; readbig++) {
// bit 29...15 14...0
// read UYYYZZ' VYYZZ' within VX partition
const u32 e = *readbig;
const u32 vyz = e & YZ1MASK;
u16 vdeg = degs[vyz];
if (vdeg) {
if (vdeg < 32) {
degs[vyz] = vdeg = 32 + newnodeid++;
*renames++ = vyz;
if (renames == endrenames) {
endrenames += (TRIMONV ? sizeof(yzbucket<ZBUCKETSIZE>) : sizeof(zbucket<ZBUCKETSIZE>)) / sizeof(u32);
renames = endrenames - NZ2;
}
}
// bit 25...15 14...0
// write VYYZZZ" UYYZZ' within UX partition
*(u32 *)(base+dst.index[ux]) = ((vdeg - 32) << (TRIMONV ? YZ1BITS : YZ2BITS)) | (e >> YZ1BITS);
dst.index[ux] += sizeof(u32);
}
}
}
if (newnodeid > maxnnid)
maxnnid = newnodeid;
sumsize += TRIMONV ? dst.storev(buckets, vx) : dst.storeu(buckets, vx);
}
rdtsc1 = __rdtsc();
if (showall || !id) printf("trimrename1 id %d round %2d size %u rdtsc: %lu maxnnid %d\n", id, round, sumsize/sizeof(u32), rdtsc1-rdtsc0, maxnnid);
assert(maxnnid < NYZ2);
tcounts[id] = sumsize/sizeof(u32);
}
void trim() {
if (nthreads == 1) {
trimmer(0);
return;
}
void *etworker(void *vp);
thread_ctx *threads = new thread_ctx[nthreads];
for (u32 t = 0; t < nthreads; t++) {
threads[t].id = t;
threads[t].et = this;
int err = pthread_create(&threads[t].thread, NULL, etworker, (void *)&threads[t]);
assert(err == 0);
}
for (u32 t = 0; t < nthreads; t++) {
int err = pthread_join(threads[t].thread, NULL);
assert(err == 0);
}
delete[] threads;
}
void barrier() {
int rc = pthread_barrier_wait(&barry);
assert(rc == 0 || rc == PTHREAD_BARRIER_SERIAL_THREAD);
}
#ifdef EXPANDROUND
#define BIGGERSIZE BIGSIZE+1
#else
#define BIGGERSIZE BIGSIZE
#define EXPANDROUND COMPRESSROUND
#endif
void trimmer(u32 id) {
genUnodes(id, 0);
barrier();
genVnodes(id, 1);
for (u32 round = 2; round < ntrims-2; round += 2) {
barrier();
if (round < COMPRESSROUND) {
if (round < EXPANDROUND)
trimedges<BIGSIZE, BIGSIZE, true>(id, round);
else if (round == EXPANDROUND)
trimedges<BIGSIZE, BIGGERSIZE, true>(id, round);
else trimedges<BIGGERSIZE, BIGGERSIZE, true>(id, round);
} else if (round==COMPRESSROUND) {
trimrename<BIGGERSIZE, BIGGERSIZE, true>(id, round);
} else trimedges1<true>(id, round);
barrier();
if (round < COMPRESSROUND) {
if (round+1 < EXPANDROUND)
trimedges<BIGSIZE, BIGSIZE, false>(id, round+1);
else if (round+1 == EXPANDROUND)
trimedges<BIGSIZE, BIGGERSIZE, false>(id, round+1);
else trimedges<BIGGERSIZE, BIGGERSIZE, false>(id, round+1);
} else if (round==COMPRESSROUND) {
trimrename<BIGGERSIZE, sizeof(u32), false>(id, round+1);
} else trimedges1<false>(id, round+1);
}
barrier();
trimrename1<true >(id, ntrims-2);
barrier();
trimrename1<false>(id, ntrims-1);
}
};
void *etworker(void *vp) {
thread_ctx *tp = (thread_ctx *)vp;
tp->et->trimmer(tp->id);
pthread_exit(NULL);
return 0;
}
#define NODEBITS (EDGEBITS + 1)
// grow with cube root of size, hardly affected by trimming
const static u32 MAXPATHLEN = 8 << ((NODEBITS+2)/3);
const static u32 CUCKOO_SIZE = 2 * NX * NYZ2;
int nonce_cmp(const void *a, const void *b) {
return *(u32 *)a - *(u32 *)b;
}
typedef u32 proof[PROOFSIZE];
// break circular reference with forward declaration
class solver_ctx;
typedef struct {
u32 id;
pthread_t thread;
solver_ctx *solver;
} match_ctx;
class solver_ctx {
public:
edgetrimmer *trimmer;
u32 *cuckoo = 0;
bool showcycle;
proof cycleus;
proof cyclevs;
std::bitset<NXY> uxymap;
std::vector<u32> sols; // concatanation of all proof's indices
solver_ctx(const u32 n_threads, const u32 n_trims, bool allrounds, bool show_cycle) {
trimmer = new edgetrimmer(n_threads, n_trims, allrounds);
showcycle = show_cycle;
cuckoo = 0;
}
void setheadernonce(char* const headernonce, const u32 len, const u32 nonce) {
((u32 *)headernonce)[len/sizeof(u32)-1] = htole32(nonce); // place nonce at end
setheader(headernonce, len, &trimmer->sip_keys);
sols.clear();
}
~solver_ctx() {
delete trimmer;
}
u64 sharedbytes() const {
return sizeof(matrix<ZBUCKETSIZE>);
}
u32 threadbytes() const {
return sizeof(thread_ctx) + sizeof(yzbucket<TBUCKETSIZE>) + sizeof(zbucket8) + sizeof(zbucket16) + sizeof(zbucket32);
}
void recordedge(const u32 i, const u32 u2, const u32 v2) {
const u32 u1 = u2/2;
const u32 ux = u1 >> YZ2BITS;
u32 uyz = trimmer->buckets[ux][(u1 >> Z2BITS) & YMASK].renameu1[u1 & Z2MASK];
assert(uyz < NYZ1);
const u32 v1 = v2/2;
const u32 vx = v1 >> YZ2BITS;
u32 vyz = trimmer->buckets[(v1 >> Z2BITS) & YMASK][vx].renamev1[v1 & Z2MASK];
assert(vyz < NYZ1);
#if COMPRESSROUND > 0
uyz = trimmer->buckets[ux][uyz >> Z1BITS].renameu[uyz & Z1MASK];
vyz = trimmer->buckets[vyz >> Z1BITS][vx].renamev[vyz & Z1MASK];
#endif
const u32 u = cycleus[i] = (ux << YZBITS) | uyz;
const u32 v = cyclevs[i] = (vx << YZBITS) | vyz;
printf(" (%x,%x)", 2*u, 2*v+1);
#ifdef SAVEEDGES
u32 *readedges = trimmer->buckets[ux][uyz >> ZBITS].edges, *endreadedges = readedges + NTRIMMEDZ;
for (; readedges < endreadedges; readedges++) {
u32 edge = *readedges;
if (sipnode(&trimmer->sip_keys, edge, 1) == v && sipnode(&trimmer->sip_keys, edge, 0) == u) {
sols.push_back(edge);
return;
}
}
assert(0);
#else
uxymap[u >> ZBITS] = 1;
#endif
}
void solution(const u32 *us, u32 nu, const u32 *vs, u32 nv) {
printf("Nodes");
u32 ni = 0;
recordedge(ni++, *us, *vs);
while (nu--)
recordedge(ni++, us[(nu+1)&~1], us[nu|1]); // u's in even position; v's in odd
while (nv--)
recordedge(ni++, vs[nv|1], vs[(nv+1)&~1]); // u's in odd position; v's in even
printf("\n");
if (showcycle) {
#ifndef SAVEEDGES
void *matchworker(void *vp);
sols.resize(sols.size() + PROOFSIZE);
match_ctx *threads = new match_ctx[trimmer->nthreads];
for (u32 t = 0; t < trimmer->nthreads; t++) {
threads[t].id = t;
threads[t].solver = this;
int err = pthread_create(&threads[t].thread, NULL, matchworker, (void *)&threads[t]);
assert(err == 0);
}
for (u32 t = 0; t < trimmer->nthreads; t++) {
int err = pthread_join(threads[t].thread, NULL);
assert(err == 0);
}
#endif
qsort(&sols[sols.size()-PROOFSIZE], PROOFSIZE, sizeof(u32), nonce_cmp);
}
}
static const u32 CUCKOO_NIL = ~0;
u32 path(u32 u, u32 *us) const {
u32 nu, u0 = u;
for (nu = 0; u != CUCKOO_NIL; u = cuckoo[u]) {
if (nu >= MAXPATHLEN) {
while (nu-- && us[nu] != u) ;
if (!~nu)
printf("maximum path length exceeded\n");
else printf("illegal %4d-cycle from node %d\n", MAXPATHLEN-nu, u0);
pthread_exit(NULL);
}
us[nu++] = u;
}
return nu-1;
}
void findcycles() {
u32 us[MAXPATHLEN], vs[MAXPATHLEN];
u64 rdtsc0, rdtsc1;
rdtsc0 = __rdtsc();
for (u32 vx = 0; vx < NX; vx++) {
for (u32 ux = 0 ; ux < NX; ux++) {
zbucket<ZBUCKETSIZE> &zb = trimmer->buckets[ux][vx];
u32 *readbig = zb.words, *endreadbig = readbig + zb.size/sizeof(u32);
// printf("vx %d ux %d size %u\n", vx, ux, zb.size/4);
for (; readbig < endreadbig; readbig++) {
// bit 21..11 10...0
// write UYYZZZ' VYYZZ' within VX partition
const u32 e = *readbig;
const u32 uxyz = (ux << YZ2BITS) | (e >> YZ2BITS);
const u32 vxyz = (vx << YZ2BITS) | (e & YZ2MASK);
const u32 u0 = uxyz << 1, v0 = (vxyz << 1) | 1;
if (u0 != CUCKOO_NIL) {
u32 nu = path(u0, us), nv = path(v0, vs);
// printf("vx %02x ux %02x e %08x uxyz %06x vxyz %06x u0 %x v0 %x nu %d nv %d\n", vx, ux, e, uxyz, vxyz, u0, v0, nu, nv);
if (us[nu] == vs[nv]) {
const u32 min = nu < nv ? nu : nv;
for (nu -= min, nv -= min; us[nu] != vs[nv]; nu++, nv++) ;
const u32 len = nu + nv + 1;
printf("%4d-cycle found\n", len);
if (len == PROOFSIZE)
solution(us, nu, vs, nv);
} else if (nu < nv) {
while (nu--)
cuckoo[us[nu+1]] = us[nu];
cuckoo[u0] = v0;
} else {
while (nv--)
cuckoo[vs[nv+1]] = vs[nv];
cuckoo[v0] = u0;
}
}
}
}
}
rdtsc1 = __rdtsc();
printf("findcycles rdtsc: %lu\n", rdtsc1-rdtsc0);
}
int solve() {
assert((u64)CUCKOO_SIZE * sizeof(u32) <= trimmer->nthreads * sizeof(yzbucket<TBUCKETSIZE>));
trimmer->trim();
cuckoo = (u32 *)trimmer->tbuckets;
memset(cuckoo, CUCKOO_NIL, CUCKOO_SIZE * sizeof(u32));
findcycles();
return sols.size() / PROOFSIZE;
}
void *matchUnodes(match_ctx *mc) {
u64 rdtsc0, rdtsc1;
rdtsc0 = __rdtsc();
const u32 starty = NY * mc->id / trimmer->nthreads;
const u32 endy = NY * (mc->id+1) / trimmer->nthreads;
u32 edge = starty << YZBITS, endedge = edge + NYZ;
#if NSIPHASH == 4
static const __m128i vnodemask = {EDGEMASK, EDGEMASK};
siphash_keys &sip_keys = trimmer->sip_keys;
__m128i v0, v1, v2, v3, v4, v5, v6, v7;
const u32 e2 = 2 * edge;
__m128i vpacket0 = _mm_set_epi64x(e2+2, e2+0);
__m128i vpacket1 = _mm_set_epi64x(e2+6, e2+4);
static const __m128i vpacketinc = {8, 8};
#elif NSIPHASH == 8
static const __m256i vnodemask = {EDGEMASK, EDGEMASK, EDGEMASK, EDGEMASK};
const __m256i vinit = _mm256_load_si256((__m256i *)&trimmer->sip_keys);
__m256i v0, v1, v2, v3, v4, v5, v6, v7;
const u32 e2 = 2 * edge;
__m256i vpacket0 = _mm256_set_epi64x(e2+6, e2+4, e2+2, e2+0);
__m256i vpacket1 = _mm256_set_epi64x(e2+14, e2+12, e2+10, e2+8);
static const __m256i vpacketinc = {16, 16, 16, 16};
#endif
for (u32 my = starty; my < endy; my++, endedge += NYZ) {
for (; edge < endedge; edge += NSIPHASH) {
// bit 28..21 20..13 12..0
// node XXXXXX YYYYYY ZZZZZ
#if NSIPHASH == 1
const u32 nodeu = sipnode(&trimmer->sip_keys, edge, 0);
if (uxymap[nodeu >> ZBITS]) {
for (u32 j = 0; j < PROOFSIZE; j++) {
if (cycleus[j] == nodeu && cyclevs[j] == sipnode(&trimmer->sip_keys, edge, 1)) {
sols[sols.size()-PROOFSIZE + j] = edge;
}
}
}
// bit 39..21 20..13 12..0
// write edge YYYYYY ZZZZZ
#elif NSIPHASH == 4
v7 = v3 = _mm_set1_epi64x(sip_keys.k3);
v4 = v0 = _mm_set1_epi64x(sip_keys.k0);
v5 = v1 = _mm_set1_epi64x(sip_keys.k1);
v6 = v2 = _mm_set1_epi64x(sip_keys.k2);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2, _mm_set1_epi64x(0xffLL));
v6 = XOR(v6, _mm_set1_epi64x(0xffLL));
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
vpacket0 = _mm_add_epi64(vpacket0, vpacketinc);
vpacket1 = _mm_add_epi64(vpacket1, vpacketinc);
v0 = v0 & vnodemask;
v4 = v4 & vnodemask;
v1 = _mm_srli_epi64(v0, ZBITS);
v5 = _mm_srli_epi64(v4, ZBITS);
u32 uxy;
#define MATCH(i,v,x,w) \
uxy = extract32(v,x);\
if (uxymap[uxy]) {\
u32 u = extract32(w,x);\
for (u32 j = 0; j < PROOFSIZE; j++) {\
if (cycleus[j] == u && cyclevs[j] == sipnode(&trimmer->sip_keys, edge+i, 1)) {\
sols[sols.size()-PROOFSIZE + j] = edge + i;\
}\
}\
}
MATCH(0,v1,0,v0); MATCH(1,v1,2,v0);
MATCH(2,v5,0,v4); MATCH(3,v5,2,v4);
#elif NSIPHASH == 8
v7 = v3 = _mm256_permute4x64_epi64(vinit, 0xFF);
v4 = v0 = _mm256_permute4x64_epi64(vinit, 0x00);
v5 = v1 = _mm256_permute4x64_epi64(vinit, 0x55);
v6 = v2 = _mm256_permute4x64_epi64(vinit, 0xAA);
v3 = XOR(v3,vpacket0); v7 = XOR(v7,vpacket1);
SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(v0,vpacket0); v4 = XOR(v4,vpacket1);
v2 = XOR(v2,_mm256_set1_epi64x(0xffLL));
v6 = XOR(v6,_mm256_set1_epi64x(0xffLL));
SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N; SIPROUNDX2N;
v0 = XOR(XOR(v0,v1),XOR(v2,v3));
v4 = XOR(XOR(v4,v5),XOR(v6,v7));
vpacket0 = _mm256_add_epi64(vpacket0, vpacketinc);
vpacket1 = _mm256_add_epi64(vpacket1, vpacketinc);
v0 = v0 & vnodemask;
v4 = v4 & vnodemask;
v1 = _mm256_srli_epi64(v0, ZBITS);
v5 = _mm256_srli_epi64(v4, ZBITS);
u32 uxy;
#define MATCH(i,v,x,w) \
uxy = _mm256_extract_epi32(v,x);\
if (uxymap[uxy]) {\
u32 u = _mm256_extract_epi32(w,x);\
for (u32 j = 0; j < PROOFSIZE; j++) {\
if (cycleus[j] == u && cyclevs[j] == sipnode(&trimmer->sip_keys, edge+i, 1)) {\
sols[sols.size()-PROOFSIZE + j] = edge + i;\
}\
}\
}
MATCH(0,v1,0,v0); MATCH(1,v1,2,v0); MATCH(2,v1,4,v0); MATCH(3,v1,6,v0);
MATCH(4,v5,0,v4); MATCH(5,v5,2,v4); MATCH(6,v5,4,v4); MATCH(7,v5,6,v4);
#else
#error not implemented
#endif
}
}
rdtsc1 = __rdtsc();
if (trimmer->showall || !mc->id) printf("matchUnodes id %d rdtsc: %lu\n", mc->id, rdtsc1-rdtsc0);
pthread_exit(NULL);
return 0;
}
};
void *matchworker(void *vp) {
match_ctx *tp = (match_ctx *)vp;
tp->solver->matchUnodes(tp);
pthread_exit(NULL);
return 0;
}
| [
"root@vps-d103d3611a7812a1.gib58asjnbc9.domain.tld"
] | root@vps-d103d3611a7812a1.gib58asjnbc9.domain.tld |
a806e3fa625d2e203237e0ea974e09b5ef9f2304 | 04855d63403efcb5316e3ea11e57128e9f7c5c02 | /mediapipe/gpu/gl_context_egl.cc | 79f0c30ebe2655b8fb0d42df2e01ba65a28cbe25 | [
"Apache-2.0"
] | permissive | Gilgahex/mediapipe | bc49f9d8b7048f24c9fe59c98f68d8b3b6cd863d | c06effd494e8da07488723615522e67ce9783c0a | refs/heads/master | 2021-10-28T07:25:30.760525 | 2020-03-09T01:52:05 | 2020-03-09T01:52:05 | 216,973,960 | 4 | 7 | Apache-2.0 | 2021-10-14T01:29:02 | 2019-10-23T05:19:19 | C++ | UTF-8 | C++ | false | false | 9,862 | cc | // Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <utility>
#include "absl/memory/memory.h"
#include "mediapipe/framework/port/logging.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/status_builder.h"
#include "mediapipe/gpu/gl_context.h"
#include "mediapipe/gpu/gl_context_internal.h"
#ifndef EGL_OPENGL_ES3_BIT_KHR
#define EGL_OPENGL_ES3_BIT_KHR 0x00000040
#endif
#if HAS_EGL
namespace mediapipe {
static pthread_key_t egl_release_thread_key;
static pthread_once_t egl_release_key_once = PTHREAD_ONCE_INIT;
static void EglThreadExitCallback(void* key_value) {
#if defined(__ANDROID__)
eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
#else
// Some implementations have chosen to allow EGL_NO_DISPLAY as a valid display
// parameter for eglMakeCurrent. This behavior is not portable to all EGL
// implementations, and should be considered as an undocumented vendor
// extension.
// https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglMakeCurrent.xhtml
eglMakeCurrent(eglGetDisplay(EGL_DEFAULT_DISPLAY), EGL_NO_SURFACE,
EGL_NO_SURFACE, EGL_NO_CONTEXT);
#endif
eglReleaseThread();
}
// If a key has a destructor callback, and a thread has a non-NULL value for
// that key, then the destructor is called when the thread exits.
static void MakeEglReleaseThreadKey() {
int err = pthread_key_create(&egl_release_thread_key, EglThreadExitCallback);
if (err) {
LOG(ERROR) << "cannot create pthread key: " << err;
}
}
// This function can be called any number of times. For any thread on which it
// was called at least once, the EglThreadExitCallback will be called (once)
// when the thread exits.
static void EnsureEglThreadRelease() {
pthread_once(&egl_release_key_once, MakeEglReleaseThreadKey);
pthread_setspecific(egl_release_thread_key,
reinterpret_cast<void*>(0xDEADBEEF));
}
GlContext::StatusOrGlContext GlContext::Create(std::nullptr_t nullp,
bool create_thread) {
return Create(EGL_NO_CONTEXT, create_thread);
}
GlContext::StatusOrGlContext GlContext::Create(const GlContext& share_context,
bool create_thread) {
return Create(share_context.context_, create_thread);
}
GlContext::StatusOrGlContext GlContext::Create(EGLContext share_context,
bool create_thread) {
std::shared_ptr<GlContext> context(new GlContext());
MP_RETURN_IF_ERROR(context->CreateContext(share_context));
MP_RETURN_IF_ERROR(context->FinishInitialization(create_thread));
return std::move(context);
}
::mediapipe::Status GlContext::CreateContextInternal(
EGLContext external_context, int gl_version) {
CHECK(gl_version == 2 || gl_version == 3);
const EGLint config_attr[] = {
// clang-format off
EGL_RENDERABLE_TYPE, gl_version == 3 ? EGL_OPENGL_ES3_BIT_KHR
: EGL_OPENGL_ES2_BIT,
// Allow rendering to pixel buffers or directly to windows.
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT | EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8, // if you need the alpha channel
EGL_DEPTH_SIZE, 16, // if you need the depth buffer
EGL_NONE
// clang-format on
};
// TODO: improve config selection.
EGLint num_configs;
EGLBoolean success =
eglChooseConfig(display_, config_attr, &config_, 1, &num_configs);
if (!success) {
return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC)
<< "eglChooseConfig() returned error " << std::showbase << std::hex
<< eglGetError();
}
if (!num_configs) {
return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC)
<< "eglChooseConfig() returned no matching EGL configuration for "
<< "RGBA8888 D16 ES" << gl_version << " request. ";
}
const EGLint context_attr[] = {
// clang-format off
EGL_CONTEXT_CLIENT_VERSION, gl_version,
EGL_NONE
// clang-format on
};
context_ =
eglCreateContext(display_, config_, external_context, context_attr);
int error = eglGetError();
RET_CHECK(context_ != EGL_NO_CONTEXT)
<< "Could not create GLES " << gl_version << " context; "
<< "eglCreateContext() returned error " << std::showbase << std::hex
<< error
<< (error == EGL_BAD_CONTEXT
? ": external context uses a different version of OpenGL"
: "");
// We can't always rely on GL_MAJOR_VERSION and GL_MINOR_VERSION, since
// GLES 2 does not have them, so let's set the major version here at least.
gl_major_version_ = gl_version;
return ::mediapipe::OkStatus();
}
::mediapipe::Status GlContext::CreateContext(EGLContext external_context) {
EGLint major = 0;
EGLint minor = 0;
display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
RET_CHECK(display_ != EGL_NO_DISPLAY)
<< "eglGetDisplay() returned error " << std::showbase << std::hex
<< eglGetError();
EGLBoolean success = eglInitialize(display_, &major, &minor);
RET_CHECK(success) << "Unable to initialize EGL";
LOG(INFO) << "Successfully initialized EGL. Major : " << major
<< " Minor: " << minor;
auto status = CreateContextInternal(external_context, 3);
if (!status.ok()) {
LOG(WARNING) << "Creating a context with OpenGL ES 3 failed: " << status;
LOG(WARNING) << "Fall back on OpenGL ES 2.";
status = CreateContextInternal(external_context, 2);
}
MP_RETURN_IF_ERROR(status);
EGLint pbuffer_attr[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
surface_ = eglCreatePbufferSurface(display_, config_, pbuffer_attr);
RET_CHECK(surface_ != EGL_NO_SURFACE)
<< "eglCreatePbufferSurface() returned error " << std::showbase
<< std::hex << eglGetError();
return ::mediapipe::OkStatus();
}
void GlContext::DestroyContext() {
if (thread_) {
// Delete thread-local storage.
// TODO: in theory our EglThreadExitCallback should suffice for
// this; however, heapcheck still reports a leak without this call here
// when using SwiftShader.
// Perhaps heapcheck misses the thread destructors?
thread_
->Run([] {
eglReleaseThread();
return ::mediapipe::OkStatus();
})
.IgnoreError();
}
// Destroy the context and surface.
if (IsCurrent()) {
if (!eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT)) {
LOG(ERROR) << "eglMakeCurrent() returned error " << std::showbase
<< std::hex << eglGetError();
}
}
if (surface_ != EGL_NO_SURFACE) {
if (!eglDestroySurface(display_, surface_)) {
LOG(ERROR) << "eglDestroySurface() returned error " << std::showbase
<< std::hex << eglGetError();
}
surface_ = EGL_NO_SURFACE;
}
if (context_ != EGL_NO_CONTEXT) {
if (!eglDestroyContext(display_, context_)) {
LOG(ERROR) << "eglDestroyContext() returned error " << std::showbase
<< std::hex << eglGetError();
}
context_ = EGL_NO_CONTEXT;
}
// Under standard EGL, eglTerminate will terminate the display connection
// for the entire process, no matter how many times eglInitialize has been
// called. So we do not want to terminate it here, in case someone else is
// using it.
// However, Android implements non-standard reference-counted semantics for
// eglInitialize/eglTerminate, so we should call it on that platform.
#ifdef __ANDROID__
// TODO: this is removed for now since it caused issues on
// YouTube. But in theory we _should_ be calling it. Needs more
// investigation.
// eglTerminate(display_);
#endif // __ANDROID__
}
GlContext::ContextBinding GlContext::ThisContextBinding() {
GlContext::ContextBinding result;
result.context_object = shared_from_this();
result.display = display_;
result.draw_surface = surface_;
result.read_surface = surface_;
result.context = context_;
return result;
}
void GlContext::GetCurrentContextBinding(GlContext::ContextBinding* binding) {
binding->display = eglGetCurrentDisplay();
binding->draw_surface = eglGetCurrentSurface(EGL_DRAW);
binding->read_surface = eglGetCurrentSurface(EGL_READ);
binding->context = eglGetCurrentContext();
}
::mediapipe::Status GlContext::SetCurrentContextBinding(
const ContextBinding& new_binding) {
EnsureEglThreadRelease();
EGLDisplay display = new_binding.display;
if (display == EGL_NO_DISPLAY) {
display = eglGetCurrentDisplay();
}
if (display == EGL_NO_DISPLAY) {
display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
}
EGLBoolean success =
eglMakeCurrent(display, new_binding.draw_surface,
new_binding.read_surface, new_binding.context);
RET_CHECK(success) << "eglMakeCurrent() returned error " << std::showbase
<< std::hex << eglGetError();
return ::mediapipe::OkStatus();
}
bool GlContext::HasContext() const { return context_ != EGL_NO_CONTEXT; }
bool GlContext::IsCurrent() const {
return HasContext() && (eglGetCurrentContext() == context_);
}
} // namespace mediapipe
#endif // HAS_EGL
| [
"jqtang@google.com"
] | jqtang@google.com |
32ce24de77b65ed770a6ab14a58082463652695c | e1abc6f1cbabad56563f49d73ac6ade4f0c0077f | /src/chain/chainparams.h | 2de01aa762bcdc4438d9a7183a2f92c3c9048350 | [
"MIT"
] | permissive | MasterKungfu/MagnaChain-dev-master | 9072bcd3790ab3f953ee6193666f6d361747605c | 2980b7f7c591e2f46f750de03a9df91e71319c74 | refs/heads/master | 2020-04-29T14:15:59.004648 | 2019-03-15T09:12:26 | 2019-03-15T09:12:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,836 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2016-2019 The MagnaChain Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MAGNACHAIN_CHAINPARAMS_H
#define MAGNACHAIN_CHAINPARAMS_H
#include "chainparamsbase.h"
#include "consensus/params.h"
#include "primitives/block.h"
#include "net/protocol.h"
#include <memory>
#include <vector>
static const int MAIN_CHAIN_POW_TARGET_SPACING = 15;
static const int BRANCH_CHAIN_POW_TARGET_SPACING = 8;
static const int TEST_CHAIN_POW_TARGET_SPACING = 5;
struct MCDNSSeedData {
std::string host;
bool supportsServiceBitsFiltering;
MCDNSSeedData(const std::string &strHost, bool supportsServiceBitsFilteringIn) : host(strHost), supportsServiceBitsFiltering(supportsServiceBitsFilteringIn) {}
};
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
typedef std::map<int, uint256> MapCheckpoints;
struct MCCheckpointData {
MapCheckpoints mapCheckpoints;
};
struct ChainTxData {
int64_t nTime;
int64_t nTxCount;
double dTxRate;
};
int GetBranchInitDefaultPort(bool fTestNet, bool fRegTest);
/**
* MCChainParams defines various tweakable parameters of a given instance of the
* MagnaChain system. There are three: the main network on which people trade goods
* and services, the public test network which gets reset from time to time and
* a regression test mode which is intended for private networks only. It has
* minimal difficulty to ensure that blocks can be found instantly.
*/
class MCChainParams
{
public:
enum Base58Type {
PUBKEY_ADDRESS,
SCRIPT_ADDRESS,
SECRET_KEY,
EXT_PUBLIC_KEY,
EXT_SECRET_KEY,
CONTRACT_ADDRESS,
MAX_BASE58_TYPES
};
const Consensus::Params& GetConsensus() const { return consensus; }
const MCMessageHeader::MessageStartChars& MessageStart() const { return pchMessageStart; }
int GetDefaultPort() const;
const MCBlock& GenesisBlock() const { return genesis; }
/** Default value for -checkmempool and -checkblockindex argument */
bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; }
/** Policy: Filter transactions that do not match well-defined patterns */
bool RequireStandard() const { return fRequireStandard; }
uint64_t PruneAfterHeight() const { return nPruneAfterHeight; }
/** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */
bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; }
/** Return the BIP70 network string (main, test or regtest) */
std::string NetworkIDString() const { return strNetworkID; }
const std::vector<MCDNSSeedData>& DNSSeeds() const { return vSeeds; }
void ClearDNSSeeds() { vSeeds.clear(); }
void PushBackDNSSeeds(const std::string strSeed) { vSeeds.emplace_back(strSeed, false); }
const std::vector<unsigned char>& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; }
const std::vector<SeedSpec6>& FixedSeeds() const { return vFixedSeeds; }
void ClearFixedSeeds() { vFixedSeeds.clear(); }
void PushFixedSeeds(const SeedSpec6 &ssp) { vFixedSeeds.emplace_back(ssp); }
const MCCheckpointData& Checkpoints() const { return checkpointData; }
const uint256* GetCheckpointHeightHash(int height) const;
const ChainTxData& TxData() const { return chainTxData; }
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout);
//void SetBranchId(const std::string& name) { strBranchId = name; }
std::string GetBranchId(void) const { return strBranchId; }
inline bool IsMainChain() const {
return GetBranchId() == MCBaseChainParams::MAIN;
}
const uint256& GetBranchHash()const { return branchhash; }
void InitMainBase58Prefixes();
void InitTestnetBase58Prefixes();
void InitRegtestBase58Prefixes();
protected:
MCChainParams() {}
Consensus::Params consensus;
MCMessageHeader::MessageStartChars pchMessageStart;
int nDefaultPort;
uint64_t nPruneAfterHeight;
std::vector<MCDNSSeedData> vSeeds;
std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES];
std::string strNetworkID;
MCBlock genesis;
std::vector<SeedSpec6> vFixedSeeds;
bool fDefaultConsistencyChecks;
bool fRequireStandard;
bool fMineBlocksOnDemand;
MCCheckpointData checkpointData;
ChainTxData chainTxData;
std::string strBranchId = MCBaseChainParams::MAIN;
uint256 branchhash;
};
/**
* Creates and returns a std::unique_ptr<MCChainParams> of the chosen chain.
* @returns a MCChainParams* of the chosen chain.
* @throws a std::runtime_error if the chain is not supported.
*/
std::unique_ptr<MCChainParams> CreateChainParams(const std::string& chain);
/**
* Return the currently selected parameters. This won't change after app
* startup, except for unit tests.
*/
const MCChainParams &Params();
const MCChainParams& BranchParams(const uint256& branchHash);
/**
* Sets the params returned by Params() to those for the given BIP70 chain name.
* @throws std::runtime_error when the chain is not supported.
*/
void SelectParams(const std::string& chain);
/**
* Allows modifying the Version Bits regtest parameters.
*/
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout);
class MCKeyStore;
class MCMutableTransaction;
class MCScript;
typedef bool(*SignatureCoinbaseTransactionPf)(int nHeight, const MCKeyStore* keystoreIn, MCMutableTransaction& tx, MCAmount nValue, const MCScript& scriptPubKey);
extern SignatureCoinbaseTransactionPf SignatureCoinbaseTransactionPF;
#endif // MAGNACHAIN_CHAINPARAMS_H
| [
"weigun@weigun.com"
] | weigun@weigun.com |
412307e608542cc6490ff7892307f7029d8adcee | 2183a08727f594925d06c73ee800163bf85ac410 | /test/analog-serial.cpp | e588864b890ae319543331a8f3a36e674347f27a | [] | no_license | tadryanom/Serasidis_arduino-opencm3 | bd600e967d15d19eaba905caa5884fcf4de8a956 | bb3a03c432bbeeae0138f6d21e40005dbfe271e3 | refs/heads/master | 2021-06-13T11:11:24.967443 | 2017-03-25T13:40:30 | 2017-03-25T13:40:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | cpp | #include <Arduino.h>
#include <stm32/gpio_arch.h>
#include <stm32/adc_arch.h>
void setup() {
Serial.begin(115200);
Serial.println("---START---");
Serial.println("---INIT---");
}
void loop() {
int start = micros();
uint32_t sensorValue = analogRead(A0);
unsigned long end = micros();
Serial.print(end - start);
Serial.print("uS. Value :");
Serial.print(sensorValue);
Serial.print(" Vref :");
Serial.print(adc_getVref());
Serial.print(" Temp :");
Serial.print(adc_getTemperature());
Serial.println("");
delay(100);
}
| [
"arkalis.e@gmail.com"
] | arkalis.e@gmail.com |
abc0cf2f380a427c04a613076fec66cd0dcbb408 | 527aaa10852c19ded7709b7c51638f54bf26a963 | /Source/Heightmap.h | cbbf803efc42857cc1103d745976201fe8edbdd5 | [
"MIT"
] | permissive | craig4096/procgenapp | 4f45bb891963021762cc8dc40caad6cfa9ab904f | 5253eac7b073f8e1842ceaf9174c807cfbb8dff6 | refs/heads/master | 2020-03-11T04:35:01.004074 | 2018-04-16T17:20:38 | 2018-04-16T17:20:38 | 129,779,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,997 | h | #pragma once
#include "math3d.h"
#include "Array2D.h"
class Heightmap : public Array2D<float> {
protected:
// the difference between a heightmap and a simple 2d array of floats
// is that the heightmap has scale factors to determine it's size in the world
// (used for calculating normals etc.)
float scaleX;
float scaleY;
float scaleZ;
// returns the normal vector of the terrain at the given x, y position
// note: vector returned depends on scale factors (x, y, z) as these
// affect the surface orientations
vec3 GetNormal(int x, int z) const;
// determines whether the angle of a point's normal
// is within a specific threshold (used for determining
// if a point is walkable or not)
bool isWalkable(int x, int z, float angleThreshold) const;
public:
Heightmap(int width, int height);
Heightmap(int width, int height, float scaleX, float scaleY, float scaleZ);
~Heightmap();
float GetScaleY() const { return scaleY; }
float GetScaleX() const { return scaleX; }
float GetScaleZ() const { return scaleZ; }
// calculates the mean value of the heightmaps corresponding slopemap
float CalculateMeanSlope() const;
// calculates the standard deviation of the slopemap
float CalculateSlopeStandardDeviation(float meanSlope) const;
// calculates the erosion score for this heightmap
float CalculateErosionScore() const;
// calculates the total walkable area given an angle threshold
// the angleThreshold is the angle (between 0-90) of which players can walk upon
float CalculateTotalWalkableArea(float angleThreshold) const;
// calculates the number of regions in the map which the player can walk on
int CalculateNumDisconnectedRegions(float angleThreshold) const;
float GetScaledHeight(int x, int y) const;
// returns an interpolated height value given the real world-x and z coords
float GetWorldHeight(float x, float y) const;
float GetMinValue() const;
float GetMaxValue() const;
};
| [
"craig4096@hotmail.co.uk"
] | craig4096@hotmail.co.uk |
29c2193df3ddbad0982be76420f8a5a78bbddc42 | cbd201169b823159a3da0a5188995a0b10c815e6 | /StateInterface.cpp | d172f503cf9b6e5b98852aa1fdd3078450aa6488 | [] | no_license | paullam328/Nova | bdd520432700fe95cc484b9955a698b3e4ed4b22 | c2ad879845d68efe7fd1f4aab121a711bf3d3b15 | refs/heads/master | 2022-03-29T07:37:01.823454 | 2020-01-17T15:39:59 | 2020-01-17T15:39:59 | 234,577,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 156 | cpp | // Copywrite Shapeshifter 2019
#include "StateInterface.h"
// Add default functionality here for any IStateInterface functions that are not pure virtual.
| [
"paullam328@gmail.com"
] | paullam328@gmail.com |
3c8f86cf8c36c7c630131db5431de5bf97c6280e | ec466877d3ab45de393c0c76ccad2679b1a5b8fe | /psr1/debugger.cpp | cff4c3189b83868c4d2227dd68dfe884afe1970a | [] | no_license | ncollisson/pointer-sequence-reversal | 99508ca343c41c1bfaa94929aad408126d38f723 | 5b84a02870b2bd08190d457fd9795aed3ef382bf | refs/heads/master | 2021-06-16T20:57:41.162588 | 2017-05-11T16:24:47 | 2017-05-11T16:24:47 | 81,142,083 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 14,520 | cpp | #include "stdafx.h"
#include "debugger.h"
#include <iostream>
#include <tlhelp32.h>
#include <array>
#include "capstone.h"
//#include <stdio.h>
#include <inttypes.h>
//#include "CsCapstoneHelper.hh"
//#include "Disasm.hpp"
//#include "CsIns.hpp"
//#include "X86Disasm.hh"
#include "Tracer.h"
int (WINAPIV * __vsnprintf)(char *, size_t, const char*, va_list) = _vsnprintf;
Debugger::Debugger()
{
// probably bad
// Tracer: cs_open(CS_ARCH_X86, CS_MODE_32, &cs_handle);
// also, where to initialize tracer?
}
Debugger::~Debugger()
{
}
int Debugger::SetTargetPID(DWORD target_pid)
{
this->target_pid = target_pid;
return 1;
}
int Debugger::SetTargetAddress(LPVOID target_address)
{
this->target_address = target_address;
return 1;
}
int Debugger::Attach()
{
if (!DebugActiveProcess(target_pid))
{
std::cout << "Error in DebugActiveProcess(): " << GetLastError() << std::endl;
return 0;
}
if (!DebugSetProcessKillOnExit(FALSE))
{
std::cout << "Could not DebugSetProcessKillOnExit(FALSE)" << std::endl;
}
std::cout << "Now debugging the target process" << std::endl;
return 1;
}
int Debugger::SetMemoryBreakpoint(LPVOID target_address = NULL)
{
DWORD old_protect;
MEMORY_BASIC_INFORMATION page_info;
PMEMORY_BASIC_INFORMATION ppage_info = &page_info;
size_t breakpoint_size = 1;
if (target_handle == NULL)
{
target_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, target_pid);
if (!target_handle)
{
std::cout << "Error in OpenProcess(): " << GetLastError() << std::endl;
return 0;
}
std::cout << "Obtained handle to target process" << std::endl;
}
if (tracer == NULL)
{
tracer = std::make_unique<Tracer>(target_handle);
}
if (target_address == NULL)
{
target_address = this->target_address;
if (target_address == NULL)
{
std::cout << "Won't attempt to set breakpoint at NULL address" << std::endl;
return 0;
}
}
if (!VirtualQueryEx(target_handle, target_address, ppage_info, sizeof(MEMORY_BASIC_INFORMATION)))
{
std::cout << "Error in VirtualQueryEx(): " << GetLastError() << std::endl;
return 0;
}
orig_protect = ppage_info->Protect;
if (!VirtualProtectEx(target_handle, target_address, breakpoint_size, orig_protect | PAGE_GUARD, &old_protect))
{
std::cout << "Error in VirtualProtectEx(): " << GetLastError() << std::endl;
return 0;
}
//std::cout << "Set memory breakpoint, waiting for debug event" << std::endl;
return 1;
}
int Debugger::RemoveMemoryBreakpoint()
{
DWORD old_protect;
MEMORY_BASIC_INFORMATION page_info;
PMEMORY_BASIC_INFORMATION ppage_info = &page_info;
size_t breakpoint_size = 1;
if (!VirtualProtectEx(target_handle, target_address, breakpoint_size, orig_protect, &old_protect))
{
std::cout << "Error in VirtualProtectEx(): " << GetLastError() << std::endl;
return 0;
}
return 1;
}
int Debugger::WaitForMemoryBreakpoint()
{
EXCEPTION_RECORD exception_record;
DEBUG_EVENT debug_event;
LPDEBUG_EVENT lpdebug_event = &debug_event;
DWORD offending_thread_ID;
HANDLE new_thread_handle;
DWORD new_thread_id;
CONTEXT thread_context;
BOOL wait_to_set_mem_bp = FALSE;
const size_t MAX_INSTRUCTION_LENGTH = 15;
uint8_t instruction_buffer[2 * MAX_INSTRUCTION_LENGTH] = {0};
SIZE_T num_bytes_read;
size_t cs_count;
cs_insn *insn;
// maybe up here set trap flag
// 0x51 == Q key
while (!GetAsyncKeyState(0x51))
{
if (!WaitForDebugEvent(lpdebug_event, INFINITE))
{
std::cout << "Error in WaitForDebugEvent(): " << GetLastError() << std::endl;
return 0;
}
exception_record = lpdebug_event->u.Exception.ExceptionRecord;
switch (lpdebug_event->dwDebugEventCode)
{
case EXCEPTION_DEBUG_EVENT:
offending_thread_ID = lpdebug_event->dwThreadId;
switch (exception_record.ExceptionCode)
{
case STATUS_GUARD_PAGE_VIOLATION:
if (IsMemoryBreakpointHit(debug_event))
{
GetCurrentThreadContext(offending_thread_ID, thread_context);
// profile this and other rpms, how bad are they?
// probably doesnt matter too much this doesnt happen very often
ReadProcessMemory(target_handle, LPCVOID (thread_context.Eip), instruction_buffer, sizeof(instruction_buffer), &num_bytes_read);
cs_count = cs_disasm(tracer->cs_handle, instruction_buffer, sizeof(instruction_buffer), thread_context.Eip, 0, &insn);
// do we need to do the first or second insn from buffer?
// if first, just get rid of 2x max size
cs_insn offending_instruction = insn[1];
// do insn_buffer = offending_instruction.byte buffer
// then saveinstruction(insn_buffer)
uint8_t* insn_buffer = insn->bytes;
tracer->SaveInstruction(insn_buffer, offending_thread_ID, thread_context);
//tracer->SaveInstructionInfo(instruction_buffer, max_insn_size, offending_thread_ID, thread_context);
tracer->AnalyzeRunTrace(offending_thread_ID, exception_record);
}
SetTrapFlag(offending_thread_ID);
ContinueDebugEvent(lpdebug_event->dwProcessId, lpdebug_event->dwThreadId, DBG_CONTINUE);
// wait a little bit before setting the mem bp again so the target program can get
// past the instruction that triggered the guard page violation. otherwise the target
// program gets stuck on the same instruction over and over. should play around with
// the amount of sleep time for optimal performance
Sleep(200);
SetMemoryBreakpoint(target_address);
continue;
case EXCEPTION_SINGLE_STEP:
GetCurrentThreadContext(offending_thread_ID, thread_context);
if (!ReadProcessMemory(target_handle, LPCVOID(thread_context.Eip), instruction_buffer, sizeof(instruction_buffer), &num_bytes_read))
{
std::cout << "Error in ReadProcessMemory(): " << GetLastError() << std::endl;
return 0;
}
tracer->SaveInstruction(instruction_buffer, offending_thread_ID, thread_context);
SetTrapFlag(offending_thread_ID);
break;
default:
//std::cout << "EXCEPTION_DEBUG_EVENT other than STATUS_GUARD_PAGE_VIOLATION or single step" << std::endl;
//std::cout << "debug event code: " << exception_record.ExceptionCode << std::endl;
break;
}
break;
case CREATE_THREAD_DEBUG_EVENT:
//std::cout << "create thread debug event" << std::endl;
/*
new_thread_handle = lpdebug_event->u.CreateProcessInfo.hThread;
new_thread_id = GetThreadId(new_thread_handle); // GetThreadId is fucking up, get error code, find out why
thread_handles.insert_or_assign(new_thread_id, new_thread_handle);
SetTrapFlag(new_thread_id);
*/
break;
default:
//std::cout << "DEBUG_EVENT other than EXCEPTION_DEBUG_EVENT" << std::endl;
//std::cout << "debug event code: " << lpdebug_event->dwDebugEventCode << std::endl;
break;
}
ContinueDebugEvent(lpdebug_event->dwProcessId, lpdebug_event->dwThreadId, DBG_CONTINUE);
}
CleanUpAndExit();
}
int Debugger::CleanUpAndExit()
{
RemoveMemoryBreakpoint();
DEBUG_EVENT debug_event;
LPDEBUG_EVENT lpdebug_event = &debug_event;
while (TRUE)
{
if (!WaitForDebugEvent(lpdebug_event, 2000)) break;
ContinueDebugEvent(lpdebug_event->dwProcessId, lpdebug_event->dwThreadId, DBG_CONTINUE);
}
return 1;
}
int Debugger::IsMemoryBreakpointHit(const DEBUG_EVENT& debug_event)
{
LPVOID access_address;
EXCEPTION_RECORD exception_record = debug_event.u.Exception.ExceptionRecord;
unsigned int i, num = exception_record.NumberParameters;
BOOL mem_breakpoint_hit = FALSE;
//std::cout << "STATUS_GUARD_PAGE_VIOLATION: Page guard hit" << std::endl;
for (i = 0; i < num; i++)
{
//std::cout << "ExceptionInformation[" << i << "]: " << std::hex << exception_record.ExceptionInformation[i] << std::endl;
}
// ExceptionInformation structure undefined for STATUS_GUARD_PAGE_VIOLATION
// Consider using PAGE_NOACCESS instead of PAGE_GUARD since
// ExceptionInformation for EXCEPTION_ACCESS_VIOLATION is defined.
access_address = (num > 0 ? (LPVOID) exception_record.ExceptionInformation[num - 1] : NULL);
if (access_address == target_address)
{
std::cout << "Memory breakpoint hit" << std::endl;
mem_breakpoint_hit = TRUE;
}
return mem_breakpoint_hit;
}
int Debugger::SetSoftBreakpoint(LPVOID target_address)
{
char orig_instruction_byte;
LPVOID lporig_instruction_byte = &orig_instruction_byte;
char int3 = '\xCC';
LPCVOID lpcint3 = &int3;
if (!ReadProcessMemory(target_handle, target_address, lporig_instruction_byte, 1, NULL))
{
std::cout << "Error in ReadProcessMemory(): " << GetLastError() << std::endl;
return 0;
}
soft_breakpoint_list[target_address] = orig_instruction_byte;
if (!WriteProcessMemory(target_handle, target_address, lpcint3, 1, NULL))
{
std::cout << "Error in WriteProcessMemory(): " << GetLastError() << std::endl;
return 0;
}
return 1;
}
LPVOID Debugger::GetInstructionPointer(const DEBUG_EVENT& debug_event)
{
CONTEXT thread_context;
LPCONTEXT lpthread_context = &thread_context;
LPVOID instruction_pointer;;
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, debug_event.dwThreadId);
if (!thread_handle)
{
std::cout << "Error in OpenThread(): " << GetLastError() << std::endl;
return 0;
}
thread_context.ContextFlags = CONTEXT_ALL;
if (!GetThreadContext(thread_handle, lpthread_context))
{
std::cout << "Error in GetThreadContext(): " << GetLastError() << std::endl;
return 0;
}
// x86 specific
instruction_pointer = (LPVOID) lpthread_context->Eip;
return instruction_pointer;
}
int Debugger::SetTrapFlag(DWORD thread_id)
{
HANDLE thread_handle;
CONTEXT thread_context;
if (thread_handles.find(thread_id) != thread_handles.end())
{
thread_handle = thread_handles[thread_id];
}
else
{
thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
if (!thread_handle)
{
std::cout << "Error in OpenThread(): " << GetLastError() << std::endl;
return 0;
}
thread_handles.insert_or_assign(thread_id, thread_handle);
}
thread_context.ContextFlags = CONTEXT_CONTROL;
if (!GetThreadContext(thread_handle, &thread_context))
{
std::cout << "Error in GetThreadContext(): " << GetLastError() << std::endl;
return 0;
}
// x86 specific
thread_context.EFlags |= 0x100;
if (!SetThreadContext(thread_handle, &thread_context))
{
std::cout << "Error in SetThreadContext(): " << GetLastError() << std::endl;
}
return 1;
}
int Debugger::StartRecordingRegisterModifications()
{
// get handle for each thread
// set single step breakpoints on each one
ListProcessThreads(target_pid);
for (auto & thread_ID : target_thread_IDs)
{
std::cout << "setting trap flag on thread id: " << thread_ID << std::endl;
if (!SetTrapFlag(thread_ID)) std::cout << "error setting trap flag: " << GetLastError() << std::endl;
}
return 1;
}
int Debugger::GetCurrentThreadContext(DWORD thread_id, CONTEXT &thread_context)
{
// close all these handles
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
if (!thread_handle)
{
std::cout << "Error in OpenThread(): " << GetLastError() << std::endl;
return 0;
}
thread_context.ContextFlags = CONTEXT_ALL;
if (!GetThreadContext(thread_handle, &thread_context))
{
std::cout << "Error in GetThreadContext(): " << GetLastError() << std::endl;
return 0;
}
return 1;
}
/*
int Debugger::SaveRegisterChanges(DWORD thread_id, const CONTEXT &thread_context)
{
std::map<std::string, DWORD> modifications;
if (thread_context.Eip != saved_thread_context.Eip) modifications["Eip"] = thread_context.Eip;
if (thread_context.Eax != saved_thread_context.Eax) modifications["Eax"] = thread_context.Eax;
if (thread_context.Ebx != saved_thread_context.Ebx) modifications["Ebx"] = thread_context.Ebx;
if (thread_context.Ecx != saved_thread_context.Ecx) modifications["Ecx"] = thread_context.Ecx;
if (thread_context.Edx != saved_thread_context.Edx) modifications["Edx"] = thread_context.Edx;
if (thread_context.Edi != saved_thread_context.Edi) modifications["Edi"] = thread_context.Edi;
if (thread_context.Esi != saved_thread_context.Esi) modifications["Esi"] = thread_context.Esi;
if (modifications.size() > 1)
{
const unsigned int MAX_RECORD_LENGTH = 50;
if (all_threads_register_changes[thread_id].size() > MAX_RECORD_LENGTH)
{
all_threads_register_changes[thread_id].erase(all_threads_register_changes[thread_id].begin());
}
all_threads_register_changes[thread_id].push_back(modifications);
}
return 1;
}
*/
/*
int Debugger::PrintRegisterChanges(DWORD thread_id)
{
DWORD Eip_value;
std::cout << "trace for thread: " << thread_id << std::endl;
for (auto &instruction_map : all_threads_register_changes[thread_id])
{
Eip_value = instruction_map["Eip"];
std::cout << "Eip: " << Eip_value << ", ";
for (auto ®ister_modification : instruction_map)
{
if (register_modification.first != "Eip")
{
std::cout << register_modification.first << ": " << std::hex << register_modification.second << ", ";
}
}
std::cout << std::endl;
}
return 1;
}
*/
/*
int Debugger::PrintRunTrace(DWORD thread_id)
{
DWORD Eip_value;
cs_insn insn;
std::map<std::string, DWORD> modifications;
std::cout << "trace for thread: " << thread_id << std::endl;
for (auto &instruction_tuple : all_threads_saved_instructions[thread_id])
{
std::tie(Eip_value, insn, modifications) = instruction_tuple;
std::cout << "0x" << std::hex << Eip_value << "\t" << insn.mnemonic << " " << insn.op_str << "\tmods: ";
for (auto &modification : modifications)
{
std::cout << modification.first << " " << std::hex << modification.second << ", ";
}
std::cout << "\n\n";
}
return 1;
}
*/
// taken from msdn
BOOL Debugger::ListProcessThreads(DWORD dwOwnerPID)
{
HANDLE hThreadSnap = INVALID_HANDLE_VALUE;
THREADENTRY32 te32;
// Take a snapshot of all running threads
hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return(FALSE);
// Fill in the size of the structure before using it.
te32.dwSize = sizeof(THREADENTRY32);
// Retrieve information about the first thread,
// and exit if unsuccessful
if (!Thread32First(hThreadSnap, &te32))
{
std::cout << TEXT("Thread32First") << std::endl; // Show cause of failure
CloseHandle(hThreadSnap); // Must clean up the snapshot object!
return(FALSE);
}
do
{
if (te32.th32OwnerProcessID == dwOwnerPID)
{
// store thread ID
target_thread_IDs.push_back(te32.th32ThreadID);
}
} while (Thread32Next(hThreadSnap, &te32));
// Don't forget to clean up the snapshot object.
CloseHandle(hThreadSnap);
return(TRUE);
} | [
"nickcollisson@gmail.com"
] | nickcollisson@gmail.com |
8fb815857b5ec815732c02a8e125e7fe14f323e4 | 7105ea0200141ac566fbf635f0c10df509612580 | /test/itemtest.cpp | 6f7217b1b912289563ee0c0cd380faa6e330eea1 | [] | no_license | nessss/spacelike | 3755c1867fbe11be511545f14c8e90f0e5a284ae | d4750165b682803e0569e6d3f22b67b28feb3864 | refs/heads/master | 2020-07-15T13:15:27.266787 | 2016-12-17T02:03:29 | 2016-12-17T02:03:29 | 67,827,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,394 | cpp | #include <string>
#include "catch.hpp"
#include "../src/item.h"
TEST_CASE( "item constructor", "[Item]" )
{
SECTION( "default constructor" )
{
Item defaultItem;
CHECK( defaultItem.name() == "" );
CHECK( defaultItem.description() == "" );
CHECK( defaultItem.group() == Item::Group::None );
CHECK( defaultItem.weight() == 0 );
CHECK( defaultItem.value() == 0 );
}
SECTION( "name only" )
{
std::string itemName = "Flux capacitor";
Item fluxCapacitor( itemName );
CHECK( fluxCapacitor.name() == itemName );
CHECK( fluxCapacitor.description() == "" );
CHECK( fluxCapacitor.group() == Item::Group::None );
CHECK( fluxCapacitor.weight() == 0 );
CHECK( fluxCapacitor.value() == 0 );
}
SECTION( "name and description" )
{
std::string itemName = "MacGuffin";
std::string itemDescription = "An ominous glow emanates from this briefcase";
Item macGuffin(
itemName,
itemDescription );
CHECK( macGuffin.name() == itemName );
CHECK( macGuffin.description() == itemDescription );
CHECK( macGuffin.group() == Item::Group::None );
CHECK( macGuffin.weight() == 0 );
CHECK( macGuffin.value() == 0 );
}
SECTION( "name, description, group" )
{
std::string itemName = "Slime mold";
std::string itemDescription = "A delcious dungeon staple";
Item::Group itemGroup = Item::Group::Consumable;
Item slimeMold(
itemName,
itemDescription,
itemGroup );
CHECK( slimeMold.name() == itemName );
CHECK( slimeMold.description() == itemDescription );
CHECK( slimeMold.group() == itemGroup );
CHECK( slimeMold.weight() == 0 );
CHECK( slimeMold.value() == 0 );
}
SECTION( "name, description, group, weight" )
{
std::string itemName = "Slime mold";
std::string itemDescription = "A delcious dungeon staple";
Item::Group itemGroup = Item::Group::Consumable;
int weight = 5;
Item slimeMold(
itemName,
itemDescription,
itemGroup,
weight );
CHECK( slimeMold.name() == itemName );
CHECK( slimeMold.description() == itemDescription );
CHECK( slimeMold.group() == itemGroup );
CHECK( slimeMold.weight() == weight );
CHECK( slimeMold.value() == 0 );
}
SECTION( "all constructor arguments" )
{
std::string itemName = "Slime mold";
std::string itemDescription = "A delcious dungeon staple";
Item::Group itemGroup = Item::Group::Consumable;
int weight = 5;
int value = 15;
Item slimeMold(
itemName,
itemDescription,
itemGroup,
weight,
value );
CHECK( slimeMold.name() == itemName );
CHECK( slimeMold.description() == itemDescription );
CHECK( slimeMold.group() == itemGroup );
CHECK( slimeMold.weight() == weight );
CHECK( slimeMold.value() == value );
}
}
TEST_CASE( "item fields", "[Item]" )
{
SECTION( "name" )
{
Item doppelgangerCorpse;
std::string slimeMoldName = "Slime mold";
std::string fluxCapacitorName = "Flux capacitor";
std::string macGuffinName = "MacGuffin";
CHECK( doppelgangerCorpse.name() == "" );
doppelgangerCorpse.name( slimeMoldName );
CHECK( doppelgangerCorpse.name() == slimeMoldName );
doppelgangerCorpse.name( fluxCapacitorName );
CHECK( doppelgangerCorpse.name() == fluxCapacitorName );
doppelgangerCorpse.name( macGuffinName );
CHECK( doppelgangerCorpse.name() == macGuffinName );
}
SECTION( "description" )
{
Item doppelgangerCorpse;
std::string slimeMoldDescription = "A mouthwatering dungeon staple";
std::string fluxCapacitorDescription = "The key to the mysteries of the universe";
std::string macGuffinDescription = "An ominous glow emanates from this briefcase";
CHECK( doppelgangerCorpse.description() == "" );
doppelgangerCorpse.description( slimeMoldDescription );
CHECK( doppelgangerCorpse.description() == slimeMoldDescription );
doppelgangerCorpse.description( fluxCapacitorDescription );
CHECK( doppelgangerCorpse.description() == fluxCapacitorDescription );
doppelgangerCorpse.description( macGuffinDescription );
CHECK( doppelgangerCorpse.description() == macGuffinDescription );
}
SECTION( "group" )
{
Item doppelgangerCorpse;
Item::Group slimeMoldGroup = Item::Group::Consumable;
Item::Group fluxCapacitorGroup = Item::Group::Craftable;
Item::Group macGuffinGroup = Item::Group::Quest;
CHECK( doppelgangerCorpse.group() == Item::Group::None );
doppelgangerCorpse.group( slimeMoldGroup );
CHECK( doppelgangerCorpse.group() == slimeMoldGroup );
doppelgangerCorpse.group( fluxCapacitorGroup );
CHECK( doppelgangerCorpse.group() == fluxCapacitorGroup );
doppelgangerCorpse.group( macGuffinGroup );
CHECK( doppelgangerCorpse.group() == macGuffinGroup );
}
}
| [
"karplusstrong@gmail.com"
] | karplusstrong@gmail.com |
edd658797931c098398f1ac7980f2b67ba86dd01 | 736d389dde3020f1e06b034b2224bed2b6dfae9c | /engine/platform/platform.cc | b87abaac121cdab0396b82d9f9067326b07517a8 | [
"MIT"
] | permissive | jamesu/korkscript | 08396ed9999c01d6ece6ef77186b4856dbb4fd27 | 14ac1acc9d766173495816d181d26fd3bd530e94 | refs/heads/master | 2022-12-20T19:43:04.670210 | 2020-09-03T15:41:39 | 2020-09-03T15:41:39 | 292,612,109 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,258 | cc | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "console/console.h"
#include "console/consoleTypes.h"
#include "platform/threads/mutex.h"
//Added for the cprintf below
#include <stdarg.h>
#include <stdio.h>
S32 sgBackgroundProcessSleepTime = 200;
S32 sgTimeManagerProcessInterval = 0;
void Platform::initConsole()
{
Con::addVariable("Pref::backgroundSleepTime", TypeS32, &sgBackgroundProcessSleepTime);
Con::addVariable("Pref::timeManagerProcessInterval", TypeS32, &sgTimeManagerProcessInterval);
}
S32 Platform::getBackgroundSleepTime()
{
return sgBackgroundProcessSleepTime;
}
void Platform::cprintf( const char* str )
{
printf( "%s \n", str );
}
bool Platform::hasExtension(const char* pFilename, const char* pExtension)
{
// Sanity!
AssertFatal( pFilename != NULL, "Filename cannot be NULL." );
AssertFatal( pExtension != NULL, "Extension cannot be NULL." );
// Find filename length.
const U32 filenameLength = dStrlen( pFilename );
// Find extension length.
const U32 extensionLength = dStrlen( pExtension );
// Skip if extension is longer than filename.
if ( extensionLength >= filenameLength )
return false;
// Check if extension exists.
return dStricmp( pFilename + filenameLength - extensionLength, pExtension ) == 0;
}
/*! @defgroup PlatformFunctions Platform
@ingroup TorqueScriptFunctions
@{
*/
//-----------------------------------------------------------------------------
/*! Get the local time
@return the local time formatted as: monthday/month/year hour/minute/second
*/
ConsoleFunction( getLocalTime, const char*, 1, 1, "")
{
char* buf = Con::getReturnBuffer(128);
Platform::LocalTime lt;
Platform::getLocalTime(lt);
dSprintf(buf, 128, "%d/%d/%d %02d:%02d:%02d",
lt.monthday,
lt.month + 1,
lt.year + 1900,
lt.hour,
lt.min,
lt.sec);
return buf;
}
/*! @} */ // group PlatformFunctions
| [
"jamesu@gmail.com"
] | jamesu@gmail.com |
04344e214f0de3a0c7f681729c339f03ef4133d2 | f1dcbf6f42794fc339887467aca3ea99278031eb | /Arduino/motors_cmds/motors_cmds.ino | 5e3d5f2d42721c7ee39b09b452a0760e0f53fe17 | [
"MIT"
] | permissive | ScifestJoensuu/theater-robot | 78d8631e791f5b42fbc7397f39b5ff12951c19bd | deb282709b4c3db89e8fbde81596754d117d21cf | refs/heads/master | 2020-06-05T08:56:39.253659 | 2015-08-31T11:44:29 | 2015-08-31T11:44:29 | 22,830,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | ino |
// Adafruit motor shield library:
// http://www.adafruit.com/product/81
#include <AFMotor.h>
AF_DCMotor ml(1);
AF_DCMotor mr(2);
void setup() {
Serial.begin(9600);
Serial.println("> Setting up motors..");
ml.setSpeed(200);
mr.setSpeed(200);
ml.run(RELEASE);
mr.run(RELEASE);
}
void loop() {
//drive a square
driveFwd();
delay(1000);
turnRight();
delay(500);
stopMotors();
}
void driveFwd() {
ml.run(FORWARD);
mr.run(FORWARD);
}
void driveBwd() {
ml.run(BACKWARD);
mr.run(BACKWARD);
}
void turnRight() {
ml.run(FORWARD);
mr.run(BACKWARD);
}
void turnLeft() {
ml.run(BACKWARD);
mr.run(FORWARD);
}
void stopMotors() {
ml.run(RELEASE);
mr.run(RELEASE);
}
| [
"mlaamane@uef.fi"
] | mlaamane@uef.fi |
03bfb345199bbc3a50925e9146c5a91c9e3ad46f | 5af68d43b182694e6955be8de0a84ecea20c078d | /BlackCat.Physics/Physics/Fundation/bcMaterial.h | 65b622bd8ceef97bc695dad44e8be907af609c92 | [] | no_license | coder965/BlackCat-Engine | 1ed5c3d33c67c537eaa1ae7d1afe40192296e03f | a692f95d5c5f0c86ababa0c5ecc06531f569f500 | refs/heads/master | 2020-03-18T21:41:31.035603 | 2017-04-15T16:53:26 | 2017-04-15T16:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,776 | h | // [11/30/2016 MRB]
#pragma once
#include "CorePlatform/bcType.h"
#include "Physics/bcPhysicsApi.h"
#include "Physics/bcPhysicsReference.h"
#include "Physics/bcPhysicsRef.h"
namespace black_cat
{
namespace physics
{
using bc_material_index = bcUINT16;
template< bc_physics_api TApi >
struct bc_platform_material_pack
{
};
template< bc_physics_api TApi >
class bc_platform_material : public bc_platform_physics_reference<TApi>
{
public:
using platform_pack = bc_platform_material_pack< TApi >;
public:
bc_platform_material();
bc_platform_material(const bc_platform_material&) noexcept;
~bc_platform_material();
bc_platform_material& operator=(const bc_platform_material&) noexcept;
bcFLOAT get_static_friction() const noexcept;
/**
* \brief Sets the coefficient of static friction.
* \param p_friction Coefficient of static friction. Range: [0, PX_MAX_F32)
*/
void set_static_friction(bcFLOAT p_friction) noexcept;
bcFLOAT get_dynamic_friction() const noexcept;
/**
* \brief Sets the coefficient of dynamic friction.
* \param p_friction Coefficient of dynamic friction. Range: [0, PX_MAX_F32)
*/
void set_dynamic_friction(bcFLOAT p_friction) noexcept;
bcFLOAT get_restitution() const noexcept;
/**
* \brief Sets the coefficient of restitution.
* \param p_restitution Coefficient of restitution. Range: [0,1]
*/
void set_restitution(bcFLOAT p_restitution) noexcept;
bool is_valid() const noexcept override;
platform_pack& get_platform_pack()
{
return m_pack;
}
protected:
private:
platform_pack m_pack;
};
using bc_material = bc_platform_material< g_current_physics_api >;
using bc_material_ref = bc_physics_ref< bc_material >;
}
} | [
"mohammad.r.barzegar@gmail.com"
] | mohammad.r.barzegar@gmail.com |
8be079e286d1d6e1d0d7cd8beecc89df8b072769 | b30b65994865ce9212da5b30834b15ea9dbb9103 | /URIOJ/C++/1217.cpp | 30aee20d3849e061f9d9dc1721607b926dff2c87 | [] | no_license | uthantvicentin/Competitive-Programming | 3d06b9cac1bf76a166f8009b7898fafdbca726bf | 6072753df64da0fa76a95fd30c9c65d89cd30a73 | refs/heads/master | 2021-09-08T19:54:18.510359 | 2021-09-05T13:14:12 | 2021-09-05T13:14:12 | 178,067,690 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
string str;
int n;
double k,soma = 0;
int somakg = 0;
cin >> n;
std::cout << std::fixed << std::showpoint;
std::cout << std::setprecision(2);
for(int i = 1 ; i <= n ; ++i){
cin >> k;
soma += k;
cin.ignore();
getline(cin,str);
istringstream iss(str);
vector<string> results((istream_iterator<string>(iss)),
istream_iterator<string>());
somakg += results.size();
cout << "day " << i << ": " << results.size() << " kg\n";
}
cout << (double(somakg)/n) << " kg by day\n";
cout << "R$ " << (soma/n) << " by day\n";
return 0;
}
| [
"uthantvicentin@gmail.com"
] | uthantvicentin@gmail.com |
943fb26fd905a51db21fcbcdc9ca91fb495f57ac | 384cce818f2f7ae6af8d4230e4adb130720c4996 | /Source/UA2/player_ball.cpp | 516947894fba18982fe830ce25799154b1397a12 | [] | no_license | jwhite510/UA2Game2 | 8a6e01f32ed2b50caf62ce65573a35978d2d5c35 | 996ec3743fe5707227a4b9ae114e7db5c4377bcf | refs/heads/master | 2022-04-09T03:53:34.320936 | 2020-02-09T18:40:28 | 2020-02-09T18:40:28 | 235,220,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,325 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "player_ball.h"
#include "Components/StaticMeshComponent.h"
#include "Movement.h"
#include "DrawDebugHelpers.h"
// Sets default values
Aplayer_ball::Aplayer_ball()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void Aplayer_ball::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void Aplayer_ball::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// FVector ForceLocation = Body->GetComponentLocation();
// Body->AddForceAtLocation(FVector(Direction*ForceMovement,0.,0), ForceLocation);
// FRotator current_rotation = Wheel_LF->GetRelativeRotation();
// float Current_Pitch = current_rotation.Pitch;
// float Current_Yaw = current_rotation.Yaw;
// float Current_Roll = current_rotation.Roll;
wheel_pitch += 90*DeltaTime;
if(wheel_pitch > 360.){
wheel_pitch = 0.;
}
FRotator NewRotation = FRotator();
NewRotation.Pitch = wheel_pitch;
NewRotation.Yaw = 0;
NewRotation.Roll = 90;
UE_LOG(LogTemp, Warning, TEXT("wheel_pitch %f"), wheel_pitch);
// current_rotation.Pitch += 10.*DeltaTime;
Wheel_LF->SetRelativeRotation(NewRotation);
Wheel_2->SetRelativeRotation(NewRotation);
Wheel_3->SetRelativeRotation(NewRotation);
Wheel_4->SetRelativeRotation(NewRotation);
}
// Called to bind functionality to input
void Aplayer_ball::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void Aplayer_ball::MoveForward(float Value)
{
// UE_LOG(LogTemp, Warning, TEXT("MoveForward called %f"), Value);
Direction = Value;
}
void Aplayer_ball::GetComponents(UStaticMeshComponent* Body, UStaticMeshComponent* Wheel_LF, UStaticMeshComponent* Wheel_2, UStaticMeshComponent* Wheel_3, UStaticMeshComponent* Wheel_4)
{
this->Body = Body;
this->Wheel_LF = Wheel_LF;
this->Wheel_2 = Wheel_2;
this->Wheel_3 = Wheel_3;
this->Wheel_4 = Wheel_4;
}
| [
"jonathonwhite@protonmail.com"
] | jonathonwhite@protonmail.com |
31fce9880b773986413f7c51c4f52a9069d978f9 | 35b929181f587c81ad507c24103d172d004ee911 | /SrcLib/core/fwAtomsPatch/include/fwAtomsPatch/PatchingManager.hpp | 8c9e805a3e14046590e0920444d7ad419618fb4b | [] | no_license | hamalawy/fw4spl | 7853aa46ed5f96660123e88d2ba8b0465bd3f58d | 680376662bf3fad54b9616d1e9d4c043d9d990df | refs/heads/master | 2021-01-10T11:33:53.571504 | 2015-07-23T08:01:59 | 2015-07-23T08:01:59 | 50,699,438 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | hpp | /* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#ifndef __FWATOMSPATCH_PATCHINGMANAGER_HPP__
#define __FWATOMSPATCH_PATCHINGMANAGER_HPP__
#include <fwCore/macros.hpp>
#include "fwAtomsPatch/VersionsGraph.hpp"
#include "fwAtomsPatch/config.hpp"
namespace fwAtoms
{
class Object;
}
namespace fwAtomsPatch
{
/**
* @class PatchingManager
* @brief Manages object patching.
*
* To be used, PatchingManager requires that available contexts and versions are loaded into
* the graph of versions through the VersionsManager.
*/
class FWATOMSPATCH_CLASS_API PatchingManager
{
public:
/// Default constructor
FWATOMSPATCH_API PatchingManager(SPTR(::fwAtoms::Object) object);
/// Default destructor
FWATOMSPATCH_API ~PatchingManager();
/**
* @brief Transforms the object to the given version.
* @pre Given version must be known by the VersionsManager
*
* @throw ::fwAtomsPatch::exceptions::MissingInformation if an information about patching is missing
* @throw ::fwAtomsPatch::exceptions::ImpossibleConversion if there is no patch available to transform an object
*/
FWATOMSPATCH_API ::fwAtoms::Object::sptr transformTo(const std::string& newVersion);
protected:
/// Object that we want to patch
SPTR(::fwAtoms::Object) m_object;
};
}
#endif //__FWATOMSPATCH_PATCHINGMANAGER_HPP__
| [
"fbridault@IRCAD.FR"
] | fbridault@IRCAD.FR |
0d6e41d696e2130dc78387e1d55b9166a4ea6e5b | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /include/sicInfo.h | 6dfb07846d8c536e99b4cb9da0aeb22fd30e2087 | [] | no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | h | #ifndef SICINFO_H
#define SICINFO_H
#include <string>
#include <vector>
#include <sys/stat.h>
#include <sys/types.h>
#include "chromatogram.h"
#include "proRataParameters.h"
#include "directoryStructure.h"
#include "idData.h"
#include "msData.h"
#include "isotopologue.h"
using namespace std;
// this is the number of the chromatogram in a xic file
const int CHRO_COUNT = 100;
class SICinfo
{
public:
SICinfo();
~SICinfo();
/*
* set the filenames for the ID files and the MS files, which
* is stored in sIDfilename and vsMZfilename
* the ID filename is sIDfilenameInput
* the MS filenames are all files with extension name of mzXML/mzData
* in the working directory.
*/
bool setFilename( string sIDfilenameInput );
/*
* instantiate the IDdata, MSdata and Isotopologue classes
* creat extract chromatograms and write them into the file one by one
*/
bool process();
private:
/*
* given an Identification, a chromatogram is extracted from the current MS file that pMSdata is pointing to
* its identifier is the parameter iIdentifier, the chromatogram is returned by reference
*/
bool extractChromatogram( const Identification & idInput, string sMSfilenameInput, int iIdentifier, Chromatogram & chroOutput );
/*
* compose a Root element start tag for the output file, sXicFilename
* and then write it to the file.
*/
bool writeRootElementStartTag( string sXicFilename, int iFirstIdentifier, int iLastIdentifier );
/*
* ID file's filename
*/
string sIDfilename;
/*
* the pointer to the ID data object for processing the given ID file
*/
IDdata* pIDdata;
/*
* the mzXML/mzData filenames in the working directory
*/
vector< string > vsMZfilename;
/*
* a pointer to an MS data object
* during process(), this pointer is moved down the list of MZ files
*/
MSdata * pMSdata;
/*
* a pointers to Isotopologues objects
*/
vector< Isotopologue * > vpIsotopologue;
};
#endif //SICINFO_H
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
] | chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a |
48f2434ad08dfd6094af0c38e194621fe1125210 | 789900f80d993fe1eb0e01387173ebdcc54007ba | /include/hogl/detail/compiler.hpp | 803a4d380b7952e8b87ffc9ae2e885bebf93ea7f | [
"BSD-2-Clause"
] | permissive | kobi-ca/hogl | 01292b783b9d5c6b3e1be78cac1c7b39d4974790 | 19cd7262ed22a46cc06346d9d592ff278db5266b | refs/heads/master | 2020-03-28T08:40:58.271548 | 2017-07-11T20:54:59 | 2018-03-29T00:19:39 | 147,981,594 | 0 | 0 | BSD-2-Clause | 2018-09-09T00:58:24 | 2018-09-09T00:58:24 | null | UTF-8 | C++ | false | false | 2,234 | hpp | /*
Copyright (c) 2015, Max Krasnyansky <max.krasnyansky@gmail.com>
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 HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file hogl/detail/compiler.h
* Compiler related macros, shortcuts, etc.
*/
#ifndef HOGL_DETAIL_COMPILER_HPP
#define HOGL_DETAIL_COMPILER_HPP
// Note: Currently supported compilers are:
// GCC 4.0 and above
// Intel C++ compiler
// Clang 3.0 and above
// Branch likelihood hints
#define hogl_likely(x) __builtin_expect(!!(x), 1)
#define hogl_unlikely(x) __builtin_expect(!!(x), 0)
// Forced inlining
#define hogl_force_inline inline __attribute__ ((always_inline))
// Forced out of lining
#define hogl_force_outofline __attribute__ ((noinline))
// Don't warn about unused function
#define hogl_maybe_unused __attribute__ ((unused))
// Frequently used function
#ifdef __clang__
#define hogl_hot_path
#else
#define hogl_hot_path __attribute__ ((hot))
#endif // clang
#endif // HOGL_DETAIL_COMPILER_HPP
| [
"max.krasnyansky@gmail.com"
] | max.krasnyansky@gmail.com |
ac9a57ea82e175a005d0abb13b7cbcd381600931 | 8d539ced39960119c418907075b631cec18ca399 | /CSES/240-IncreasingArray.cpp | ecf559e1ad4477f005859f4883fc041645f9e4ba | [
"MIT"
] | permissive | lucastarche/aotd | d27eed7414c11ce1a0a18c2459b800e9cdf91eef | e501a1f27fc48508d24eac461308aaa2e56a23cf | refs/heads/master | 2023-07-19T03:56:06.845259 | 2021-09-12T12:14:56 | 2021-09-12T12:14:56 | 294,989,043 | 3 | 1 | null | 2020-12-16T13:58:42 | 2020-09-12T17:06:06 | C++ | UTF-8 | C++ | false | false | 694 | cpp | //Increasing array
//Problem: Given an array of n numbers, find the number of times you gotta increase a number to get a non decreasing array.
//Solution: We can keep track of the previous number. If the new number if bigger than the current one, we change the current.
//Else, we add their difference to the result.
//Runtime: O(n)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long result = 0, curr = 0;
cin >> curr;
for (int i = 0; i < n - 1; i++) {
long long temp = 0;
cin >> temp;
if (temp > curr)
curr = temp;
else
result += curr - temp;
}
cout << result << '\n';
} | [
"lucastarche@gmail.com"
] | lucastarche@gmail.com |
c7ca0d5e80702977d8fa93f00e2db0b8d743ffbf | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/llvm/3.6.2/include/llvm/IR/DebugLoc.h | 86e64417099d0e15b8d2753522f7c4f46779e5a0 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 3,974 | h | //===- DebugLoc.h - Debug Location Information ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a number of light weight data structures used
// to describe and track debug location information.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_IR_DEBUGLOC_H
#define LLVM_IR_DEBUGLOC_H
#include "llvm/IR/TrackingMDRef.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class LLVMContext;
class raw_ostream;
class MDNode;
/// DebugLoc - Debug location id. This is carried by Instruction, SDNode,
/// and MachineInstr to compactly encode file/line/scope information for an
/// operation.
class DebugLoc {
TrackingMDNodeRef Loc;
public:
DebugLoc() {}
DebugLoc(DebugLoc &&X) : Loc(std::move(X.Loc)) {}
DebugLoc(const DebugLoc &X) : Loc(X.Loc) {}
DebugLoc &operator=(DebugLoc &&X) {
Loc = std::move(X.Loc);
return *this;
}
DebugLoc &operator=(const DebugLoc &X) {
Loc = X.Loc;
return *this;
}
/// \brief Check whether this has a trivial destructor.
bool hasTrivialDestructor() const { return Loc.hasTrivialDestructor(); }
/// get - Get a new DebugLoc that corresponds to the specified line/col
/// scope/inline location.
static DebugLoc get(unsigned Line, unsigned Col, MDNode *Scope,
MDNode *InlinedAt = nullptr);
/// getFromDILocation - Translate the DILocation quad into a DebugLoc.
static DebugLoc getFromDILocation(MDNode *N);
/// getFromDILexicalBlock - Translate the DILexicalBlock into a DebugLoc.
static DebugLoc getFromDILexicalBlock(MDNode *N);
/// isUnknown - Return true if this is an unknown location.
bool isUnknown() const { return !Loc; }
unsigned getLine() const;
unsigned getCol() const;
/// getScope - This returns the scope pointer for this DebugLoc, or null if
/// invalid.
MDNode *getScope() const;
MDNode *getScope(const LLVMContext &) const { return getScope(); }
/// getInlinedAt - This returns the InlinedAt pointer for this DebugLoc, or
/// null if invalid or not present.
MDNode *getInlinedAt() const;
MDNode *getInlinedAt(const LLVMContext &) const { return getInlinedAt(); }
/// getScopeAndInlinedAt - Return both the Scope and the InlinedAt values.
void getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA) const;
void getScopeAndInlinedAt(MDNode *&Scope, MDNode *&IA,
const LLVMContext &) const {
return getScopeAndInlinedAt(Scope, IA);
}
/// getScopeNode - Get MDNode for DebugLoc's scope, or null if invalid.
MDNode *getScopeNode() const;
MDNode *getScopeNode(const LLVMContext &) const { return getScopeNode(); }
// getFnDebugLoc - Walk up the scope chain of given debug loc and find line
// number info for the function.
DebugLoc getFnDebugLoc() const;
DebugLoc getFnDebugLoc(const LLVMContext &) const {
return getFnDebugLoc();
}
/// getAsMDNode - This method converts the compressed DebugLoc node into a
/// DILocation compatible MDNode.
MDNode *getAsMDNode() const;
MDNode *getAsMDNode(LLVMContext &) const { return getAsMDNode(); }
bool operator==(const DebugLoc &DL) const { return Loc == DL.Loc; }
bool operator!=(const DebugLoc &DL) const { return !(*this == DL); }
void dump() const;
void dump(const LLVMContext &) const { dump(); }
/// \brief prints source location /path/to/file.exe:line:col @[inlined at]
void print(raw_ostream &OS) const;
void print(const LLVMContext &, raw_ostream &OS) const { print(OS); }
};
} // end namespace llvm
#endif /* LLVM_SUPPORT_DEBUGLOC_H */
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
fb474f4eccefd856bda576c2abb9ac48139672df | ac5ad059f6c31c1a7729650903cfc6101eb8a7f0 | /main5-1.cpp | b1a9fbeda6d38dffd3b8dea6e1ae4848601c8e6d | [] | no_license | wangxb96/datastructure | 8a6fc6cc47b759e62cccaadfcafba442af37c45c | 4a3e7950a1c15cff7b8ab21ae3051bfc1db86fe9 | refs/heads/master | 2022-02-18T02:17:14.825992 | 2019-09-20T11:17:08 | 2019-09-20T11:17:08 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,163 | cpp | #include"c1.h"
typedef int ElemType;
#include"c5-1.h"//数组的动态顺序存储结构
#include"bo5-1.cpp"
int main()
{
Array A;
int i,j,k,dim=3,bound1=3,bound2=4,bound3=2;//A[3][4][2]数组
ElemType e;
InitArray(A,dim,bound1,bound2,bound3);//构造3×4×2的三维数组A
printf("A.bounds=");
for(i=0;i<dim;i++)//顺序输出A.bounds
printf("%d",*(A.bounds+i));
printf("\nA.constats=");
for(i=0;i<dim;i++)//顺序输出A.constants
printf("%d",*(A.constants+i));
printf("\n%d页%d行%d列矩阵元素如下:\n",bound1,bound2,bound3);
for(i=0;i<bound1;i++)
{
for(j=0;j<bound2;j++)
{
for(k=0;k<bound3;k++)
{
Assign(A,i*100+j*10+k,i,j,k);//将i×100+j×10+k赋值给A[i][j][k]
Value(e,A,i,j,k);//将A[i][j][k]的值赋给e
printf("A[%d][%d][%d]=%2d",i,j,k,e);//输出A[i][j][k]
}
printf("\n");
}
printf("\n");
}
printf("A.base=\n");
for(i=0;i<bound1*bound2*bound3;i++)//顺序输出A.base
{
printf("%4d+",*(A.base+i));
if(i%(bound2*bound3)==bound2*bound3-1)
printf("\n");
}
printf("A.dim=%d\n",A.dim);
DestroyArray(A);
}
| [
"noreply@github.com"
] | noreply@github.com |
b3a4fbc66026181b4acfe0f4d696b6e5689f876a | 019b1b4fc4a0c8bf0f65f5bec2431599e5de5300 | /chrome/browser/safe_browsing/ui_manager.h | 18b8702db37b8914759a7a47ad7dfba83d5ea30c | [
"BSD-3-Clause"
] | permissive | wyrover/downloader | bd61b858d82ad437df36fbbaaf58d293f2f77445 | a2239a4de6b8b545d6d88f6beccaad2b0c831e07 | refs/heads/master | 2020-12-30T14:45:13.193034 | 2017-04-23T07:39:04 | 2017-04-23T07:39:04 | 91,083,169 | 1 | 2 | null | 2017-05-12T11:06:42 | 2017-05-12T11:06:42 | null | UTF-8 | C++ | false | false | 6,895 | h | // 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.
//
// The Safe Browsing service is responsible for downloading anti-phishing and
// anti-malware tables and checking urls against them.
#ifndef CHROME_BROWSER_SAFE_BROWSING_UI_MANAGER_H_
#define CHROME_BROWSER_SAFE_BROWSING_UI_MANAGER_H_
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "components/safe_browsing_db/hit_report.h"
#include "components/safe_browsing_db/util.h"
#include "content/public/browser/browser_thread.h"
#include "url/gurl.h"
namespace base {
class Thread;
} // namespace base
namespace content {
class NavigationEntry;
} // namespace content
namespace net {
class SSLInfo;
} // namespace net
namespace safe_browsing {
class SafeBrowsingService;
// Construction needs to happen on the main thread.
class SafeBrowsingUIManager
: public base::RefCountedThreadSafe<SafeBrowsingUIManager> {
public:
// Passed a boolean indicating whether or not it is OK to proceed with
// loading an URL.
typedef base::Callback<void(bool /*proceed*/)> UrlCheckCallback;
// Structure used to pass parameters between the IO and UI thread when
// interacting with the blocking page.
struct UnsafeResource {
UnsafeResource();
UnsafeResource(const UnsafeResource& other);
~UnsafeResource();
// Returns true if this UnsafeResource is a main frame load that was blocked
// while the navigation is still pending. Note that a main frame hit may not
// be blocking, eg. client side detection happens after the load is
// committed.
bool IsMainPageLoadBlocked() const;
// Returns the NavigationEntry for this resource (for a main frame hit) or
// for the page which contains this resource (for a subresource hit).
// This method must only be called while the UnsafeResource is still
// "valid".
// I.e,
// For MainPageLoadBlocked resources, it must not be called if the load
// was aborted (going back or replaced with a different navigation),
// or resumed (proceeded through warning or matched whitelist).
// For non-MainPageLoadBlocked resources, it must not be called if any
// other navigation has committed (whether by going back or unrelated
// navigations), though a pending navigation is okay.
content::NavigationEntry* GetNavigationEntryForResource() const;
GURL url;
GURL original_url;
std::vector<GURL> redirect_urls;
bool is_subresource;
bool is_subframe;
SBThreatType threat_type;
ThreatMetadata threat_metadata;
UrlCheckCallback callback; // This is called back on |callback_thread|.
scoped_refptr<base::SingleThreadTaskRunner> callback_thread;
int render_process_host_id;
int render_frame_id;
safe_browsing::ThreatSource threat_source;
};
// Observer class can be used to get notified when a SafeBrowsing hit
// was found.
class Observer {
public:
// The |resource| was classified as unsafe by SafeBrowsing, and is
// not whitelisted.
// The |resource| must not be accessed after OnSafeBrowsingHit returns.
// This method will be called on the UI thread.
virtual void OnSafeBrowsingHit(const UnsafeResource& resource) = 0;
protected:
Observer() {}
virtual ~Observer() {}
private:
DISALLOW_COPY_AND_ASSIGN(Observer);
};
explicit SafeBrowsingUIManager(
const scoped_refptr<SafeBrowsingService>& service);
// Called to stop or shutdown operations on the io_thread. This may be called
// multiple times during the life of the UIManager. Should be called
// on IO thread. If shutdown is true, the manager is disabled permanently.
void StopOnIOThread(bool shutdown);
// Called on the UI thread to display an interstitial page.
// |url| is the url of the resource that matches a safe browsing list.
// If the request contained a chain of redirects, |url| is the last url
// in the chain, and |original_url| is the first one (the root of the
// chain). Otherwise, |original_url| = |url|.
virtual void DisplayBlockingPage(const UnsafeResource& resource);
// Returns true if we already displayed an interstitial for that top-level
// site in a given WebContents. Called on the UI thread.
bool IsWhitelisted(const UnsafeResource& resource);
// The blocking page on the UI thread has completed.
void OnBlockingPageDone(const std::vector<UnsafeResource>& resources,
bool proceed);
// Log the user perceived delay caused by SafeBrowsing. This delay is the time
// delta starting from when we would have started reading data from the
// network, and ending when the SafeBrowsing check completes indicating that
// the current page is 'safe'.
void LogPauseDelay(base::TimeDelta time);
// Called on the IO thread by the ThreatDetails with the serialized
// protocol buffer, so the service can send it over.
virtual void SendSerializedThreatDetails(const std::string& serialized);
// Report hits to the unsafe contents (malware, phishing, unsafe download URL)
// to the server. Can only be called on UI thread. If |post_data| is
// non-empty, the request will be sent as a POST instead of a GET.
// Will report only for UMA || is_extended_reporting.
virtual void MaybeReportSafeBrowsingHit(
const safe_browsing::HitReport& hit_report);
// Report an invalid TLS/SSL certificate chain to the server. Can only
// be called on UI thread.
void ReportInvalidCertificateChain(const std::string& serialized_report,
const base::Closure& callback);
// Add and remove observers. These methods must be invoked on the UI thread.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* remove);
protected:
virtual ~SafeBrowsingUIManager();
private:
friend class base::RefCountedThreadSafe<SafeBrowsingUIManager>;
friend class SafeBrowsingUIManagerTest;
// Call protocol manager on IO thread to report hits of unsafe contents.
void ReportSafeBrowsingHitOnIOThread(
const safe_browsing::HitReport& hit_report);
// Sends an invalid certificate chain report over the network.
void ReportInvalidCertificateChainOnIOThread(
const std::string& serialized_report);
// Updates the whitelist state. Called on the UI thread.
void AddToWhitelist(const UnsafeResource& resource);
// Safebrowsing service.
scoped_refptr<SafeBrowsingService> sb_service_;
base::ObserverList<Observer> observer_list_;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingUIManager);
};
} // namespace safe_browsing
#endif // CHROME_BROWSER_SAFE_BROWSING_UI_MANAGER_H_
| [
"wangpp_os@sari.ac.cn"
] | wangpp_os@sari.ac.cn |
67a4d076c5d453e04d96f28707d90a6758d9e3dc | fd9f5186fa5d19db077dbf302fe9c940cb42e82f | /src/kvstore/RateLimiter.h | 6e03ec8da5b67c11436826b7a15f33447c6bedd6 | [
"Apache-2.0"
] | permissive | vesoft-inc/nebula | a0b9af548e124e59ecbfb0c5152098a1020b621c | 7c32088dec1891870a24aaa37ee5818e69f5ad6d | refs/heads/master | 2023-08-17T00:00:29.022525 | 2023-08-16T04:02:03 | 2023-08-16T04:02:03 | 146,459,443 | 11,007 | 1,220 | Apache-2.0 | 2023-09-05T05:48:16 | 2018-08-28T14:25:09 | C++ | UTF-8 | C++ | false | false | 1,979 | h | /* Copyright (c) 2021 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#ifndef KVSTORE_RATELIMITER_H
#define KVSTORE_RATELIMITER_H
#include <folly/TokenBucket.h>
#include "common/base/Base.h"
#include "common/thrift/ThriftTypes.h"
#include "common/time/WallClock.h"
DECLARE_bool(skip_wait_in_rate_limiter);
namespace nebula {
namespace kvstore {
// A simple wrapper for folly::TokenBucket, it would limit the speed to rate_ * buckets_.size().
// For now, there are two major cases: snapshot (both for balance or catch up) and rebuild index.
class RateLimiter {
public:
RateLimiter() {
// token will be available after 1 second, to prevent speed spike at the beginning
auto now = time::WallClock::fastNowInSec();
int64_t waitInSec = FLAGS_skip_wait_in_rate_limiter ? 0 : 1;
bucket_.reset(new folly::DynamicTokenBucket(static_cast<double>(now + waitInSec)));
}
/**
* @brief Consume some budget from rate limiter. Caller must make sure the **the partition has
* been add, and won't be removed during consume.** Snapshot and rebuild index follow this
* principle by design.
*
* @param toConsume Amount to consume
* @param rate Generate speed
* @param burstSize Maximum consume speed to consume
*/
void consume(double toConsume, double rate, double burstSize) {
if (toConsume > burstSize) {
// consumeWithBorrowAndWait do nothing when toConsume > burstSize_, we sleep 1s instead
std::this_thread::sleep_for(std::chrono::seconds(1));
} else {
// If there are enough tokens, consume and return immediately.
// If not, consume anyway, but sleep enough time before return.
auto now = time::WallClock::fastNowInSec();
bucket_->consumeWithBorrowAndWait(toConsume, rate, burstSize, static_cast<double>(now));
}
}
private:
std::unique_ptr<folly::DynamicTokenBucket> bucket_;
};
} // namespace kvstore
} // namespace nebula
#endif
| [
"noreply@github.com"
] | noreply@github.com |
a2cc62ecd1648caf74dff7cd29b948b779193cba | 35f2ac06068ced05ab27e329052e9d9758fe59c3 | /lexer/v2/parser.hpp | d58d34c366e35e72d77e0c6a1969c36022f5ab1f | [
"MIT"
] | permissive | mhhollomon/blogcode | c7247cb15109371ae9df7ead0c39e3d5b6cd894a | 0cb82ab90d33d3eac14974a9c4d890d6abd6325e | refs/heads/master | 2021-06-18T11:19:55.989911 | 2019-10-10T18:29:04 | 2019-10-10T18:29:04 | 148,825,994 | 2 | 1 | null | 2018-09-14T18:31:23 | 2018-09-14T18:16:38 | null | UTF-8 | C++ | false | false | 1,697 | hpp | #if !defined(LEXER_PARSER_H_)
#define LEXER_PARSER_H_
//****************************************
// Copyright 2018 - Mark Hollomon
//
// Attempt to use a lexer with Boost.Spirit X3
// Main
//****************************************
#include <boost/spirit/home/x3.hpp>
#include "lexer.hpp"
namespace x3 = boost::spirit::x3;
struct tok_sym: x3::parser<tok_sym> {
using attribute_type = std::string;
tok_sym(TokenType t = tokNil) : m_tt{t} {};
template<typename Iterator, typename Context, typename RContext, typename Attribute>
bool parse(Iterator &first, Iterator const& last, Context const& context,
RContext const& rcontext, Attribute& attr) const
{
if ((*first).istype(m_tt)) {
attr = (*first).lexeme;
++first;
return true;
}
return false;
}
private:
TokenType m_tt;
};
template<typename T>
auto operator>>(TokenType left, T right)
{
return (tok_sym(left) >> right);
}
template<typename T>
auto operator>>(T left, TokenType right)
{
return (left >> tok_sym(right));
}
struct tok_kw: x3::parser<tok_kw> {
using attribute_type = x3::unused_type;
tok_kw(TokenType t = tokNil) : m_tt{t} {};
template<typename Iterator, typename Context, typename RContext, typename Attribute>
bool parse(Iterator &first, Iterator const& last, Context const& context,
RContext const& rcontext, Attribute& attr) const
{
if ((*first).istype(m_tt)) {
++first;
return true;
}
return false;
}
private:
TokenType m_tt;
};
#endif
| [
"mhhollomon@gmail.com"
] | mhhollomon@gmail.com |
4c51f95aaf83c4c1adb375159e5d776cec4fb80b | e6b4a9fb699feb39ae4c80ae5c59c539440ccb43 | /Prototypes/C++/Overload/overload.c++ | 99d9e4c34ed83bb61647264ba2b6000ffaf7f2c9 | [] | no_license | Hedede/various-things | 2451154473892546c94633289b66b9d6cd341f9c | ae813b21d70a1dab72a091035332c898d89e5eda | refs/heads/master | 2023-08-09T17:46:52.906049 | 2023-07-30T09:55:41 | 2023-07-30T09:55:41 | 63,462,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,856 | #include <utility>
template<typename F, typename...Fs>
struct overloaded : overloaded<F>, overloaded<Fs...> {
overloaded(F&& f, Fs&&... fs)
: overloaded<F>{std::forward<F>(f)},
overloaded<Fs...>{std::forward<Fs>(fs)...}
{}
using overloaded<F>::operator();
using overloaded<Fs...>::operator();
};
template<typename F>
struct overloaded<F> : F {
overloaded(F&& f)
: F{std::forward<F>(f)}
{}
};
template<typename...Fs>
overloaded<Fs...> overload(Fs&&... fs)
{
return {std::forward<Fs>(fs)...};
}
#include <iostream>
int main()
{
std::cout << std::boolalpha;
std::string str = "got boool";
auto lambda = overload(
[] (int x) { std::cout << "got int " << x << "\n"; },
[&] (bool b) { std::cout << str << ' ' << b << '\n'; }
);
lambda(1);
lambda(true);
str = "got bole";
lambda(false);
}
/* аттемптинг беттер экцпланацион */
// аз ай шовн, из лямбд можно наследовать
template<typename F>
struct func : F {
using F::operator(); // is not necessary now, but will be later
};
// но есть одна проблема: лямбды можно только копировать
{
auto lambda = [] { return 3; };
func<decltype(lambda)> f; // error no matching constructor
}
// посему нужно сделать функ конструироваемым из лябмды
template<typename F>
struct func : F {
func(F&& f)
: F{std::forward<F>(f)} // обычное обращение к конструктору бейзкласса
{}
using F::operator();
};
// и чтобы не писать decltype(), сделаем функцию:
template<typename F>
func<F> make_func(F&& f)
{
return {std::forward<F>(f)};
}
// теперь можно писать:
{
auto lambda = func([] { return 3; });
}
// нот вери юзфул, бат летс мейк ит оверлоадабле
template<typename F1, typename F2>
struct func : F1, F2 {
func(F1&& f1, F2&& f2)
: F1{std::forward<F1>(f1)},
F2{std::forward<F2>(f2)}
{}
// а вот теперь нам нужен юзинг, иначе компилер не знает
// к какому из бейзклассов обращаться, а с юзингом
// они становятся частью общего набора оверлоадед функций
using F1::operator();
using F2::operator();
};
template<typename F1, typename F2>
func<F1,F2> make_func(F1&& f1, F2&& f2)
{
return {std::forward<F1>(f1), std::forward<f2>(f2)};
}
// теперь можно делать простые оверлоады:
{
auto lambda = make_func(
[] (float f) { return int(f); }
[] (int i) { return i; }
);
}
// но мы потеряли возможность (бесполезную) создавать функции из 1 лямбды,
// и что насчёт 3,4,5 и более?
// вступают вариадик темплаты
template<typename F, typename...Rest>
struct func : F, func<Rest...> {
func(F&& f, Rest&&...rest)
// всё еще обычные вызовы конструкторов бейзклассов
: F{std::forward<F>(f)},
func<Rest...>{std::forward<Rest>(rest)...}
{}
// сейм
using F::operator();
using func<Rest...>::operator();
};
// этот класс рекурсивно деривится с меньшим и меньшим количеством
// параметров шаблона, пока не достигнет <>, но
// чтобы он не пытался сконструировать func<> с пустым паком <Rest...>,
// (<Ts...> — называется параметр пак, и он может быть пустым (<>))
// нужна специализация:
template<typename F1>
struct func<F1> : F1 { // [ F = F1, Rest... = <empty>]
func(F1&& f)
: F{std::forward<F1>(f)},
{}
using F1::operator();
};
// всо, класс готов
// за счет множественного наследования func получает все () лямбд из которых
// он наследовался, а также все захваченные ими переменные
// (хмм, ай вондер можно ли их соптимизировать, чтобы не дублировался одинаковый захват…)
// ах да
template<typename... Fs>
func<Fs...> make_func(Fs&&... fs)
{
return {std::forward<Fs>(fs)...};
}
// ещё что то хотел сказать… про шаблоны, но забыл
// алсо, конечно хотелось бы
template<typename...Fs>
// possible
struct func : Fs... {
func(Fs&&... fs)
// not possible :(
// WAIT, ya mooduck,
: Fs(std::forward<Fs>(fs)...)...
{}
func(Fs&&... fs)
// possible
: Fs(std::forward<Fs>(fs))...
{}
// not possible :(
using Fs...::operator();
};
| [
"haddayn@gmail.com"
] | haddayn@gmail.com | |
f139659e9383f204fd4d2d2544fa56dc7e11caa3 | f9a4647a22a5c27ae3228ab11bbbd7a0dcdbd09d | /Sources/VPDFDocument.cpp | 86ade96682e2b94724e1312230da9d7c0dd9da6e | [] | no_license | ayoubserti/PDFCreator | d768260a73050236376a606a1fc463d1eb4e1837 | 004a2e7ad265b659eb8fa0326f02b5fad27b4fec | refs/heads/master | 2021-01-10T13:21:56.139055 | 2016-05-06T14:54:06 | 2016-05-06T14:54:06 | 46,519,005 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,778 | cpp | /*
VPDFDocument implementation
*/
#include "VPDFDocument.h"
#include "VPDFPage.h"
#include "VPDFOutline.h"
#include "VPDFEncoding.h"
#include "VPDFImage.h"
#include <stdio.h> //for NULL definition
using namespace XBOX;
VError __stdcall ErrorHandlerFunc(HPDF_STATUS s1, HPDF_STATUS s2, void* e)
{
return s1;
}
VPDFDocument::VPDFDocument()
{
fDocHandle = HPDF_New((HPDF_Error_Handler)(NULL), NULL);
fCurrentPage = nullptr;
}
VPDFDocument::~VPDFDocument()
{
HPDF_Free(fDocHandle);
}
VPDFPage* VPDFDocument::AddPage( VError& outError )
{
VPDFPage* pdfPage = nullptr;
HPDF_Page hPage = HPDF_AddPage ( fDocHandle );
outError = HPDF_GetError( fDocHandle );
if (outError == VE_OK )
{
pdfPage = VPDFPage::CreatePage (hPage);
if(pdfPage != nullptr )
{
pdfPage->fDocParent = fDocHandle;
}
}
return pdfPage;
}
VError VPDFDocument::AddPageLabel ( uLONG inPageNumber, ePDFPageNumStyle inPageNumStyle, uLONG inFirstPage , const uBYTE* inPrefix )
{
VError error = VE_OK;
error = HPDF_AddPageLabel (fDocHandle,inPageNumber,inPageNumStyle,inFirstPage,(const char*)inPrefix);
return error;
}
VPDFOutline* VPDFDocument::CreateOutline ( VPDFOutline* inParent, const uBYTE* inTitle, VPDFEncoder* inEncoder, XBOX::VError& outError )
{
VPDFOutline* rOutLine = new VPDFOutline();
rOutLine->fOutlineHandle = HPDF_CreateOutline(fDocHandle,inParent->fOutlineHandle,(const char*) inTitle,inEncoder->fEncoderHandle);
outError = HPDF_GetError( fDocHandle );
return rOutLine;
}
VPDFPage* VPDFDocument::CreatePage( XBOX::VError& outError )
{
VPDFPage* pdfPage = AddPage( outError );
return pdfPage;
}
VPDFEncoder* VPDFDocument::GetCurrentEncoder (VError& outError )
{
VPDFEncoder* encoder = new VPDFEncoder();
encoder->fEncoderHandle = HPDF_GetCurrentEncoder(fDocHandle );
outError = HPDF_GetError( fDocHandle );
if ( outError != VE_OK )
{
delete encoder;
}
return encoder;
}
VPDFPage* VPDFDocument::GetCurrentPage( )
{
return fCurrentPage;
}
VPDFEncoder* VPDFDocument::GetEncoder(const uBYTE* inEncodingName, VError& outError )
{
VPDFEncoder* vEncoder = nullptr;
HPDF_Encoder hEncoder = HPDF_GetEncoder(fDocHandle,(const char*)inEncodingName );
outError = HPDF_GetError( fDocHandle );
if (hEncoder == nullptr && outError == VE_OK )
{
vEncoder = new VPDFEncoder(hEncoder);
}
return vEncoder;
}
VPDFFont* VPDFDocument::GetFont (const uBYTE* inFontName , const uBYTE* inEncondingName, XBOX::VError& outError)
{
VPDFFont* vFont = nullptr;
HPDF_Font hFont = HPDF_GetFont( fDocHandle,(const char*)inFontName, (const char*)inEncondingName );
outError = HPDF_GetError(fDocHandle);
if (hFont && (outError == VE_OK) )
{
vFont = new VPDFFont(hFont);
}
return vFont;
}
VPDFPage* VPDFDocument::InsertPage( const VPDFPage& inTargetPage)
{
VPDFPage* vPage = nullptr;
HPDF_Page hTargetPage = inTargetPage.fPageHandle;
if (hTargetPage != nullptr)
{
HPDF_Page hPage = HPDF_InsertPage ( fDocHandle, hTargetPage );
VError err = HPDF_GetError ( fDocHandle ) ;
if (!err && hPage )
{
vPage = VPDFPage::CreatePage(hPage);
}
}
return vPage;
}
VPDFImage* VPDFDocument::LoadPngImage (const uBYTE* inImgFileName , VError& outError )
{
VPDFImage* vImage = nullptr;
HPDF_Image hImage = HPDF_LoadPngImageFromFile ( fDocHandle, (const char*)inImgFileName );
outError = HPDF_GetError( fDocHandle );
if (!outError && hImage )
{
vImage = new VPDFImage( hImage );
}
return vImage;
}
VError VPDFDocument::Save(uBYTE *inFileName)
{
VError err = VE_OK;
err = HPDF_SaveToFile ( fDocHandle , (const char*)inFileName );
return err;
}
VError VPDFDocument::SetPassword ( const uBYTE* inOwnerPwd, const uBYTE* inUserPwd )
{
return HPDF_SetPassword ( fDocHandle,(const char*)inOwnerPwd , (const char*)inUserPwd );
}
| [
"ayb.serti@gmail.com"
] | ayb.serti@gmail.com |
3a69cb06b0130d8ca1dd853ef3ebda9248300f93 | 0215086324881a4e26eac4cb565c0032fdcf7c62 | /Source/EMOSWS/Classes/Framework/UWebsocketppClient.cpp | bb060054f082f8d0d1d93b9c62406c2afe3145c9 | [
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | DigitalKarnage/EMOS | b650667ebb9d66117c6d9ce6579b99f0bb7c78d1 | 909528d59070359e225ff12a364eed215b4c70b4 | refs/heads/master | 2016-08-13T00:33:20.088877 | 2016-03-28T18:12:22 | 2016-03-28T18:12:22 | 52,461,391 | 23 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | cpp | /*
All rights reserved. Copyright (c) 2015-2016, DigitalKarnage
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 HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <EMOSWSPCH.h>
#include <Framework/UWebsocketClient_impl.h>
#include <Framework/UWebsocketppClient.h>
UWebsocketppClient::UWebsocketppClient(const FObjectInitializer& objectInitializer) : Super(objectInitializer)
{
bReplicates = false;
this->PrimaryComponentTick.bCanEverTick = true;
this->PrimaryComponentTick.bRunOnAnyThread = false;
this->PrimaryComponentTick.bTickEvenWhenPaused = true;
this->PrimaryComponentTick.bStartWithTickEnabled = true;
this->p_Impl = MakeShareable<UWebsocketClient_impl>(new UWebsocketClient_impl());
}
void UWebsocketppClient::TickComponent(float delta, enum ELevelTick tickType, struct FActorComponentTickFunction* thisTickFunction)
{
Super::TickComponent(delta, tickType, thisTickFunction);
p_Impl->Poll();
auto messages = p_Impl->GetMessages();
if (EventOnMessageReceived.IsBound())
{
for (auto& message : messages)
EventOnMessageReceived.Broadcast(message);
}
}
void UWebsocketppClient::Connect(const FString& RemoteLocation, const int32 Port)
{
if (p_Impl.IsValid())
p_Impl->Connect(RemoteLocation, Port);
}
void UWebsocketppClient::Shutdown()
{
if (p_Impl.IsValid())
p_Impl->Shutdown();
}
void UWebsocketppClient::K2_SendMessage(const FString& Message)
{
if (p_Impl.IsValid())
p_Impl->SendMessageEx(Message);
} | [
"DigitalKarnage@github.com"
] | DigitalKarnage@github.com |
8f51ed2f92b56392b5b4f7a1076e76555cb848e2 | ac78cdf5bbbf6c509151d66bfca60e7b463af055 | /hsp3dish/win32gp/hsp3extlib.cpp | 33e84ba026961e7cdac55c13ae64fb5c7c117bbc | [] | no_license | sharkpp/openhsp | 98fe6f69ebcb03d80ff0ab11e96645b92b9d7038 | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | refs/heads/master | 2020-12-01T03:05:01.294639 | 2016-01-20T13:37:04 | 2016-01-20T13:37:04 | 12,005,521 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 15,025 | cpp |
//
// HSP3 External COM manager
// onion software/onitama 2004/6
// chokuto 2005/3
//
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <objbase.h>
#include <algorithm>
#include "../supio.h"
#include "../hsp3ext.h"
#include "hsp3extlib.h"
#include "../hspwnd.h"
#if defined(HSPDISH)||defined(HSPDISHGP)
#include "../../hsp3/dpmread.h"
#include "../../hsp3/strbuf.h"
#else
//#include "hspvar_comobj.h"
//#include "hsp3win.h"
#include "../dpmread.h"
#include "../strbuf.h"
#endif
static HSPCTX *hspctx; // Current Context
static HSPEXINFO *exinfo; // Info for Plugins
static PVal **pmpval;
static int libmax, prmmax, hpimax;
static HPIDAT *hpidat;
#define GetPRM(id) (&hspctx->mem_finfo[id])
#define GetLIB(id) (&hspctx->mem_linfo[id])
#define strp(dsptr) &hspctx->mem_mds[dsptr]
typedef void (CALLBACK *DLLFUNC)(HSP3TYPEINFO *);
static DLLFUNC func;
//------------------------------------------------------------//
namespace hsp3 {
//------------------------------------------------------------//
/*
CDllManager
*/
//------------------------------------------------------------//
CDllManager::CDllManager()
: mModules(), mError( NULL )
{}
CDllManager::~CDllManager()
{
typedef holder_type::iterator Iter;
for ( Iter i = mModules.begin(); i != mModules.end(); ++i ) {
FreeLibrary( *i );
}
}
HMODULE CDllManager::load_library( LPCTSTR lpFileName )
{
mError = NULL;
HMODULE h = LoadLibrary( lpFileName );
try {
if ( h != NULL ) mModules.push_front( h );
}
catch ( ... ) {
if ( !FreeLibrary( h ) ) mError = h;
h = NULL;
}
return h;
}
BOOL CDllManager::free_library( HMODULE hModule )
{
typedef holder_type::iterator Iter;
mError = NULL;
Iter i = std::find( mModules.begin(), mModules.end(), hModule );
if ( i == mModules.end() ) return FALSE;
BOOL res = FreeLibrary( hModule );
if ( res ) {
mModules.erase( i );
} else {
mError = hModule;
}
return res;
}
BOOL CDllManager::free_all_library()
{
typedef holder_type::iterator Iter;
for ( Iter i = mModules.begin(); i != mModules.end(); ++i ) {
if ( FreeLibrary( *i ) ) *i = NULL;
}
mModules.erase( std::remove( mModules.begin(), mModules.end(),
static_cast< HMODULE >( NULL ) ), mModules.end() );
return ( mModules.empty() ? TRUE : FALSE );
}
HMODULE CDllManager::get_error() const
{
return mError;
}
//------------------------------------------------------------//
}; //namespace hsp3 {
//------------------------------------------------------------//
hsp3::CDllManager & DllManager()
{
static hsp3::CDllManager dm;
return dm;
}
/*------------------------------------------------------------*/
/*
routines
*/
/*------------------------------------------------------------*/
static void BindLIB( LIBDAT *lib, char *name )
{
// ライブラリのバインドを行なう
// (name:後から与える時のライブラリ名)
//
int i;
char *n;
HINSTANCE hd;
if ( lib->flag != LIBDAT_FLAG_DLL ) return;
i = lib->nameidx;
if ( i < 0 ) {
if ( name == NULL ) return;
n = name;
} else {
n = strp(i);
}
hd = DllManager().load_library( n );
if ( hd == NULL ) return;
lib->hlib = (void *)hd;
lib->flag = LIBDAT_FLAG_DLLINIT;
}
static int BindFUNC( STRUCTDAT *st, char *name )
{
// ファンクションのバインドを行なう
// (name:後から与える時のファンクション名)
//
int i;
char *n;
LIBDAT *lib;
HINSTANCE hd;
if (( st->subid != STRUCTPRM_SUBID_DLL )&&( st->subid != STRUCTPRM_SUBID_OLDDLL )) return 4;
i = st->nameidx;
if ( i < 0 ) {
if ( name == NULL ) return 3;
n = name;
} else {
n = strp(i);
}
lib = GetLIB( st->index );
if ( lib->flag != LIBDAT_FLAG_DLLINIT ) {
BindLIB( lib, NULL );
if ( lib->flag != LIBDAT_FLAG_DLLINIT ) return 2;
}
hd = (HINSTANCE)(lib->hlib);
st->proc = (void *)GetProcAddress( hd, n );
if ( hd == NULL ) return 1;
st->subid--;
return 0;
}
static void ExitFunc( STRUCTDAT *st )
{
// 終了時関数の呼び出し
//
int p[16];
FARPROC pFn;
BindFUNC( st, NULL );
pFn = (FARPROC)st->proc;
if ( pFn == NULL ) return;
p[0] = p[1] = p[2] = p[3] = 0;
call_extfunc( pFn, p, st->size / 4 );
}
static int Hsp3ExtAddPlugin( void )
{
// プラグインの登録
//
int i;
HSPHED *hed;
char *ptr;
char *libname;
char *funcname;
HPIDAT *hpi;
HSP3TYPEINFO *info;
HINSTANCE hd;
char tmp[512];
hed = hspctx->hsphed; ptr = (char *)hed;
hpi = hpidat = (HPIDAT *)( ptr + hed->pt_hpidat );
hpimax = hed->max_hpi / sizeof( HPIDAT );
for ( i=0;i<hpimax;i++ ) {
libname = strp(hpi->libname);
funcname = strp(hpi->funcname);
info = code_gettypeinfo(-1);
if ( hpi->flag == HPIDAT_FLAG_TYPEFUNC ) {
hd = DllManager().load_library( libname );
if ( hd == NULL ) {
sprintf( tmp,"No DLL:%s",libname );
Alert( tmp );
return 1;
}
hpi->libptr = (void *)hd;
func = (DLLFUNC)GetProcAddress( hd, funcname );
if ( func == NULL ) {
sprintf( tmp,"No DLL:%s:%s", libname, funcname );
Alert( tmp );
return 1;
}
func( info );
code_enable_typeinfo( info );
//Alertf( "%d_%d [%s][%s]", i, info->type, libname, funcname );
}
hpi++;
}
return 0;
}
/*------------------------------------------------------------*/
/*
window object support
*/
/*------------------------------------------------------------*/
static BMSCR *GetBMSCR( void )
{
HSPEXINFO *exinfo;
exinfo = hspctx->exinfo2;
return (BMSCR *)exinfo->HspFunc_getbmscr( *(exinfo->actscr) );
}
/*------------------------------------------------------------*/
/*
interface
*/
/*------------------------------------------------------------*/
int Hsp3ExtLibInit( HSP3TYPEINFO *info )
{
int i;
STRUCTDAT *st;
char tmp[1024];
hspctx = info->hspctx;
exinfo = info->hspexinfo;
pmpval = exinfo->mpval;
libmax = hspctx->hsphed->max_linfo / sizeof(LIBDAT);
prmmax = hspctx->hsphed->max_finfo / sizeof(STRUCTDAT);
if ( Hsp3ExtAddPlugin() ) return 1;
for(i=0;i<prmmax;i++) {
st = GetPRM(i);
if ( BindFUNC( st, NULL ) == 1 ) {
sprintf( tmp,"No FUNC:%s",strp(st->nameidx) );
Alert( tmp );
}
}
return 0;
}
void Hsp3ExtLibTerm( void )
{
int i;
STRUCTDAT *st;
// クリーンアップ登録されているユーザー定義関数・命令呼び出し
for(i=0;i<prmmax;i++) {
st = GetPRM(i);
if ( st->index >= 0 ) {
if ( st->otindex & STRUCTDAT_OT_CLEANUP ) {
ExitFunc( st ); // クリーンアップ関数を呼び出す
}
}
}
}
/*------------------------------------------------------------*/
/*
code expand function
*/
/*------------------------------------------------------------*/
/*
rev 43
mingw(gcc) 用のコード追加
*/
#if defined( _MSC_VER )
#ifdef HSP64
int __cdecl call_extfunc( void *proc, int *prm, int prms )
{
return 0;
}
#else
__declspec( naked ) int __cdecl call_extfunc( void *proc, int *prm, int prms )
{
// 外部関数呼び出し(VC++ のインラインアセンブラを使用)
//
__asm {
push ebp
mov ebp,esp
;# ebp+8 : 関数のポインタ
;# ebp+12 : 引数が入ったINTの配列
;# ebp+16 : 引数の数(pushする回数)
;# パラメータをnp個pushする
mov eax, dword ptr [ebp+12]
mov ecx, dword ptr [ebp+16]
jmp _$push_chk
_$push:
push dword ptr [eax+ecx*4]
_$push_chk:
dec ecx
jge _$push
;# 関数呼び出し
call dword ptr [ebp+8]
;# 戻り値は eax に入るのでそのままリターン
leave
ret
}
}
#endif
#elif defined( __GNUC__ )
int __cdecl call_extfunc( void * proc, int * prm, int prms )
{
// 外部関数呼び出し(GCC の拡張インラインアセンブラを使用)
int ret = 0;
__asm__ volatile (
"pushl %%ebp;"
"movl %%esp, %%ebp;"
"jmp _push_chk;"
// パラメータをprms個pushする
"_push:"
"pushl ( %2, %3, 4 );"
"_push_chk:"
"decl %3;"
"jge _push;"
"calll *%1;"
"leave;"
: "=a" ( ret )
: "r" ( proc ) , "r" ( prm ), "r" ( prms )
);
return ret;
}
#endif
int cnvwstr( void *out, char *in, int bufsize )
{
// sjis->unicode に変換
//
return MultiByteToWideChar( CP_ACP, 0, in, -1, (LPWSTR)out, bufsize );
}
int cnvsjis( void *out, char *in, int bufsize )
{
// unicode->sjis に変換
//
return WideCharToMultiByte( CP_ACP, 0, (LPCWSTR)in, -1, (LPSTR)out, bufsize, NULL, NULL);
}
static char *prepare_localstr( char *src, int mode )
{
// DLL 渡しのための文字列を準備する
// mode:0=ansi/1=unicode
//
// 使用後は sbFree() で解放すること
//
int srcsize;
char *dst;
if ( mode ) {
srcsize = (int)(( strlen(src) + 1 ) * 2); // unicodeのサイズを概算
dst = sbAlloc( srcsize );
cnvwstr( dst, src, srcsize );
} else {
dst = sbAlloc( (int)strlen(src)+1 );
strcpy( dst, src );
}
return dst;
}
static int code_expand_next( char *, const STRUCTDAT *, int );
int code_expand_and_call( const STRUCTDAT *st )
{
// パラメータの取得および関数呼び出し(再帰処理による)
//
// 通常の DLL 関数呼び出しか COM メソッド呼び出しかどうかは
// STRUCTDAT の内容から判断します。
//
// DLL 関数呼び出し時は st->proc に関数アドレスをセットして
// おかなければなりません( BindFUNC() により)。
//
int result;
char *prmbuf = sbAlloc( st->size );
try {
result = code_expand_next( prmbuf, st, 0 );
}
catch (...) {
sbFree( prmbuf );
throw;
}
sbFree( prmbuf );
return result;
}
static int code_expand_next( char *prmbuf, const STRUCTDAT *st, int index )
{
// 次のパラメータを取得(および関数呼び出し)(再帰処理)
//
int result;
if ( index == st->prmmax ) {
// 関数(またはメソッド)の呼び出し
//if ( !code_getexflg() ) throw HSPERR_TOO_MANY_PARAMETERS;
switch ( st->subid ) {
case STRUCTPRM_SUBID_DLL:
case STRUCTPRM_SUBID_DLLINIT:
case STRUCTPRM_SUBID_OLDDLL:
case STRUCTPRM_SUBID_OLDDLLINIT:
// 外部 DLL 関数の呼び出し
result = call_extfunc( st->proc, (int*)prmbuf, (st->size / 4) );
break;
#ifndef HSP_COM_UNSUPPORTED
case STRUCTPRM_SUBID_COMOBJ:
// COM メソッドの呼び出し
result = call_method2( prmbuf, st );
break;
#endif
default:
throw ( HSPERR_UNSUPPORTED_FUNCTION );
}
return result;
}
STRUCTPRM *prm = &hspctx->mem_minfo[ st->prmindex + index ];
void *out = prmbuf + prm->offset;
int srcsize;
PVal *pval_dst, *mpval;
APTR aptr;
PVal *pval;
int chk;
// 以下のポインタ(またはオブジェクト)は呼出し後に解放
void *localbuf = NULL;
IUnknown *punklocal = NULL;
switch ( prm->mptype ) {
case MPTYPE_INUM:
*(int *)out = code_getdi(0);
break;
case MPTYPE_PVARPTR:
aptr = code_getva( &pval );
*(void **)out = HspVarCorePtrAPTR( pval, aptr );
break;
case MPTYPE_LOCALSTRING:
localbuf = prepare_localstr( code_gets(), 0 );
*(void **)out = localbuf;
break;
case MPTYPE_LOCALWSTR:
localbuf = prepare_localstr( code_gets(), 1 );
*(void **)out = localbuf;
break;
case MPTYPE_DNUM:
*(double *)out = code_getdd(0.0);
break;
case MPTYPE_FLOAT:
*(float *)out = (float)code_getdd(0.0);
break;
case MPTYPE_PPVAL:
aptr = code_getva( &pval );
localbuf = sbAlloc( sizeof(PVal) );
pval_dst = (PVal *)localbuf;
*pval_dst = *pval;
if ( pval->flag & HSPVAR_SUPPORT_FLEXSTORAGE ) { // ver2.5互換のための変換
HspVarCoreGetBlockSize( pval, HspVarCorePtrAPTR( pval, aptr ), &srcsize );
pval_dst->len[1] = (srcsize+3)/4;
pval_dst->len[2] = 1;
pval_dst->len[3] = 0;
pval_dst->len[4] = 0;
}
*(void **)out = pval_dst;
break;
case MPTYPE_PBMSCR:
*(void **)out = GetBMSCR();
break;
case MPTYPE_FLEXSPTR:
case MPTYPE_FLEXWPTR:
chk = code_get();
if ( chk<=PARAM_END ) throw ( HSPERR_NO_DEFAULT );
mpval = *pmpval;
switch( mpval->flag ) {
case HSPVAR_FLAG_INT:
*(int *)out = *(int *)(mpval->pt);
break;
case HSPVAR_FLAG_STR:
localbuf = prepare_localstr( mpval->pt, (prm->mptype==MPTYPE_FLEXWPTR) );
*(void **)out = localbuf;
break;
default:
throw ( HSPERR_TYPE_MISMATCH );
}
break;
case MPTYPE_PTR_REFSTR:
*(void **)out = hspctx->refstr;
break;
case MPTYPE_PTR_EXINFO:
*(void **)out = exinfo;
break;
case MPTYPE_PTR_DPMINFO:
dpm_getinf( hspctx->refstr );
*(void **)out = hspctx->refstr;
break;
case MPTYPE_NULLPTR:
*(int *)out = 0;
break;
#ifndef HSP_COM_UNSUPPORTED
case MPTYPE_IOBJECTVAR:
aptr = code_getva( &pval );
if ( pval->flag != TYPE_COMOBJ ) throw ( HSPERR_TYPE_MISMATCH );
punklocal = *(IUnknown **)HspVarCorePtrAPTR( pval, aptr );
if ( punklocal ) punklocal->AddRef(); // 呼出し後に解放する
*(void **)out = (void *)punklocal;
break;
#endif
default:
throw ( HSPERR_UNSUPPORTED_FUNCTION );
}
// 次のパラメータの取り出し(再帰的に処理)
// (例外処理により動的確保したオブジェクトを確実に解放する)
try {
result = code_expand_next( prmbuf, st, index + 1 );
}
catch (...) {
if ( localbuf ) sbFree( localbuf );
if ( punklocal ) punklocal->Release();
throw;
}
if ( localbuf ) sbFree( localbuf );
if ( punklocal ) punklocal->Release();
return result;
}
int exec_dllcmd( int cmd, int mask )
{
STRUCTDAT *st;
FARPROC pFn;
int result;
code_next(); // 次のコードを取得(最初に必ず必要です)
if ( cmd >= prmmax ) {
throw ( HSPERR_UNSUPPORTED_FUNCTION );
}
st = GetPRM(cmd);
pFn = (FARPROC)st->proc;
if ( pFn == NULL ) {
if ( BindFUNC( st, NULL ) ) throw ( HSPERR_DLL_ERROR );
pFn = (FARPROC)st->proc;
}
if (( st->otindex & mask ) == 0 ) throw ( HSPERR_SYNTAX );
result = code_expand_and_call( st );
if ( st->subid == STRUCTPRM_SUBID_OLDDLLINIT ) {
if ( result > 0 ) {
if ( result & 0x20000 ) {
result &= 0x1ffff;
} else if ( result & 0x10000 ) {
result = ( result & 0xffff ) * 10;
} else {
throw ( HSPERR_DLL_ERROR );
}
hspctx->waitcount = result;
hspctx->waittick = -1;
hspctx->runmode = RUNMODE_AWAIT;
return RUNMODE_AWAIT;
}
hspctx->stat = -result;
} else {
hspctx->stat = result;
}
return RUNMODE_RUN;
}
int cmdfunc_dllcmd( int cmd )
{
// cmdfunc : TYPE_DLLCMD
// (拡張DLLコマンド)
//
return exec_dllcmd( cmd, STRUCTDAT_OT_STATEMENT );
}
| [
"onitama@ceb3ebad-0e53-d446-8596-a45b2b8d79cd"
] | onitama@ceb3ebad-0e53-d446-8596-a45b2b8d79cd |
7697d192055d728e43f83775cde955cdf3f20989 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14117/function14117_schedule_2/function14117_schedule_2.cpp | 8c128e10cb5baf797abc4fa70947c534eb2af778 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 719 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14117_schedule_2");
constant c0("c0", 128), c1("c1", 64), c2("c2", 128), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04");
computation comp0("comp0", {i0, i1, i2, i3}, 7 * 6 * 0);
comp0.tile(i2, i3, 32, 32, i01, i02, i03, i04);
comp0.parallelize(i0);
buffer buf0("buf0", {128, 64, 128, 64}, p_int32, a_output);
comp0.store_in(&buf0);
tiramisu::codegen({&buf0}, "../data/programs/function14117/function14117_schedule_2/function14117_schedule_2.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
52962d367e769f4a7f22d386d3f52e27ade14b73 | cad7462a6aa224ced2ed49dd23556af7d8dacc28 | /Week 8/final/final 2/Node.signed/SortedVector.cpp | e6fd640b02e8f6a8a07ab0b9fadc371374710d34 | [] | no_license | Anuragis/CPP-Labs | 7af71db42f65008bec3bc2203e69c37d9aabc2b8 | e5401173497fd2abe51025255236827994d54d91 | refs/heads/master | 2020-03-18T17:58:53.166045 | 2018-05-27T16:45:59 | 2018-05-27T16:45:59 | 135,064,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,746 | cpp | #include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include "SortedVector.h"
#include "Node.h"
using namespace std;
SortedVector::SortedVector()
{
Node::reset();
}
SortedVector::~SortedVector()
{
Node::reset();
}
int SortedVector::size() const { return data.size(); }
bool SortedVector::check() const
{
if (data.size() == 0) return true;
vector<Node>::const_iterator it = data.begin();
vector<Node>::const_iterator prev = it;
it++;
// Ensure that each node is greater than the previous node.
while ((it != data.end()) && (*it > *prev))
{
prev = it;
it++;
}
return it == data.end(); // Good if reached the end.
}
void SortedVector::prepend(const long value)
{
/***** Complete this function. *****/
// vector<Node>::iterator it;
data.insert(data.begin(),Node(value));
}
void SortedVector::append(const long value)
{
/***** Complete this function. *****/
Node val(value);
data.push_back(val);
}
void SortedVector::remove(const int index)
{
/***** Complete this function. *****/
data.erase(data.begin() + index);
}
void SortedVector::insert(const long value)
{
vector<Node>::iterator it = data.begin();
int index = 0;
while (index < data.size()) {
if((*it).get_value()>value) {
data.insert(it, Node(value));
return;
}
index++;it++;
}
if(it == data.end()) {
data.push_back(Node(value));
}
// upper_bound (data.begin(), data.end(), Node(value));
}
Node SortedVector::at(const int index) const
{
/***** Complete this function. *****/
return data[index];
}
void SortedVector::reserve_size(const int size){
data.reserve(size);
} | [
"Anuragis@users.noreply.github.com"
] | Anuragis@users.noreply.github.com |
1b7db9718efa382c7a557007ca1862a73c8bac43 | e83aaf423d3624748522b9adecdeb15659f5bdee | /ditfw-gfx/deps/wxwidgets/src/aui/auibar.cpp | 37413d8acf7fe04b7f4e32f621bcf64acd075725 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | chartly/portfolio | 4b432c212968b56d6a1514efe3dae87ae9a0c0e0 | bd1782c274604f29f0edaa1407efce2a80d2c58f | refs/heads/master | 2021-01-19T18:33:16.143552 | 2016-11-29T03:03:25 | 2016-11-29T03:03:25 | 30,293,065 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 78,739 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: src/aui/auibar.cpp
// Purpose: wxaui: wx advanced user interface - docking window manager
// Author: Benjamin I. Williams
// Modified by:
// Created: 2005-05-17
// Copyright: (C) Copyright 2005-2006, Kirix Corporation, All Rights Reserved
// Licence: wxWindows Library Licence, Version 3.1
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_AUI
#include "wx/statline.h"
#include "wx/dcbuffer.h"
#include "wx/sizer.h"
#include "wx/image.h"
#include "wx/settings.h"
#include "wx/menu.h"
#include "wx/aui/auibar.h"
#include "wx/aui/framemanager.h"
#ifdef __WXMAC__
#include "wx/osx/private.h"
#endif
#include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(wxAuiToolBarItemArray)
wxDEFINE_EVENT( wxEVT_AUITOOLBAR_TOOL_DROPDOWN, wxAuiToolBarEvent );
wxDEFINE_EVENT( wxEVT_AUITOOLBAR_OVERFLOW_CLICK, wxAuiToolBarEvent );
wxDEFINE_EVENT( wxEVT_AUITOOLBAR_RIGHT_CLICK, wxAuiToolBarEvent );
wxDEFINE_EVENT( wxEVT_AUITOOLBAR_MIDDLE_CLICK, wxAuiToolBarEvent );
wxDEFINE_EVENT( wxEVT_AUITOOLBAR_BEGIN_DRAG, wxAuiToolBarEvent );
IMPLEMENT_CLASS(wxAuiToolBar, wxControl)
IMPLEMENT_DYNAMIC_CLASS(wxAuiToolBarEvent, wxEvent)
// missing wxITEM_* items
enum
{
wxITEM_CONTROL = wxITEM_MAX,
wxITEM_LABEL,
wxITEM_SPACER
};
const int BUTTON_DROPDOWN_WIDTH = 10;
wxBitmap wxAuiBitmapFromBits(const unsigned char bits[], int w, int h,
const wxColour& color);
static wxColor GetBaseColor()
{
#if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
wxColor baseColour = wxColour( wxMacCreateCGColorFromHITheme(kThemeBrushToolbarBackground));
#else
wxColor baseColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
#endif
// the baseColour is too pale to use as our base colour,
// so darken it a bit --
if ((255-baseColour.Red()) +
(255-baseColour.Green()) +
(255-baseColour.Blue()) < 60)
{
baseColour = baseColour.ChangeLightness(92);
}
return baseColour;
}
class ToolbarCommandCapture : public wxEvtHandler
{
public:
ToolbarCommandCapture() { m_lastId = 0; }
int GetCommandId() const { return m_lastId; }
bool ProcessEvent(wxEvent& evt) wxOVERRIDE
{
if (evt.GetEventType() == wxEVT_MENU)
{
m_lastId = evt.GetId();
return true;
}
if (GetNextHandler())
return GetNextHandler()->ProcessEvent(evt);
return false;
}
private:
int m_lastId;
};
static const unsigned char
DISABLED_TEXT_GREY_HUE = wxColour::AlphaBlend(0, 255, 0.4);
const wxColour DISABLED_TEXT_COLOR(DISABLED_TEXT_GREY_HUE,
DISABLED_TEXT_GREY_HUE,
DISABLED_TEXT_GREY_HUE);
wxAuiDefaultToolBarArt::wxAuiDefaultToolBarArt()
{
m_baseColour = GetBaseColor();
m_flags = 0;
m_textOrientation = wxAUI_TBTOOL_TEXT_BOTTOM;
m_highlightColour = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
m_separatorSize = 7;
m_gripperSize = 7;
m_overflowSize = 16;
wxColor darker1Colour = m_baseColour.ChangeLightness(85);
wxColor darker2Colour = m_baseColour.ChangeLightness(75);
wxColor darker3Colour = m_baseColour.ChangeLightness(60);
wxColor darker4Colour = m_baseColour.ChangeLightness(50);
wxColor darker5Colour = m_baseColour.ChangeLightness(40);
m_gripperPen1 = wxPen(darker5Colour);
m_gripperPen2 = wxPen(darker3Colour);
m_gripperPen3 = *wxWHITE_PEN;
static const unsigned char buttonDropdownBits[] = { 0xe0, 0xf1, 0xfb };
static const unsigned char overflowBits[] = { 0x80, 0xff, 0x80, 0xc1, 0xe3, 0xf7 };
m_buttonDropDownBmp = wxAuiBitmapFromBits(buttonDropdownBits, 5, 3,
*wxBLACK);
m_disabledButtonDropDownBmp = wxAuiBitmapFromBits(
buttonDropdownBits, 5, 3,
wxColor(128,128,128));
m_overflowBmp = wxAuiBitmapFromBits(overflowBits, 7, 6, *wxBLACK);
m_disabledOverflowBmp = wxAuiBitmapFromBits(overflowBits, 7, 6, wxColor(128,128,128));
m_font = *wxNORMAL_FONT;
}
wxAuiDefaultToolBarArt::~wxAuiDefaultToolBarArt()
{
m_font = *wxNORMAL_FONT;
}
wxAuiToolBarArt* wxAuiDefaultToolBarArt::Clone()
{
return static_cast<wxAuiToolBarArt*>(new wxAuiDefaultToolBarArt);
}
void wxAuiDefaultToolBarArt::SetFlags(unsigned int flags)
{
m_flags = flags;
}
void wxAuiDefaultToolBarArt::SetFont(const wxFont& font)
{
m_font = font;
}
void wxAuiDefaultToolBarArt::SetTextOrientation(int orientation)
{
m_textOrientation = orientation;
}
unsigned int wxAuiDefaultToolBarArt::GetFlags()
{
return m_flags;
}
wxFont wxAuiDefaultToolBarArt::GetFont()
{
return m_font;
}
int wxAuiDefaultToolBarArt::GetTextOrientation()
{
return m_textOrientation;
}
void wxAuiDefaultToolBarArt::DrawBackground(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxRect& _rect)
{
wxRect rect = _rect;
rect.height++;
wxColour startColour = m_baseColour.ChangeLightness(150);
wxColour endColour = m_baseColour.ChangeLightness(90);
dc.GradientFillLinear(rect, startColour, endColour, wxSOUTH);
}
void wxAuiDefaultToolBarArt::DrawPlainBackground(wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxRect& _rect)
{
wxRect rect = _rect;
rect.height++;
dc.SetBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
dc.DrawRectangle(rect.GetX() - 1, rect.GetY() - 1,
rect.GetWidth() + 2, rect.GetHeight() + 1);
}
void wxAuiDefaultToolBarArt::DrawLabel(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item,
const wxRect& rect)
{
dc.SetFont(m_font);
dc.SetTextForeground(*wxBLACK);
// we only care about the text height here since the text
// will get cropped based on the width of the item
int textWidth = 0, textHeight = 0;
dc.GetTextExtent(wxT("ABCDHgj"), &textWidth, &textHeight);
// set the clipping region
wxRect clipRect = rect;
clipRect.width -= 1;
dc.SetClippingRegion(clipRect);
int textX, textY;
textX = rect.x + 1;
textY = rect.y + (rect.height-textHeight)/2;
dc.DrawText(item.GetLabel(), textX, textY);
dc.DestroyClippingRegion();
}
void wxAuiDefaultToolBarArt::DrawButton(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item,
const wxRect& rect)
{
int textWidth = 0, textHeight = 0;
if (m_flags & wxAUI_TB_TEXT)
{
dc.SetFont(m_font);
int tx, ty;
dc.GetTextExtent(wxT("ABCDHgj"), &tx, &textHeight);
textWidth = 0;
dc.GetTextExtent(item.GetLabel(), &textWidth, &ty);
}
int bmpX = 0, bmpY = 0;
int textX = 0, textY = 0;
if (m_textOrientation == wxAUI_TBTOOL_TEXT_BOTTOM)
{
bmpX = rect.x +
(rect.width/2) -
(item.GetBitmap().GetWidth()/2);
bmpY = rect.y +
((rect.height-textHeight)/2) -
(item.GetBitmap().GetHeight()/2);
textX = rect.x + (rect.width/2) - (textWidth/2) + 1;
textY = rect.y + rect.height - textHeight - 1;
}
else if (m_textOrientation == wxAUI_TBTOOL_TEXT_RIGHT)
{
bmpX = rect.x + 3;
bmpY = rect.y +
(rect.height/2) -
(item.GetBitmap().GetHeight()/2);
textX = bmpX + 3 + item.GetBitmap().GetWidth();
textY = rect.y +
(rect.height/2) -
(textHeight/2);
}
if (!(item.GetState() & wxAUI_BUTTON_STATE_DISABLED))
{
if (item.GetState() & wxAUI_BUTTON_STATE_PRESSED)
{
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(150)));
dc.DrawRectangle(rect);
}
else if ((item.GetState() & wxAUI_BUTTON_STATE_HOVER) || item.IsSticky())
{
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(170)));
// draw an even lighter background for checked item hovers (since
// the hover background is the same color as the check background)
if (item.GetState() & wxAUI_BUTTON_STATE_CHECKED)
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(180)));
dc.DrawRectangle(rect);
}
else if (item.GetState() & wxAUI_BUTTON_STATE_CHECKED)
{
// it's important to put this code in an else statement after the
// hover, otherwise hovers won't draw properly for checked items
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(170)));
dc.DrawRectangle(rect);
}
}
wxBitmap bmp;
if (item.GetState() & wxAUI_BUTTON_STATE_DISABLED)
bmp = item.GetDisabledBitmap();
else
bmp = item.GetBitmap();
if ( bmp.IsOk() )
dc.DrawBitmap(bmp, bmpX, bmpY, true);
// set the item's text color based on if it is disabled
dc.SetTextForeground(*wxBLACK);
if (item.GetState() & wxAUI_BUTTON_STATE_DISABLED)
dc.SetTextForeground(DISABLED_TEXT_COLOR);
if ( (m_flags & wxAUI_TB_TEXT) && !item.GetLabel().empty() )
{
dc.DrawText(item.GetLabel(), textX, textY);
}
}
void wxAuiDefaultToolBarArt::DrawDropDownButton(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item,
const wxRect& rect)
{
int textWidth = 0, textHeight = 0, textX = 0, textY = 0;
int bmpX = 0, bmpY = 0, dropBmpX = 0, dropBmpY = 0;
wxRect buttonRect = wxRect(rect.x,
rect.y,
rect.width-BUTTON_DROPDOWN_WIDTH,
rect.height);
wxRect dropDownRect = wxRect(rect.x+rect.width-BUTTON_DROPDOWN_WIDTH-1,
rect.y,
BUTTON_DROPDOWN_WIDTH+1,
rect.height);
if (m_flags & wxAUI_TB_TEXT)
{
dc.SetFont(m_font);
int tx, ty;
if (m_flags & wxAUI_TB_TEXT)
{
dc.GetTextExtent(wxT("ABCDHgj"), &tx, &textHeight);
textWidth = 0;
}
dc.GetTextExtent(item.GetLabel(), &textWidth, &ty);
}
dropBmpX = dropDownRect.x +
(dropDownRect.width/2) -
(m_buttonDropDownBmp.GetWidth()/2);
dropBmpY = dropDownRect.y +
(dropDownRect.height/2) -
(m_buttonDropDownBmp.GetHeight()/2);
if (m_textOrientation == wxAUI_TBTOOL_TEXT_BOTTOM)
{
bmpX = buttonRect.x +
(buttonRect.width/2) -
(item.GetBitmap().GetWidth()/2);
bmpY = buttonRect.y +
((buttonRect.height-textHeight)/2) -
(item.GetBitmap().GetHeight()/2);
textX = rect.x + (rect.width/2) - (textWidth/2) + 1;
textY = rect.y + rect.height - textHeight - 1;
}
else if (m_textOrientation == wxAUI_TBTOOL_TEXT_RIGHT)
{
bmpX = rect.x + 3;
bmpY = rect.y +
(rect.height/2) -
(item.GetBitmap().GetHeight()/2);
textX = bmpX + 3 + item.GetBitmap().GetWidth();
textY = rect.y +
(rect.height/2) -
(textHeight/2);
}
if (item.GetState() & wxAUI_BUTTON_STATE_PRESSED)
{
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(140)));
dc.DrawRectangle(buttonRect);
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(170)));
dc.DrawRectangle(dropDownRect);
}
else if (item.GetState() & wxAUI_BUTTON_STATE_HOVER ||
item.IsSticky())
{
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(170)));
dc.DrawRectangle(buttonRect);
dc.DrawRectangle(dropDownRect);
}
else if (item.GetState() & wxAUI_BUTTON_STATE_CHECKED)
{
// Notice that this branch must come after the hover one to ensure the
// correct appearance when the mouse hovers over a checked item.m_
dc.SetPen(wxPen(m_highlightColour));
dc.SetBrush(wxBrush(m_highlightColour.ChangeLightness(170)));
dc.DrawRectangle(buttonRect);
dc.DrawRectangle(dropDownRect);
}
wxBitmap bmp;
wxBitmap dropbmp;
if (item.GetState() & wxAUI_BUTTON_STATE_DISABLED)
{
bmp = item.GetDisabledBitmap();
dropbmp = m_disabledButtonDropDownBmp;
}
else
{
bmp = item.GetBitmap();
dropbmp = m_buttonDropDownBmp;
}
if (!bmp.IsOk())
return;
dc.DrawBitmap(bmp, bmpX, bmpY, true);
dc.DrawBitmap(dropbmp, dropBmpX, dropBmpY, true);
// set the item's text color based on if it is disabled
dc.SetTextForeground(*wxBLACK);
if (item.GetState() & wxAUI_BUTTON_STATE_DISABLED)
dc.SetTextForeground(DISABLED_TEXT_COLOR);
if ( (m_flags & wxAUI_TB_TEXT) && !item.GetLabel().empty() )
{
dc.DrawText(item.GetLabel(), textX, textY);
}
}
void wxAuiDefaultToolBarArt::DrawControlLabel(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item,
const wxRect& rect)
{
if (!(m_flags & wxAUI_TB_TEXT))
return;
if (m_textOrientation != wxAUI_TBTOOL_TEXT_BOTTOM)
return;
int textX = 0, textY = 0;
int textWidth = 0, textHeight = 0;
dc.SetFont(m_font);
int tx, ty;
if (m_flags & wxAUI_TB_TEXT)
{
dc.GetTextExtent(wxT("ABCDHgj"), &tx, &textHeight);
textWidth = 0;
}
dc.GetTextExtent(item.GetLabel(), &textWidth, &ty);
// don't draw the label if it is wider than the item width
if (textWidth > rect.width)
return;
// set the label's text color
dc.SetTextForeground(*wxBLACK);
textX = rect.x + (rect.width/2) - (textWidth/2) + 1;
textY = rect.y + rect.height - textHeight - 1;
if ( (m_flags & wxAUI_TB_TEXT) && !item.GetLabel().empty() )
{
dc.DrawText(item.GetLabel(), textX, textY);
}
}
wxSize wxAuiDefaultToolBarArt::GetLabelSize(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item)
{
dc.SetFont(m_font);
// get label's height
int width = 0, height = 0;
dc.GetTextExtent(wxT("ABCDHgj"), &width, &height);
// get item's width
width = item.GetMinSize().GetWidth();
if (width == -1)
{
// no width specified, measure the text ourselves
width = dc.GetTextExtent(item.GetLabel()).GetX();
}
return wxSize(width, height);
}
wxSize wxAuiDefaultToolBarArt::GetToolSize(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxAuiToolBarItem& item)
{
if (!item.GetBitmap().IsOk() && !(m_flags & wxAUI_TB_TEXT))
return wxSize(16,16);
int width = item.GetBitmap().GetWidth();
int height = item.GetBitmap().GetHeight();
if (m_flags & wxAUI_TB_TEXT)
{
dc.SetFont(m_font);
int tx, ty;
if (m_textOrientation == wxAUI_TBTOOL_TEXT_BOTTOM)
{
dc.GetTextExtent(wxT("ABCDHgj"), &tx, &ty);
height += ty;
if ( !item.GetLabel().empty() )
{
dc.GetTextExtent(item.GetLabel(), &tx, &ty);
width = wxMax(width, tx+6);
}
}
else if ( m_textOrientation == wxAUI_TBTOOL_TEXT_RIGHT &&
!item.GetLabel().empty() )
{
width += 3; // space between left border and bitmap
width += 3; // space between bitmap and text
if ( !item.GetLabel().empty() )
{
dc.GetTextExtent(item.GetLabel(), &tx, &ty);
width += tx;
height = wxMax(height, ty);
}
}
}
// if the tool has a dropdown button, add it to the width
if (item.HasDropDown())
width += (BUTTON_DROPDOWN_WIDTH+4);
return wxSize(width, height);
}
void wxAuiDefaultToolBarArt::DrawSeparator(
wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxRect& _rect)
{
bool horizontal = true;
if (m_flags & wxAUI_TB_VERTICAL)
horizontal = false;
wxRect rect = _rect;
if (horizontal)
{
rect.x += (rect.width/2);
rect.width = 1;
int new_height = (rect.height*3)/4;
rect.y += (rect.height/2) - (new_height/2);
rect.height = new_height;
}
else
{
rect.y += (rect.height/2);
rect.height = 1;
int new_width = (rect.width*3)/4;
rect.x += (rect.width/2) - (new_width/2);
rect.width = new_width;
}
wxColour startColour = m_baseColour.ChangeLightness(80);
wxColour endColour = m_baseColour.ChangeLightness(80);
dc.GradientFillLinear(rect, startColour, endColour, horizontal ? wxSOUTH : wxEAST);
}
void wxAuiDefaultToolBarArt::DrawGripper(wxDC& dc,
wxWindow* WXUNUSED(wnd),
const wxRect& rect)
{
int i = 0;
while (1)
{
int x, y;
if (m_flags & wxAUI_TB_VERTICAL)
{
x = rect.x + (i*4) + 5;
y = rect.y + 3;
if (x > rect.GetWidth()-5)
break;
}
else
{
x = rect.x + 3;
y = rect.y + (i*4) + 5;
if (y > rect.GetHeight()-5)
break;
}
dc.SetPen(m_gripperPen1);
dc.DrawPoint(x, y);
dc.SetPen(m_gripperPen2);
dc.DrawPoint(x, y+1);
dc.DrawPoint(x+1, y);
dc.SetPen(m_gripperPen3);
dc.DrawPoint(x+2, y+1);
dc.DrawPoint(x+2, y+2);
dc.DrawPoint(x+1, y+2);
i++;
}
}
void wxAuiDefaultToolBarArt::DrawOverflowButton(wxDC& dc,
wxWindow* /*wnd*/,
const wxRect& rect,
int state)
{
if (state & wxAUI_BUTTON_STATE_HOVER ||
state & wxAUI_BUTTON_STATE_PRESSED)
{
wxColor light_gray_bg = m_highlightColour.ChangeLightness(170);
if (m_flags & wxAUI_TB_VERTICAL)
{
dc.SetPen(wxPen(m_highlightColour));
dc.DrawLine(rect.x, rect.y, rect.x+rect.width, rect.y);
dc.SetPen(wxPen(light_gray_bg));
dc.SetBrush(wxBrush(light_gray_bg));
dc.DrawRectangle(rect.x, rect.y+1, rect.width, rect.height);
}
else
{
dc.SetPen(wxPen(m_highlightColour));
dc.DrawLine(rect.x, rect.y, rect.x, rect.y+rect.height);
dc.SetPen(wxPen(light_gray_bg));
dc.SetBrush(wxBrush(light_gray_bg));
dc.DrawRectangle(rect.x+1, rect.y, rect.width, rect.height);
}
}
int x = rect.x+1+(rect.width-m_overflowBmp.GetWidth())/2;
int y = rect.y+1+(rect.height-m_overflowBmp.GetHeight())/2;
dc.DrawBitmap(m_overflowBmp, x, y, true);
}
int wxAuiDefaultToolBarArt::GetElementSize(int element_id)
{
switch (element_id)
{
case wxAUI_TBART_SEPARATOR_SIZE: return m_separatorSize;
case wxAUI_TBART_GRIPPER_SIZE: return m_gripperSize;
case wxAUI_TBART_OVERFLOW_SIZE: return m_overflowSize;
default: return 0;
}
}
void wxAuiDefaultToolBarArt::SetElementSize(int element_id, int size)
{
switch (element_id)
{
case wxAUI_TBART_SEPARATOR_SIZE: m_separatorSize = size; break;
case wxAUI_TBART_GRIPPER_SIZE: m_gripperSize = size; break;
case wxAUI_TBART_OVERFLOW_SIZE: m_overflowSize = size; break;
}
}
int wxAuiDefaultToolBarArt::ShowDropDown(wxWindow* wnd,
const wxAuiToolBarItemArray& items)
{
wxMenu menuPopup;
size_t items_added = 0;
size_t i, count = items.GetCount();
for (i = 0; i < count; ++i)
{
wxAuiToolBarItem& item = items.Item(i);
if (item.GetKind() == wxITEM_NORMAL)
{
wxString text = item.GetShortHelp();
if (text.empty())
text = item.GetLabel();
if (text.empty())
text = wxT(" ");
wxMenuItem* m = new wxMenuItem(&menuPopup, item.GetId(), text, item.GetShortHelp());
m->SetBitmap(item.GetBitmap());
menuPopup.Append(m);
items_added++;
}
else if (item.GetKind() == wxITEM_SEPARATOR)
{
if (items_added > 0)
menuPopup.AppendSeparator();
}
}
// find out where to put the popup menu of window items
wxPoint pt = ::wxGetMousePosition();
pt = wnd->ScreenToClient(pt);
// find out the screen coordinate at the bottom of the tab ctrl
wxRect cli_rect = wnd->GetClientRect();
pt.y = cli_rect.y + cli_rect.height;
ToolbarCommandCapture* cc = new ToolbarCommandCapture;
wnd->PushEventHandler(cc);
wnd->PopupMenu(&menuPopup, pt);
int command = cc->GetCommandId();
wnd->PopEventHandler(true);
return command;
}
static wxOrientation GetOrientation(long style)
{
switch (style & wxAUI_ORIENTATION_MASK)
{
case wxAUI_TB_HORIZONTAL:
return wxHORIZONTAL;
case wxAUI_TB_VERTICAL:
return wxVERTICAL;
default:
wxFAIL_MSG("toolbar cannot be locked in both horizontal and vertical orientations (maybe no lock was intended?)");
wxFALLTHROUGH;
case 0:
return wxBOTH;
}
}
BEGIN_EVENT_TABLE(wxAuiToolBar, wxControl)
EVT_SIZE(wxAuiToolBar::OnSize)
EVT_IDLE(wxAuiToolBar::OnIdle)
EVT_ERASE_BACKGROUND(wxAuiToolBar::OnEraseBackground)
EVT_PAINT(wxAuiToolBar::OnPaint)
EVT_LEFT_DOWN(wxAuiToolBar::OnLeftDown)
EVT_LEFT_DCLICK(wxAuiToolBar::OnLeftDown)
EVT_LEFT_UP(wxAuiToolBar::OnLeftUp)
EVT_RIGHT_DOWN(wxAuiToolBar::OnRightDown)
EVT_RIGHT_DCLICK(wxAuiToolBar::OnRightDown)
EVT_RIGHT_UP(wxAuiToolBar::OnRightUp)
EVT_MIDDLE_DOWN(wxAuiToolBar::OnMiddleDown)
EVT_MIDDLE_DCLICK(wxAuiToolBar::OnMiddleDown)
EVT_MIDDLE_UP(wxAuiToolBar::OnMiddleUp)
EVT_MOTION(wxAuiToolBar::OnMotion)
EVT_LEAVE_WINDOW(wxAuiToolBar::OnLeaveWindow)
EVT_MOUSE_CAPTURE_LOST(wxAuiToolBar::OnCaptureLost)
EVT_SET_CURSOR(wxAuiToolBar::OnSetCursor)
END_EVENT_TABLE()
void wxAuiToolBar::Init()
{
m_sizer = new wxBoxSizer(wxHORIZONTAL);
m_buttonWidth = -1;
m_buttonHeight = -1;
m_sizerElementCount = 0;
m_actionPos = wxDefaultPosition;
m_actionItem = NULL;
m_tipItem = NULL;
m_art = new wxAuiDefaultToolBarArt;
m_toolPacking = 2;
m_toolBorderPadding = 3;
m_toolTextOrientation = wxAUI_TBTOOL_TEXT_BOTTOM;
m_gripperSizerItem = NULL;
m_overflowSizerItem = NULL;
m_dragging = false;
m_gripperVisible = false;
m_overflowVisible = false;
m_overflowState = 0;
m_orientation = wxHORIZONTAL;
}
bool wxAuiToolBar::Create(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style)
{
style = style|wxBORDER_NONE;
if (!wxControl::Create(parent, id, pos, size, style))
return false;
m_windowStyle = style;
m_gripperVisible = (style & wxAUI_TB_GRIPPER) ? true : false;
m_overflowVisible = (style & wxAUI_TB_OVERFLOW) ? true : false;
m_orientation = GetOrientation(style);
if (m_orientation == wxBOTH)
{
m_orientation = wxHORIZONTAL;
}
SetMargins(5, 5, 2, 2);
SetFont(*wxNORMAL_FONT);
SetArtFlags();
SetExtraStyle(wxWS_EX_PROCESS_IDLE);
if (style & wxAUI_TB_HORZ_LAYOUT)
SetToolTextOrientation(wxAUI_TBTOOL_TEXT_RIGHT);
SetBackgroundStyle(wxBG_STYLE_CUSTOM);
return true;
}
wxAuiToolBar::~wxAuiToolBar()
{
delete m_art;
delete m_sizer;
}
void wxAuiToolBar::SetWindowStyleFlag(long style)
{
GetOrientation(style); // assert if style is invalid
wxCHECK_RET(IsPaneValid(style),
"window settings and pane settings are incompatible");
wxControl::SetWindowStyleFlag(style);
m_windowStyle = style;
if (m_art)
{
SetArtFlags();
}
if (m_windowStyle & wxAUI_TB_GRIPPER)
m_gripperVisible = true;
else
m_gripperVisible = false;
if (m_windowStyle & wxAUI_TB_OVERFLOW)
m_overflowVisible = true;
else
m_overflowVisible = false;
if (style & wxAUI_TB_HORZ_LAYOUT)
SetToolTextOrientation(wxAUI_TBTOOL_TEXT_RIGHT);
else
SetToolTextOrientation(wxAUI_TBTOOL_TEXT_BOTTOM);
}
void wxAuiToolBar::SetArtProvider(wxAuiToolBarArt* art)
{
delete m_art;
m_art = art;
if (m_art)
{
SetArtFlags();
m_art->SetTextOrientation(m_toolTextOrientation);
}
}
wxAuiToolBarArt* wxAuiToolBar::GetArtProvider() const
{
return m_art;
}
wxAuiToolBarItem* wxAuiToolBar::AddTool(int tool_id,
const wxString& label,
const wxBitmap& bitmap,
const wxString& shortHelp_string,
wxItemKind kind)
{
return AddTool(tool_id,
label,
bitmap,
wxNullBitmap,
kind,
shortHelp_string,
wxEmptyString,
NULL);
}
wxAuiToolBarItem* wxAuiToolBar::AddTool(int tool_id,
const wxString& label,
const wxBitmap& bitmap,
const wxBitmap& disabledBitmap,
wxItemKind kind,
const wxString& shortHelpString,
const wxString& longHelpString,
wxObject* WXUNUSED(client_data))
{
wxAuiToolBarItem item;
item.m_window = NULL;
item.m_label = label;
item.m_bitmap = bitmap;
item.m_disabledBitmap = disabledBitmap;
item.m_shortHelp = shortHelpString;
item.m_longHelp = longHelpString;
item.m_active = true;
item.m_dropDown = false;
item.m_spacerPixels = 0;
item.m_toolId = tool_id;
item.m_state = 0;
item.m_proportion = 0;
item.m_kind = kind;
item.m_sizerItem = NULL;
item.m_minSize = wxDefaultSize;
item.m_userData = 0;
item.m_sticky = false;
if (item.m_toolId == wxID_ANY)
item.m_toolId = wxNewId();
if (!item.m_disabledBitmap.IsOk())
{
// no disabled bitmap specified, we need to make one
if (item.m_bitmap.IsOk())
{
item.m_disabledBitmap = item.m_bitmap.ConvertToDisabled();
}
}
m_items.Add(item);
return &m_items.Last();
}
wxAuiToolBarItem* wxAuiToolBar::AddControl(wxControl* control,
const wxString& label)
{
wxAuiToolBarItem item;
item.m_window = (wxWindow*)control;
item.m_label = label;
item.m_bitmap = wxNullBitmap;
item.m_disabledBitmap = wxNullBitmap;
item.m_active = true;
item.m_dropDown = false;
item.m_spacerPixels = 0;
item.m_toolId = control->GetId();
item.m_state = 0;
item.m_proportion = 0;
item.m_kind = wxITEM_CONTROL;
item.m_sizerItem = NULL;
item.m_minSize = control->GetEffectiveMinSize();
item.m_userData = 0;
item.m_sticky = false;
m_items.Add(item);
return &m_items.Last();
}
wxAuiToolBarItem* wxAuiToolBar::AddLabel(int tool_id,
const wxString& label,
const int width)
{
wxSize min_size = wxDefaultSize;
if (width != -1)
min_size.x = width;
wxAuiToolBarItem item;
item.m_window = NULL;
item.m_label = label;
item.m_bitmap = wxNullBitmap;
item.m_disabledBitmap = wxNullBitmap;
item.m_active = true;
item.m_dropDown = false;
item.m_spacerPixels = 0;
item.m_toolId = tool_id;
item.m_state = 0;
item.m_proportion = 0;
item.m_kind = wxITEM_LABEL;
item.m_sizerItem = NULL;
item.m_minSize = min_size;
item.m_userData = 0;
item.m_sticky = false;
if (item.m_toolId == wxID_ANY)
item.m_toolId = wxNewId();
m_items.Add(item);
return &m_items.Last();
}
wxAuiToolBarItem* wxAuiToolBar::AddSeparator()
{
wxAuiToolBarItem item;
item.m_window = NULL;
item.m_label = wxEmptyString;
item.m_bitmap = wxNullBitmap;
item.m_disabledBitmap = wxNullBitmap;
item.m_active = true;
item.m_dropDown = false;
item.m_toolId = -1;
item.m_state = 0;
item.m_proportion = 0;
item.m_kind = wxITEM_SEPARATOR;
item.m_sizerItem = NULL;
item.m_minSize = wxDefaultSize;
item.m_userData = 0;
item.m_sticky = false;
m_items.Add(item);
return &m_items.Last();
}
wxAuiToolBarItem* wxAuiToolBar::AddSpacer(int pixels)
{
wxAuiToolBarItem item;
item.m_window = NULL;
item.m_label = wxEmptyString;
item.m_bitmap = wxNullBitmap;
item.m_disabledBitmap = wxNullBitmap;
item.m_active = true;
item.m_dropDown = false;
item.m_spacerPixels = pixels;
item.m_toolId = -1;
item.m_state = 0;
item.m_proportion = 0;
item.m_kind = wxITEM_SPACER;
item.m_sizerItem = NULL;
item.m_minSize = wxDefaultSize;
item.m_userData = 0;
item.m_sticky = false;
m_items.Add(item);
return &m_items.Last();
}
wxAuiToolBarItem* wxAuiToolBar::AddStretchSpacer(int proportion)
{
wxAuiToolBarItem item;
item.m_window = NULL;
item.m_label = wxEmptyString;
item.m_bitmap = wxNullBitmap;
item.m_disabledBitmap = wxNullBitmap;
item.m_active = true;
item.m_dropDown = false;
item.m_spacerPixels = 0;
item.m_toolId = -1;
item.m_state = 0;
item.m_proportion = proportion;
item.m_kind = wxITEM_SPACER;
item.m_sizerItem = NULL;
item.m_minSize = wxDefaultSize;
item.m_userData = 0;
item.m_sticky = false;
m_items.Add(item);
return &m_items.Last();
}
void wxAuiToolBar::Clear()
{
m_items.Clear();
m_sizerElementCount = 0;
}
bool wxAuiToolBar::DeleteTool(int tool_id)
{
int idx = GetToolIndex(tool_id);
if (idx >= 0 && idx < (int)m_items.GetCount())
{
m_items.RemoveAt(idx);
Realize();
return true;
}
return false;
}
bool wxAuiToolBar::DeleteByIndex(int idx)
{
if (idx >= 0 && idx < (int)m_items.GetCount())
{
m_items.RemoveAt(idx);
Realize();
return true;
}
return false;
}
wxControl* wxAuiToolBar::FindControl(int id)
{
wxWindow* wnd = FindWindow(id);
return (wxControl*)wnd;
}
wxAuiToolBarItem* wxAuiToolBar::FindTool(int tool_id) const
{
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_toolId == tool_id)
return &item;
}
return NULL;
}
wxAuiToolBarItem* wxAuiToolBar::FindToolByPosition(wxCoord x, wxCoord y) const
{
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (!item.m_sizerItem)
continue;
wxRect rect = item.m_sizerItem->GetRect();
if (rect.Contains(x,y))
{
// if the item doesn't fit on the toolbar, return NULL
if (!GetToolFitsByIndex(i))
return NULL;
return &item;
}
}
return NULL;
}
wxAuiToolBarItem* wxAuiToolBar::FindToolByPositionWithPacking(wxCoord x, wxCoord y) const
{
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (!item.m_sizerItem)
continue;
wxRect rect = item.m_sizerItem->GetRect();
// apply tool packing
if (i+1 < count)
rect.width += m_toolPacking;
if (rect.Contains(x,y))
{
// if the item doesn't fit on the toolbar, return NULL
if (!GetToolFitsByIndex(i))
return NULL;
return &item;
}
}
return NULL;
}
wxAuiToolBarItem* wxAuiToolBar::FindToolByIndex(int idx) const
{
if (idx < 0)
return NULL;
if (idx >= (int)m_items.size())
return NULL;
return &(m_items[idx]);
}
void wxAuiToolBar::SetToolBitmapSize(const wxSize& WXUNUSED(size))
{
// TODO: wxToolBar compatibility
}
wxSize wxAuiToolBar::GetToolBitmapSize() const
{
// TODO: wxToolBar compatibility
return wxSize(16,15);
}
void wxAuiToolBar::SetToolProportion(int tool_id, int proportion)
{
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return;
item->m_proportion = proportion;
}
int wxAuiToolBar::GetToolProportion(int tool_id) const
{
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return 0;
return item->m_proportion;
}
void wxAuiToolBar::SetToolSeparation(int separation)
{
if (m_art)
m_art->SetElementSize(wxAUI_TBART_SEPARATOR_SIZE, separation);
}
int wxAuiToolBar::GetToolSeparation() const
{
if (m_art)
return m_art->GetElementSize(wxAUI_TBART_SEPARATOR_SIZE);
else
return 5;
}
void wxAuiToolBar::SetToolDropDown(int tool_id, bool dropdown)
{
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return;
item->SetHasDropDown(dropdown);
}
bool wxAuiToolBar::GetToolDropDown(int tool_id) const
{
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return false;
return item->HasDropDown();
}
void wxAuiToolBar::SetToolSticky(int tool_id, bool sticky)
{
// ignore separators
if (tool_id == -1)
return;
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return;
if (item->m_sticky == sticky)
return;
item->m_sticky = sticky;
Refresh(false);
Update();
}
bool wxAuiToolBar::GetToolSticky(int tool_id) const
{
wxAuiToolBarItem* item = FindTool(tool_id);
if (!item)
return 0;
return item->m_sticky;
}
void wxAuiToolBar::SetToolBorderPadding(int padding)
{
m_toolBorderPadding = padding;
}
int wxAuiToolBar::GetToolBorderPadding() const
{
return m_toolBorderPadding;
}
void wxAuiToolBar::SetToolTextOrientation(int orientation)
{
m_toolTextOrientation = orientation;
if (m_art)
{
m_art->SetTextOrientation(orientation);
}
}
int wxAuiToolBar::GetToolTextOrientation() const
{
return m_toolTextOrientation;
}
void wxAuiToolBar::SetToolPacking(int packing)
{
m_toolPacking = packing;
}
int wxAuiToolBar::GetToolPacking() const
{
return m_toolPacking;
}
void wxAuiToolBar::SetOrientation(int orientation)
{
wxCHECK_RET(orientation == wxHORIZONTAL ||
orientation == wxVERTICAL,
"invalid orientation value");
if (orientation != m_orientation)
{
m_orientation = wxOrientation(orientation);
SetArtFlags();
}
}
void wxAuiToolBar::SetMargins(int left, int right, int top, int bottom)
{
if (left != -1)
m_leftPadding = left;
if (right != -1)
m_rightPadding = right;
if (top != -1)
m_topPadding = top;
if (bottom != -1)
m_bottomPadding = bottom;
}
bool wxAuiToolBar::GetGripperVisible() const
{
return m_gripperVisible;
}
void wxAuiToolBar::SetGripperVisible(bool visible)
{
m_gripperVisible = visible;
if (visible)
m_windowStyle |= wxAUI_TB_GRIPPER;
else
m_windowStyle &= ~wxAUI_TB_GRIPPER;
Realize();
Refresh(false);
}
bool wxAuiToolBar::GetOverflowVisible() const
{
return m_overflowVisible;
}
void wxAuiToolBar::SetOverflowVisible(bool visible)
{
m_overflowVisible = visible;
if (visible)
m_windowStyle |= wxAUI_TB_OVERFLOW;
else
m_windowStyle &= ~wxAUI_TB_OVERFLOW;
Refresh(false);
}
bool wxAuiToolBar::SetFont(const wxFont& font)
{
bool res = wxWindow::SetFont(font);
if (m_art)
{
m_art->SetFont(font);
}
return res;
}
void wxAuiToolBar::SetHoverItem(wxAuiToolBarItem* pitem)
{
if (pitem && (pitem->m_state & wxAUI_BUTTON_STATE_DISABLED))
pitem = NULL;
wxAuiToolBarItem* former_hover = NULL;
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_state & wxAUI_BUTTON_STATE_HOVER)
former_hover = &item;
item.m_state &= ~wxAUI_BUTTON_STATE_HOVER;
}
if (pitem)
{
pitem->m_state |= wxAUI_BUTTON_STATE_HOVER;
}
if (former_hover != pitem)
{
Refresh(false);
Update();
}
}
void wxAuiToolBar::SetPressedItem(wxAuiToolBarItem* pitem)
{
wxAuiToolBarItem* former_item = NULL;
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_state & wxAUI_BUTTON_STATE_PRESSED)
former_item = &item;
item.m_state &= ~wxAUI_BUTTON_STATE_PRESSED;
}
if (pitem)
{
pitem->m_state &= ~wxAUI_BUTTON_STATE_HOVER;
pitem->m_state |= wxAUI_BUTTON_STATE_PRESSED;
}
if (former_item != pitem)
{
Refresh(false);
Update();
}
}
void wxAuiToolBar::RefreshOverflowState()
{
if (!m_overflowSizerItem)
{
m_overflowState = 0;
return;
}
int overflow_state = 0;
wxRect overflow_rect = GetOverflowRect();
// find out the mouse's current position
wxPoint pt = ::wxGetMousePosition();
pt = this->ScreenToClient(pt);
// find out if the mouse cursor is inside the dropdown rectangle
if (overflow_rect.Contains(pt.x, pt.y))
{
if (::wxGetMouseState().LeftIsDown())
overflow_state = wxAUI_BUTTON_STATE_PRESSED;
else
overflow_state = wxAUI_BUTTON_STATE_HOVER;
}
if (overflow_state != m_overflowState)
{
m_overflowState = overflow_state;
Refresh(false);
Update();
}
m_overflowState = overflow_state;
}
void wxAuiToolBar::ToggleTool(int tool_id, bool state)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool && (tool->m_kind == wxITEM_CHECK || tool->m_kind == wxITEM_RADIO))
{
if (tool->m_kind == wxITEM_RADIO)
{
int i, idx, count;
idx = GetToolIndex(tool_id);
count = (int)m_items.GetCount();
if (idx >= 0 && idx < count)
{
for (i = idx + 1; i < count; ++i)
{
if (m_items[i].m_kind != wxITEM_RADIO)
break;
m_items[i].m_state &= ~wxAUI_BUTTON_STATE_CHECKED;
}
for (i = idx - 1; i >= 0; i--)
{
if (m_items[i].m_kind != wxITEM_RADIO)
break;
m_items[i].m_state &= ~wxAUI_BUTTON_STATE_CHECKED;
}
}
tool->m_state |= wxAUI_BUTTON_STATE_CHECKED;
}
else if (tool->m_kind == wxITEM_CHECK)
{
if (state == true)
tool->m_state |= wxAUI_BUTTON_STATE_CHECKED;
else
tool->m_state &= ~wxAUI_BUTTON_STATE_CHECKED;
}
}
}
bool wxAuiToolBar::GetToolToggled(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
if ( (tool->m_kind != wxITEM_CHECK) && (tool->m_kind != wxITEM_RADIO) )
return false;
return (tool->m_state & wxAUI_BUTTON_STATE_CHECKED) ? true : false;
}
return false;
}
void wxAuiToolBar::EnableTool(int tool_id, bool state)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
if (state == true)
tool->m_state &= ~wxAUI_BUTTON_STATE_DISABLED;
else
tool->m_state |= wxAUI_BUTTON_STATE_DISABLED;
}
}
bool wxAuiToolBar::GetToolEnabled(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
return (tool->m_state & wxAUI_BUTTON_STATE_DISABLED) ? false : true;
return false;
}
wxString wxAuiToolBar::GetToolLabel(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
wxASSERT_MSG(tool, wxT("can't find tool in toolbar item array"));
if (!tool)
return wxEmptyString;
return tool->m_label;
}
void wxAuiToolBar::SetToolLabel(int tool_id, const wxString& label)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
tool->m_label = label;
}
}
wxBitmap wxAuiToolBar::GetToolBitmap(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
wxASSERT_MSG(tool, wxT("can't find tool in toolbar item array"));
if (!tool)
return wxNullBitmap;
return tool->m_bitmap;
}
void wxAuiToolBar::SetToolBitmap(int tool_id, const wxBitmap& bitmap)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
tool->m_bitmap = bitmap;
}
}
wxString wxAuiToolBar::GetToolShortHelp(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
wxASSERT_MSG(tool, wxT("can't find tool in toolbar item array"));
if (!tool)
return wxEmptyString;
return tool->m_shortHelp;
}
void wxAuiToolBar::SetToolShortHelp(int tool_id, const wxString& help_string)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
tool->m_shortHelp = help_string;
}
}
wxString wxAuiToolBar::GetToolLongHelp(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
wxASSERT_MSG(tool, wxT("can't find tool in toolbar item array"));
if (!tool)
return wxEmptyString;
return tool->m_longHelp;
}
void wxAuiToolBar::SetToolLongHelp(int tool_id, const wxString& help_string)
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool)
{
tool->m_longHelp = help_string;
}
}
void wxAuiToolBar::SetCustomOverflowItems(const wxAuiToolBarItemArray& prepend,
const wxAuiToolBarItemArray& append)
{
m_customOverflowPrepend = prepend;
m_customOverflowAppend = append;
}
// get size of hint rectangle for a particular dock location
wxSize wxAuiToolBar::GetHintSize(int dock_direction) const
{
switch (dock_direction)
{
case wxAUI_DOCK_TOP:
case wxAUI_DOCK_BOTTOM:
return m_horzHintSize;
case wxAUI_DOCK_RIGHT:
case wxAUI_DOCK_LEFT:
return m_vertHintSize;
default:
wxFAIL_MSG("invalid dock location value");
}
return wxDefaultSize;
}
bool wxAuiToolBar::IsPaneValid(const wxAuiPaneInfo& pane) const
{
return IsPaneValid(m_windowStyle, pane);
}
bool wxAuiToolBar::IsPaneValid(long style, const wxAuiPaneInfo& pane)
{
if (style & wxAUI_TB_HORIZONTAL)
{
if (pane.IsLeftDockable() || pane.IsRightDockable())
{
return false;
}
}
else if (style & wxAUI_TB_VERTICAL)
{
if (pane.IsTopDockable() || pane.IsBottomDockable())
{
return false;
}
}
return true;
}
bool wxAuiToolBar::IsPaneValid(long style) const
{
wxAuiManager* manager = wxAuiManager::GetManager(const_cast<wxAuiToolBar*>(this));
if (manager)
{
return IsPaneValid(style, manager->GetPane(const_cast<wxAuiToolBar*>(this)));
}
return true;
}
void wxAuiToolBar::SetArtFlags() const
{
unsigned int artflags = m_windowStyle & ~wxAUI_ORIENTATION_MASK;
if (m_orientation == wxVERTICAL)
{
artflags |= wxAUI_TB_VERTICAL;
}
m_art->SetFlags(artflags);
}
size_t wxAuiToolBar::GetToolCount() const
{
return m_items.size();
}
int wxAuiToolBar::GetToolIndex(int tool_id) const
{
// this will prevent us from returning the index of the
// first separator in the toolbar since its id is equal to -1
if (tool_id == -1)
return wxNOT_FOUND;
size_t i, count = m_items.GetCount();
for (i = 0; i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_toolId == tool_id)
return i;
}
return wxNOT_FOUND;
}
bool wxAuiToolBar::GetToolFitsByIndex(int tool_idx) const
{
if (tool_idx < 0 || tool_idx >= (int)m_items.GetCount())
return false;
if (!m_items[tool_idx].m_sizerItem)
return false;
int cli_w, cli_h;
GetClientSize(&cli_w, &cli_h);
wxRect rect = m_items[tool_idx].m_sizerItem->GetRect();
if (m_orientation == wxVERTICAL)
{
// take the dropdown size into account
if (m_overflowVisible && m_overflowSizerItem)
cli_h -= m_overflowSizerItem->GetSize().y;
if (rect.y+rect.height < cli_h)
return true;
}
else
{
// take the dropdown size into account
if (m_overflowVisible && m_overflowSizerItem)
cli_w -= m_overflowSizerItem->GetSize().x;
if (rect.x+rect.width < cli_w)
return true;
}
return false;
}
bool wxAuiToolBar::GetToolFits(int tool_id) const
{
return GetToolFitsByIndex(GetToolIndex(tool_id));
}
wxRect wxAuiToolBar::GetToolRect(int tool_id) const
{
wxAuiToolBarItem* tool = FindTool(tool_id);
if (tool && tool->m_sizerItem)
{
return tool->m_sizerItem->GetRect();
}
return wxRect();
}
bool wxAuiToolBar::GetToolBarFits() const
{
if (m_items.GetCount() == 0)
{
// empty toolbar always 'fits'
return true;
}
// entire toolbar content fits if the last tool fits
return GetToolFitsByIndex(m_items.GetCount() - 1);
}
bool wxAuiToolBar::Realize()
{
wxClientDC dc(this);
if (!dc.IsOk())
return false;
// calculate hint sizes for both horizontal and vertical
// in the order that leaves toolbar in correct final state
bool retval = false;
if (m_orientation == wxHORIZONTAL)
{
if (RealizeHelper(dc, false))
{
m_vertHintSize = GetSize();
if (RealizeHelper(dc, true))
{
m_horzHintSize = GetSize();
retval = true;
}
}
}
else
{
if (RealizeHelper(dc, true))
{
m_horzHintSize = GetSize();
if (RealizeHelper(dc, false))
{
m_vertHintSize = GetSize();
retval = true;
}
}
}
Refresh(false);
return retval;
}
bool wxAuiToolBar::RealizeHelper(wxClientDC& dc, bool horizontal)
{
// create the new sizer to add toolbar elements to
wxBoxSizer* sizer = new wxBoxSizer(horizontal ? wxHORIZONTAL : wxVERTICAL);
// add gripper area
int separatorSize = m_art->GetElementSize(wxAUI_TBART_SEPARATOR_SIZE);
int gripperSize = m_art->GetElementSize(wxAUI_TBART_GRIPPER_SIZE);
if (gripperSize > 0 && m_gripperVisible)
{
if (horizontal)
m_gripperSizerItem = sizer->Add(gripperSize, 1, 0, wxEXPAND);
else
m_gripperSizerItem = sizer->Add(1, gripperSize, 0, wxEXPAND);
}
else
{
m_gripperSizerItem = NULL;
}
// add "left" padding
if (m_leftPadding > 0)
{
if (horizontal)
sizer->Add(m_leftPadding, 1);
else
sizer->Add(1, m_leftPadding);
}
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
wxSizerItem* m_sizerItem = NULL;
switch (item.m_kind)
{
case wxITEM_LABEL:
{
wxSize size = m_art->GetLabelSize(dc, this, item);
m_sizerItem = sizer->Add(size.x + (m_toolBorderPadding*2),
size.y + (m_toolBorderPadding*2),
item.m_proportion,
item.m_alignment);
if (i+1 < count)
{
sizer->AddSpacer(m_toolPacking);
}
break;
}
case wxITEM_CHECK:
case wxITEM_NORMAL:
case wxITEM_RADIO:
{
wxSize size = m_art->GetToolSize(dc, this, item);
m_sizerItem = sizer->Add(size.x + (m_toolBorderPadding*2),
size.y + (m_toolBorderPadding*2),
0,
item.m_alignment);
// add tool packing
if (i+1 < count)
{
sizer->AddSpacer(m_toolPacking);
}
break;
}
case wxITEM_SEPARATOR:
{
if (horizontal)
m_sizerItem = sizer->Add(separatorSize, 1, 0, wxEXPAND);
else
m_sizerItem = sizer->Add(1, separatorSize, 0, wxEXPAND);
// add tool packing
if (i+1 < count)
{
sizer->AddSpacer(m_toolPacking);
}
break;
}
case wxITEM_SPACER:
if (item.m_proportion > 0)
m_sizerItem = sizer->AddStretchSpacer(item.m_proportion);
else
m_sizerItem = sizer->Add(item.m_spacerPixels, 1);
break;
case wxITEM_CONTROL:
{
//m_sizerItem = sizer->Add(item.m_window, item.m_proportion, wxEXPAND);
wxSizerItem* ctrl_m_sizerItem;
wxBoxSizer* vert_sizer = new wxBoxSizer(wxVERTICAL);
vert_sizer->AddStretchSpacer(1);
ctrl_m_sizerItem = vert_sizer->Add(item.m_window, 0, wxEXPAND);
vert_sizer->AddStretchSpacer(1);
if ( (m_windowStyle & wxAUI_TB_TEXT) &&
m_toolTextOrientation == wxAUI_TBTOOL_TEXT_BOTTOM &&
!item.GetLabel().empty() )
{
wxSize s = GetLabelSize(item.GetLabel());
vert_sizer->Add(1, s.y);
}
m_sizerItem = sizer->Add(vert_sizer, item.m_proportion, wxEXPAND);
wxSize min_size = item.m_minSize;
// proportional items will disappear from the toolbar if
// their min width is not set to something really small
if (item.m_proportion != 0)
{
min_size.x = 1;
}
if (min_size.IsFullySpecified())
{
m_sizerItem->SetMinSize(min_size);
ctrl_m_sizerItem->SetMinSize(min_size);
}
// add tool packing
if (i+1 < count)
{
sizer->AddSpacer(m_toolPacking);
}
}
}
item.m_sizerItem = m_sizerItem;
}
// add "right" padding
if (m_rightPadding > 0)
{
if (horizontal)
sizer->Add(m_rightPadding, 1);
else
sizer->Add(1, m_rightPadding);
}
// add drop down area
m_overflowSizerItem = NULL;
if (m_windowStyle & wxAUI_TB_OVERFLOW)
{
int overflow_size = m_art->GetElementSize(wxAUI_TBART_OVERFLOW_SIZE);
if (overflow_size > 0 && m_overflowVisible)
{
if (horizontal)
m_overflowSizerItem = sizer->Add(overflow_size, 1, 0, wxEXPAND);
else
m_overflowSizerItem = sizer->Add(1, overflow_size, 0, wxEXPAND);
}
else
{
m_overflowSizerItem = NULL;
}
}
// the outside sizer helps us apply the "top" and "bottom" padding
wxBoxSizer* outside_sizer = new wxBoxSizer(horizontal ? wxVERTICAL : wxHORIZONTAL);
// add "top" padding
if (m_topPadding > 0)
{
if (horizontal)
outside_sizer->Add(1, m_topPadding);
else
outside_sizer->Add(m_topPadding, 1);
}
// add the sizer that contains all of the toolbar elements
outside_sizer->Add(sizer, 1, wxEXPAND);
// add "bottom" padding
if (m_bottomPadding > 0)
{
if (horizontal)
outside_sizer->Add(1, m_bottomPadding);
else
outside_sizer->Add(m_bottomPadding, 1);
}
delete m_sizer; // remove old sizer
m_sizer = outside_sizer;
// calculate the rock-bottom minimum size
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_sizerItem && item.m_proportion > 0 && item.m_minSize.IsFullySpecified())
item.m_sizerItem->SetMinSize(0,0);
}
m_absoluteMinSize = m_sizer->GetMinSize();
// reset the min sizes to what they were
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_sizerItem && item.m_proportion > 0 && item.m_minSize.IsFullySpecified())
item.m_sizerItem->SetMinSize(item.m_minSize);
}
// set control size
wxSize size = m_sizer->GetMinSize();
m_minWidth = size.x;
m_minHeight = size.y;
if ((m_windowStyle & wxAUI_TB_NO_AUTORESIZE) == 0)
{
wxSize curSize = GetClientSize();
wxSize new_size = GetMinSize();
if (new_size != curSize)
{
SetClientSize(new_size);
}
else
{
m_sizer->SetDimension(0, 0, curSize.x, curSize.y);
}
}
else
{
wxSize curSize = GetClientSize();
m_sizer->SetDimension(0, 0, curSize.x, curSize.y);
}
return true;
}
int wxAuiToolBar::GetOverflowState() const
{
return m_overflowState;
}
wxRect wxAuiToolBar::GetOverflowRect() const
{
wxRect cli_rect(wxPoint(0,0), GetClientSize());
wxRect overflow_rect = m_overflowSizerItem->GetRect();
int overflow_size = m_art->GetElementSize(wxAUI_TBART_OVERFLOW_SIZE);
if (m_orientation == wxVERTICAL)
{
overflow_rect.y = cli_rect.height - overflow_size;
overflow_rect.x = 0;
overflow_rect.width = cli_rect.width;
overflow_rect.height = overflow_size;
}
else
{
overflow_rect.x = cli_rect.width - overflow_size;
overflow_rect.y = 0;
overflow_rect.width = overflow_size;
overflow_rect.height = cli_rect.height;
}
return overflow_rect;
}
wxSize wxAuiToolBar::GetLabelSize(const wxString& label)
{
wxClientDC dc(this);
int tx, ty;
int textWidth = 0, textHeight = 0;
dc.SetFont(m_font);
// get the text height
dc.GetTextExtent(wxT("ABCDHgj"), &tx, &textHeight);
// get the text width
dc.GetTextExtent(label, &textWidth, &ty);
return wxSize(textWidth, textHeight);
}
void wxAuiToolBar::DoIdleUpdate()
{
wxEvtHandler* handler = GetEventHandler();
bool need_refresh = false;
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_toolId == -1)
continue;
wxUpdateUIEvent evt(item.m_toolId);
evt.SetEventObject(this);
if (handler->ProcessEvent(evt))
{
if (evt.GetSetEnabled())
{
bool is_enabled;
if (item.m_window)
is_enabled = item.m_window->IsThisEnabled();
else
is_enabled = (item.m_state & wxAUI_BUTTON_STATE_DISABLED) ? false : true;
bool new_enabled = evt.GetEnabled();
if (new_enabled != is_enabled)
{
if (item.m_window)
{
item.m_window->Enable(new_enabled);
}
else
{
if (new_enabled)
item.m_state &= ~wxAUI_BUTTON_STATE_DISABLED;
else
item.m_state |= wxAUI_BUTTON_STATE_DISABLED;
}
need_refresh = true;
}
}
if (evt.GetSetChecked())
{
// make sure we aren't checking an item that can't be
if (item.m_kind != wxITEM_CHECK && item.m_kind != wxITEM_RADIO)
continue;
bool is_checked = (item.m_state & wxAUI_BUTTON_STATE_CHECKED) ? true : false;
bool new_checked = evt.GetChecked();
if (new_checked != is_checked)
{
if (new_checked)
item.m_state |= wxAUI_BUTTON_STATE_CHECKED;
else
item.m_state &= ~wxAUI_BUTTON_STATE_CHECKED;
need_refresh = true;
}
}
}
}
if (need_refresh)
{
Refresh(false);
}
}
void wxAuiToolBar::OnSize(wxSizeEvent& WXUNUSED(evt))
{
int x, y;
GetClientSize(&x, &y);
if (((x >= y) && m_absoluteMinSize.x > x) ||
((y > x) && m_absoluteMinSize.y > y))
{
// hide all flexible items
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_sizerItem && item.m_proportion > 0 && item.m_sizerItem->IsShown())
{
item.m_sizerItem->Show(false);
item.m_sizerItem->SetProportion(0);
}
}
}
else
{
// show all flexible items
size_t i, count;
for (i = 0, count = m_items.GetCount(); i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (item.m_sizerItem && item.m_proportion > 0 && !item.m_sizerItem->IsShown())
{
item.m_sizerItem->Show(true);
item.m_sizerItem->SetProportion(item.m_proportion);
}
}
}
m_sizer->SetDimension(0, 0, x, y);
Refresh(false);
Update();
// idle events aren't sent while user is resizing frame (why?),
// but resizing toolbar here causes havoc,
// so force idle handler to run after size handling complete
QueueEvent(new wxIdleEvent);
}
void wxAuiToolBar::DoSetSize(int x,
int y,
int width,
int height,
int sizeFlags)
{
wxSize parent_size = GetParent()->GetClientSize();
if (x + width > parent_size.x)
width = wxMax(0, parent_size.x - x);
if (y + height > parent_size.y)
height = wxMax(0, parent_size.y - y);
wxWindow::DoSetSize(x, y, width, height, sizeFlags);
}
void wxAuiToolBar::OnIdle(wxIdleEvent& evt)
{
// if orientation doesn't match dock, fix it
wxAuiManager* manager = wxAuiManager::GetManager(this);
if (manager)
{
wxAuiPaneInfo& pane = manager->GetPane(this);
// pane state member is public, so it might have been changed
// without going through wxPaneInfo::SetFlag() check
bool ok = pane.IsOk();
wxCHECK2_MSG(!ok || IsPaneValid(m_windowStyle, pane), ok = false,
"window settings and pane settings are incompatible");
if (ok)
{
wxOrientation newOrientation = m_orientation;
if (pane.IsDocked())
{
switch (pane.dock_direction)
{
case wxAUI_DOCK_TOP:
case wxAUI_DOCK_BOTTOM:
newOrientation = wxHORIZONTAL;
break;
case wxAUI_DOCK_LEFT:
case wxAUI_DOCK_RIGHT:
newOrientation = wxVERTICAL;
break;
default:
wxFAIL_MSG("invalid dock location value");
}
}
else if (pane.IsResizable() &&
GetOrientation(m_windowStyle) == wxBOTH)
{
// changing orientation in OnSize causes havoc
int x, y;
GetClientSize(&x, &y);
if (x > y)
{
newOrientation = wxHORIZONTAL;
}
else
{
newOrientation = wxVERTICAL;
}
}
if (newOrientation != m_orientation)
{
SetOrientation(newOrientation);
Realize();
if (newOrientation == wxHORIZONTAL)
{
pane.best_size = GetHintSize(wxAUI_DOCK_TOP);
}
else
{
pane.best_size = GetHintSize(wxAUI_DOCK_LEFT);
}
if (pane.IsDocked())
{
pane.floating_size = wxDefaultSize;
}
else
{
SetSize(GetParent()->GetClientSize());
}
manager->Update();
}
}
}
evt.Skip();
}
void wxAuiToolBar::UpdateWindowUI(long flags)
{
if ( flags & wxUPDATE_UI_FROMIDLE )
{
DoIdleUpdate();
}
wxControl::UpdateWindowUI(flags);
}
void wxAuiToolBar::OnPaint(wxPaintEvent& WXUNUSED(evt))
{
wxAutoBufferedPaintDC dc(this);
wxRect cli_rect(wxPoint(0,0), GetClientSize());
bool horizontal = m_orientation == wxHORIZONTAL;
if (m_windowStyle & wxAUI_TB_PLAIN_BACKGROUND)
m_art->DrawPlainBackground(dc, this, cli_rect);
else
m_art->DrawBackground(dc, this, cli_rect);
int gripperSize = m_art->GetElementSize(wxAUI_TBART_GRIPPER_SIZE);
int dropdown_size = m_art->GetElementSize(wxAUI_TBART_OVERFLOW_SIZE);
// paint the gripper
if (gripperSize > 0 && m_gripperSizerItem)
{
wxRect gripper_rect = m_gripperSizerItem->GetRect();
if (horizontal)
gripper_rect.width = gripperSize;
else
gripper_rect.height = gripperSize;
m_art->DrawGripper(dc, this, gripper_rect);
}
// calculated how far we can draw items
int last_extent;
if (horizontal)
last_extent = cli_rect.width;
else
last_extent = cli_rect.height;
if (m_overflowVisible)
last_extent -= dropdown_size;
// paint each individual tool
size_t i, count = m_items.GetCount();
for (i = 0; i < count; ++i)
{
wxAuiToolBarItem& item = m_items.Item(i);
if (!item.m_sizerItem)
continue;
wxRect item_rect = item.m_sizerItem->GetRect();
if ((horizontal && item_rect.x + item_rect.width >= last_extent) ||
(!horizontal && item_rect.y + item_rect.height >= last_extent))
{
break;
}
switch ( item.m_kind )
{
case wxITEM_NORMAL:
// draw a regular or dropdown button
if (!item.m_dropDown)
m_art->DrawButton(dc, this, item, item_rect);
else
m_art->DrawDropDownButton(dc, this, item, item_rect);
break;
case wxITEM_CHECK:
case wxITEM_RADIO:
// draw a toggle button
m_art->DrawButton(dc, this, item, item_rect);
break;
case wxITEM_SEPARATOR:
// draw a separator
m_art->DrawSeparator(dc, this, item_rect);
break;
case wxITEM_LABEL:
// draw a text label only
m_art->DrawLabel(dc, this, item, item_rect);
break;
case wxITEM_CONTROL:
// draw the control's label
m_art->DrawControlLabel(dc, this, item, item_rect);
break;
}
// fire a signal to see if the item wants to be custom-rendered
OnCustomRender(dc, item, item_rect);
}
// paint the overflow button
if (dropdown_size > 0 && m_overflowSizerItem)
{
wxRect dropDownRect = GetOverflowRect();
m_art->DrawOverflowButton(dc, this, dropDownRect, m_overflowState);
}
}
void wxAuiToolBar::OnEraseBackground(wxEraseEvent& WXUNUSED(evt))
{
// empty
}
void wxAuiToolBar::OnLeftDown(wxMouseEvent& evt)
{
wxRect cli_rect(wxPoint(0,0), GetClientSize());
if (m_gripperSizerItem)
{
wxRect gripper_rect = m_gripperSizerItem->GetRect();
if (gripper_rect.Contains(evt.GetX(), evt.GetY()))
{
// find aui manager
wxAuiManager* manager = wxAuiManager::GetManager(this);
if (!manager)
return;
int x_drag_offset = evt.GetX() - gripper_rect.GetX();
int y_drag_offset = evt.GetY() - gripper_rect.GetY();
// gripper was clicked
manager->StartPaneDrag(this, wxPoint(x_drag_offset, y_drag_offset));
return;
}
}
if (m_overflowSizerItem && m_overflowVisible && m_art)
{
wxRect overflow_rect = GetOverflowRect();
if (overflow_rect.Contains(evt.m_x, evt.m_y))
{
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_OVERFLOW_CLICK, -1);
e.SetEventObject(this);
e.SetToolId(-1);
e.SetClickPoint(wxPoint(evt.GetX(), evt.GetY()));
bool processed = GetEventHandler()->ProcessEvent(e);
if (processed)
{
DoIdleUpdate();
}
else
{
size_t i, count;
wxAuiToolBarItemArray overflow_items;
// add custom overflow prepend items, if any
count = m_customOverflowPrepend.GetCount();
for (i = 0; i < count; ++i)
overflow_items.Add(m_customOverflowPrepend[i]);
// only show items that don't fit in the dropdown
count = m_items.GetCount();
for (i = 0; i < count; ++i)
{
if (!GetToolFitsByIndex(i))
overflow_items.Add(m_items[i]);
}
// add custom overflow append items, if any
count = m_customOverflowAppend.GetCount();
for (i = 0; i < count; ++i)
overflow_items.Add(m_customOverflowAppend[i]);
int res = m_art->ShowDropDown(this, overflow_items);
m_overflowState = 0;
Refresh(false);
if (res != -1)
{
wxCommandEvent event(wxEVT_MENU, res);
event.SetEventObject(this);
GetParent()->GetEventHandler()->ProcessEvent(event);
}
}
return;
}
}
m_dragging = false;
m_actionPos = wxPoint(evt.GetX(), evt.GetY());
m_actionItem = FindToolByPosition(evt.GetX(), evt.GetY());
if (m_actionItem)
{
if (m_actionItem->m_state & wxAUI_BUTTON_STATE_DISABLED)
{
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
return;
}
UnsetToolTip();
// fire the tool dropdown event
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_TOOL_DROPDOWN, m_actionItem->m_toolId);
e.SetEventObject(this);
e.SetToolId(m_actionItem->m_toolId);
int mouse_x = evt.GetX();
wxRect rect = m_actionItem->m_sizerItem->GetRect();
const bool dropDownHit = m_actionItem->m_dropDown &&
mouse_x >= (rect.x+rect.width-BUTTON_DROPDOWN_WIDTH-1) &&
mouse_x < (rect.x+rect.width);
e.SetDropDownClicked(dropDownHit);
e.SetClickPoint(evt.GetPosition());
e.SetItemRect(rect);
// we only set the 'pressed button' state if we hit the actual button
// and not just the drop-down
SetPressedItem(dropDownHit ? 0 : m_actionItem);
if(dropDownHit)
{
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
}
if(!GetEventHandler()->ProcessEvent(e) || e.GetSkipped())
CaptureMouse();
// Ensure hovered item is really ok, as mouse may have moved during
// event processing
wxPoint cursor_pos_after_evt = ScreenToClient(wxGetMousePosition());
SetHoverItem(FindToolByPosition(cursor_pos_after_evt.x, cursor_pos_after_evt.y));
DoIdleUpdate();
}
}
void wxAuiToolBar::OnLeftUp(wxMouseEvent& evt)
{
if (!HasCapture())
return;
SetPressedItem(NULL);
wxAuiToolBarItem* hitItem;
hitItem = FindToolByPosition(evt.GetX(), evt.GetY());
SetHoverItem(hitItem);
if (m_dragging)
{
// TODO: it would make sense to send out an 'END_DRAG' event here,
// otherwise a client would never know what to do with the 'BEGIN_DRAG'
// event
// OnCaptureLost() will be called now and this will reset all our state
// tracking variables
ReleaseMouse();
}
else
{
if (m_actionItem && hitItem == m_actionItem)
{
UnsetToolTip();
wxCommandEvent e(wxEVT_MENU, m_actionItem->m_toolId);
e.SetEventObject(this);
if (hitItem->m_kind == wxITEM_CHECK || hitItem->m_kind == wxITEM_RADIO)
{
const bool toggle = !(m_actionItem->m_state & wxAUI_BUTTON_STATE_CHECKED);
ToggleTool(m_actionItem->m_toolId, toggle);
// repaint immediately
Refresh(false);
Update();
e.SetInt(toggle);
}
// we have to release the mouse *before* sending the event, because
// we don't know what a handler might do. It could open up a popup
// menu for example and that would make us lose our capture anyway.
ReleaseMouse();
GetEventHandler()->ProcessEvent(e);
// Ensure hovered item is really ok, as mouse may have moved during
// event processing
wxPoint cursor_pos_after_evt = ScreenToClient(wxGetMousePosition());
SetHoverItem(FindToolByPosition(cursor_pos_after_evt.x, cursor_pos_after_evt.y));
DoIdleUpdate();
}
else
ReleaseMouse();
}
}
void wxAuiToolBar::OnRightDown(wxMouseEvent& evt)
{
wxRect cli_rect(wxPoint(0,0), GetClientSize());
if (m_gripperSizerItem)
{
wxRect gripper_rect = m_gripperSizerItem->GetRect();
if (gripper_rect.Contains(evt.GetX(), evt.GetY()))
return;
}
if (m_overflowSizerItem && m_art)
{
int dropdown_size = m_art->GetElementSize(wxAUI_TBART_OVERFLOW_SIZE);
if (dropdown_size > 0 &&
evt.m_x > cli_rect.width - dropdown_size &&
evt.m_y >= 0 &&
evt.m_y < cli_rect.height)
{
return;
}
}
m_actionPos = wxPoint(evt.GetX(), evt.GetY());
m_actionItem = FindToolByPosition(evt.GetX(), evt.GetY());
if (m_actionItem && m_actionItem->m_state & wxAUI_BUTTON_STATE_DISABLED)
{
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
return;
}
UnsetToolTip();
}
void wxAuiToolBar::OnRightUp(wxMouseEvent& evt)
{
wxAuiToolBarItem* hitItem;
hitItem = FindToolByPosition(evt.GetX(), evt.GetY());
if (m_actionItem && hitItem == m_actionItem)
{
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_RIGHT_CLICK, m_actionItem->m_toolId);
e.SetEventObject(this);
e.SetToolId(m_actionItem->m_toolId);
e.SetClickPoint(m_actionPos);
GetEventHandler()->ProcessEvent(e);
DoIdleUpdate();
}
else
{
// right-clicked on the invalid area of the toolbar
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_RIGHT_CLICK, -1);
e.SetEventObject(this);
e.SetToolId(-1);
e.SetClickPoint(m_actionPos);
GetEventHandler()->ProcessEvent(e);
DoIdleUpdate();
}
// reset member variables
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
}
void wxAuiToolBar::OnMiddleDown(wxMouseEvent& evt)
{
wxRect cli_rect(wxPoint(0,0), GetClientSize());
if (m_gripperSizerItem)
{
wxRect gripper_rect = m_gripperSizerItem->GetRect();
if (gripper_rect.Contains(evt.GetX(), evt.GetY()))
return;
}
if (m_overflowSizerItem && m_art)
{
int dropdown_size = m_art->GetElementSize(wxAUI_TBART_OVERFLOW_SIZE);
if (dropdown_size > 0 &&
evt.m_x > cli_rect.width - dropdown_size &&
evt.m_y >= 0 &&
evt.m_y < cli_rect.height)
{
return;
}
}
m_actionPos = wxPoint(evt.GetX(), evt.GetY());
m_actionItem = FindToolByPosition(evt.GetX(), evt.GetY());
if (m_actionItem)
{
if (m_actionItem->m_state & wxAUI_BUTTON_STATE_DISABLED)
{
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
return;
}
}
UnsetToolTip();
}
void wxAuiToolBar::OnMiddleUp(wxMouseEvent& evt)
{
wxAuiToolBarItem* hitItem;
hitItem = FindToolByPosition(evt.GetX(), evt.GetY());
if (m_actionItem && hitItem == m_actionItem)
{
if (hitItem->m_kind == wxITEM_NORMAL)
{
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_MIDDLE_CLICK, m_actionItem->m_toolId);
e.SetEventObject(this);
e.SetToolId(m_actionItem->m_toolId);
e.SetClickPoint(m_actionPos);
GetEventHandler()->ProcessEvent(e);
DoIdleUpdate();
}
}
// reset member variables
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
}
void wxAuiToolBar::OnMotion(wxMouseEvent& evt)
{
const bool button_pressed = HasCapture();
// start a drag event
if (!m_dragging && button_pressed &&
abs(evt.GetX() - m_actionPos.x) + abs(evt.GetY() - m_actionPos.y) > 5)
{
// TODO: sending this event only makes sense if there is an 'END_DRAG'
// event sent sometime in the future (see OnLeftUp())
wxAuiToolBarEvent e(wxEVT_AUITOOLBAR_BEGIN_DRAG, GetId());
e.SetEventObject(this);
e.SetToolId(m_actionItem->m_toolId);
m_dragging = GetEventHandler()->ProcessEvent(e) && !e.GetSkipped();
DoIdleUpdate();
}
if(m_dragging)
return;
wxAuiToolBarItem* hitItem = FindToolByPosition(evt.GetX(), evt.GetY());
if(button_pressed)
{
// if we have a button pressed we want it to be shown in 'depressed'
// state unless we move the mouse outside the button, then we want it
// to show as just 'highlighted'
if (hitItem == m_actionItem)
SetPressedItem(m_actionItem);
else
{
SetPressedItem(NULL);
SetHoverItem(m_actionItem);
}
}
else
{
SetHoverItem(hitItem);
// tooltips handling
wxAuiToolBarItem* packingHitItem;
packingHitItem = FindToolByPositionWithPacking(evt.GetX(), evt.GetY());
if (packingHitItem)
{
if (packingHitItem != m_tipItem)
{
m_tipItem = packingHitItem;
if ( !packingHitItem->m_shortHelp.empty() )
SetToolTip(packingHitItem->m_shortHelp);
else
UnsetToolTip();
}
}
else
{
UnsetToolTip();
m_tipItem = NULL;
}
// figure out the dropdown button state (are we hovering or pressing it?)
RefreshOverflowState();
}
}
void wxAuiToolBar::DoResetMouseState()
{
RefreshOverflowState();
SetHoverItem(NULL);
SetPressedItem(NULL);
m_tipItem = NULL;
// we have to reset those here, because the mouse-up handlers which do
// it usually won't be called if we let go of a mouse button while we
// are outside of the window
m_actionPos = wxPoint(-1,-1);
m_actionItem = NULL;
}
void wxAuiToolBar::OnLeaveWindow(wxMouseEvent& evt)
{
if(HasCapture())
{
evt.Skip();
return;
}
DoResetMouseState();
}
void wxAuiToolBar::OnCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(evt))
{
m_dragging = false;
DoResetMouseState();
}
void wxAuiToolBar::OnSetCursor(wxSetCursorEvent& evt)
{
wxCursor cursor = wxNullCursor;
if (m_gripperSizerItem)
{
wxRect gripper_rect = m_gripperSizerItem->GetRect();
if (gripper_rect.Contains(evt.GetX(), evt.GetY()))
{
cursor = wxCursor(wxCURSOR_SIZING);
}
}
evt.SetCursor(cursor);
}
#endif // wxUSE_AUI
| [
"the.corbin.hart@gmail.com"
] | the.corbin.hart@gmail.com |
e00ad4ebe4dcbe901e513cef26dffc34fe44358e | 840877399be53611e086f898c37d6b2179b8248f | /proj8/ArrayQueueTester.cpp | 8f278cef28ed785c059cf14d8adb1bfb47515b4e | [] | no_license | BryceAllen613/112 | e1fdb9e7943b177aea9a35f0f5c5196116d1acb0 | ecb04b3482a6dc88221910395c0de27840bd29d9 | refs/heads/master | 2020-08-16T23:44:12.518871 | 2019-10-16T14:51:05 | 2019-10-16T14:51:05 | 215,572,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,684 | cpp | /* QueueTester.cpp defines the test-methods for class Queue.
* Joel Adams, for CS 112 at Calvin College.
*/
#include "ArrayQueueTester.h"
#include <iostream>
#include <cassert>
#include <stdexcept>
#include <cstdlib>
typedef int Item;
using namespace std;
void ArrayQueueTester::runTests() {
cout << "Testing class ArrayQueue..." << endl;
testConstructor();
testAppend();
testRemove();
testCopyConstructor();
testAssignment();
testSetCapacity();
cout << "All tests passed!\n" << endl;
}
void ArrayQueueTester::testAssignment() {
cout << "- testing assignment... " << flush;
// empty, smaller-to-bigger;
ArrayQueue<int> q1(4);
ArrayQueue<int> q2(3);
q1 = q2;
assert( q1.isEmpty() );
assert( q1.myCapacity == 3 );
assert( q1.getSize() == 0 );
assert( q1.myFirstIndex == q2.myFirstIndex );
assert( q1.myLastIndex == q2.myLastIndex );
assert( q1.myArrayPtr != q2.myArrayPtr );
cout << " 1 " << flush;
//empty, bigger to smaller
ArrayQueue<int> q3(3);
ArrayQueue<int> q4(4);
q3 = q4;
assert( q3.isEmpty() );
assert( q3.myCapacity == 4 );
assert( q3.getSize() == 0 );
assert( q3.myFirstIndex == q4.myFirstIndex );
assert( q3.myLastIndex == q4.myLastIndex );
assert( q3.myArrayPtr != q4.myArrayPtr );
cout << " 2 " << flush;
// full, same-sized
ArrayQueue<int> q5(4);
q5.append(11);
q5.append(22);
q5.append(33);
q5.append(44);
ArrayQueue<int> q6(4);
q6 = q5;
assert( q6.isFull() );
assert( !q6.isEmpty() );
assert( q6.myCapacity == 4 );
assert( q6.getSize() == 4 );
assert( q6.myFirstIndex == q5.myFirstIndex );
assert( q6.myLastIndex == q5.myLastIndex );
for (unsigned i = 0; i < q6.myCapacity; i++) {
assert( q6.myArrayPtr[i] == q5.myArrayPtr[i] );
}
assert( q6.myArrayPtr != q5.myArrayPtr );
cout << " 3 " << flush;
// full, smaller-to-larger
ArrayQueue<int> q7(3);
q7 = q5;
assert( q7.isFull() );
assert( !q7.isEmpty() );
assert( q7.myCapacity == 4 );
assert( q7.getSize() == 4 );
assert( q7.myFirstIndex == q5.myFirstIndex );
assert( q7.myLastIndex == q5.myLastIndex );
for (unsigned i = 0; i < q7.myCapacity; i++) {
assert( q7.myArrayPtr[i] == q5.myArrayPtr[i] );
}
assert( q7.myArrayPtr != q5.myArrayPtr );
cout << " 4 " << flush;
// full, larger-to-smaller
ArrayQueue<int> q8(5);
q8 = q5;
assert( q8.isFull() );
assert( !q8.isEmpty() );
assert( q8.myCapacity == 4 );
assert( q8.getSize() == 4 );
assert( q8.myFirstIndex == q5.myFirstIndex );
assert( q8.myLastIndex == q5.myLastIndex );
for (unsigned i = 0; i < q8.myCapacity; i++) {
assert( q8.myArrayPtr[i] == q5.myArrayPtr[i] );
}
assert( q8.myArrayPtr != q5.myArrayPtr );
cout << " 5 " << flush;
// self assignment
q5 = q5;
assert( q5.isFull() );
assert( !q5.isEmpty() );
assert( q5.myCapacity == 4 );
assert( q5.getSize() == 4 );
assert( q5.myArrayPtr[0] == 11 );
assert( q5.myArrayPtr[1] == 22 );
assert( q5.myArrayPtr[2] == 33 );
assert( q5.myArrayPtr[3] == 44 );
cout << " 6 " << flush;
// chaining
q1 = q3 = q5;
assert( q1.isFull() );
assert( !q1.isEmpty() );
assert( q1.myCapacity == 4 );
assert( q1.getSize() == 4 );
assert( q1.myArrayPtr[0] == 11 );
assert( q1.myArrayPtr[1] == 22 );
assert( q1.myArrayPtr[2] == 33 );
assert( q1.myArrayPtr[3] == 44 );
assert( q1.myArrayPtr != q3.myArrayPtr );
assert( q1.myArrayPtr != q5.myArrayPtr );
assert( q3.myArrayPtr != q5.myArrayPtr );
cout << " 7 " << flush;
cout << "Passed!" << endl;
}
void ArrayQueueTester::testCopyConstructor() {
cout << "- testing copy constructor... " << flush;
// empty queue
ArrayQueue<int> q1(4);
ArrayQueue<int> q2(q1);
assert( q2.isEmpty() );
assert( !q2.isFull() );
assert( q2.myCapacity == q1.myCapacity);
assert( q2.myFirstIndex == q1.myFirstIndex );
assert( q2.myLastIndex == q1.myLastIndex );
assert( q2.myArrayPtr != q1.myArrayPtr );
cout << " 1 " << flush;
// queue of 1 item
ArrayQueue<int> q3(4);
q3.append(11);
ArrayQueue<int> q4(q3);
assert( !q4.isFull() );
assert( !q4.isEmpty() );
assert( q4.myCapacity == q3.myCapacity);
assert( q4.myFirstIndex == q3.myFirstIndex );
assert( q4.myLastIndex == q3.myLastIndex );
assert( q4.myArrayPtr != q3.myArrayPtr );
assert( q4.getFirst() == 11 );
assert( q4.getLast() == 11 );
assert( q4.myArrayPtr != q3.myArrayPtr );
cout << " 2 " << flush;
// full queue
q3.append(22);
q3.append(33);
q3.append(44);
ArrayQueue<int> q5(q3);
assert( q5.isFull() );
assert( !q5.isEmpty() );
assert( q5.myCapacity == q3.myCapacity);
assert( q5.myFirstIndex == q3.myFirstIndex );
assert( q5.myLastIndex == q3.myLastIndex );
assert( q5.myArrayPtr != q3.myArrayPtr );
assert( q5.getFirst() == 11 );
assert( q5.getLast() == 44 );
assert( q5.myArrayPtr != q3.myArrayPtr );
cout << " 3 " << flush;
cout << "Passed!" << endl;
}
void ArrayQueueTester::testRemove() {
cout << "- testing remove()... " << flush;
ArrayQueue<int> q1(4);
cout << " 0 " << flush;
// check with empty queue
try {
q1.remove();
cerr << "\nremove() worked on empty Queue - 1\n";
exit(1);
} catch (EmptyQueueException& eqe) {
cout << " 1 " << flush;
}
// check with 1 item
q1.append(1);
assert( !q1.isEmpty() );
assert( q1.remove() == 1 );
assert( q1.isEmpty() );
cout << " 2 " << flush;
// check with 2 items
q1.append(11);
q1.append(22);
assert( !q1.isEmpty() );
assert( q1.getFirst() == 11 );
assert( q1.getLast() == 22 );
assert( q1.remove() == 11 );
assert( q1.getFirst() == 22 );
assert( q1.getLast() == 22 );
assert( q1.remove() == 22 );
assert( q1.isEmpty() );
cout << " 3 " << flush;
// load it up
q1.append(111);
q1.append(222);
q1.append(333);
q1.append(444);
assert( q1.isFull() );
assert( !q1.isEmpty() );
assert( q1.getFirst() == 111 );
assert( q1.getLast() == 444 );
// start removing items
assert( q1.remove() == 111 );
assert( !q1.isFull() );
assert( !q1.isEmpty() );
assert( q1.getFirst() == 222 );
assert( q1.getLast() == 444 );
cout << " 4a " << flush;
assert( q1.remove() == 222 );
assert( !q1.isFull() );
assert( !q1.isEmpty() );
assert( q1.getFirst() == 333 );
assert( q1.getLast() == 444 );
cout << " 4b " << flush;
assert( q1.remove() == 333 );
assert( !q1.isFull() );
assert( !q1.isEmpty() );
assert( q1.getFirst() == 444 );
assert( q1.getLast() == 444 );
cout << " 4c " << flush;
assert( q1.remove() == 444 );
assert( !q1.isFull() );
assert( q1.isEmpty() );
cout << " 4d " << flush;
// recheck empty queue
try {
q1.remove();
cerr << "\nremove() worked on empty Queue - 2\n";
exit(1);
} catch (EmptyQueueException& eqe) {
cout << " 5 " << flush;
}
ArrayQueue<int> q2(5000);
cout << " 6a " << flush;
for (Item i = 5000; i > 0; i--) {
q2.append(i);
}
assert( q2.isFull() );
cout << " 6b " << flush;
for (Item i = 5000; i > 0; i--) {
assert( q2.remove() == i );
}
assert( q2.isEmpty() );
cout << " 6c " << flush;
cout << "Passed!" << endl;
}
void ArrayQueueTester::testAppend() {
cout << "- testing append(), getFirst(), getLast() ... " << flush;
ArrayQueue<int> q1(4);
assert( q1.isEmpty() );
assert( !q1.isFull() );
try {
q1.getFirst();
cerr << "\ngetFirst() worked on empty queue\n";
exit(1);
} catch (EmptyQueueException& eqe) {
cout << " 0a " << flush;
}
try {
q1.getLast();
cerr << "\ngetLast() worked on empty queue\n";
exit(1);
} catch (EmptyQueueException& eqe) {
cout << " 0b " << flush;
}
q1.append(11);
assert( !q1.isEmpty() );
assert( !q1.isFull() );
assert( q1.getFirst() == 11 );
assert( q1.getLast() == 11 );
cout << " 1 " << flush;
q1.append(22);
assert( !q1.isEmpty() );
assert( !q1.isFull() );
assert( q1.getFirst() == 11 );
assert( q1.getLast() == 22 );
cout << " 2 " << flush;
q1.append(33);
assert( !q1.isEmpty() );
assert( !q1.isFull() );
assert( q1.getFirst() == 11 );
assert( q1.getLast() == 33 );
cout << " 3 " << flush;
q1.append(44);
assert( !q1.isEmpty() );
assert( q1.isFull() );
assert( q1.getFirst() == 11 );
assert( q1.getLast() == 44 );
cout << " 4 " << flush;
// append to full queue
try {
q1.append(55);
cerr << "\nappend() worked on full queue\n";
exit(1);
} catch (FullQueueException& fqe) {
cout << " 5 " << flush;
}
cout << "Passed, but wrap-around not tested..." << endl;
}
void ArrayQueueTester::testConstructor() {
cout << "- testing constructor... " << flush;
// try with capacity zero
try {
ArrayQueue<int> q1(0);
cerr << "Constructed Queue with capacity zero" << endl;
exit(1);
} catch (QueueException& qe) {
cout << " 1 " << flush;
}
// positive capacity
ArrayQueue<int> q2(3);
assert( q2.isEmpty() );
assert( !q2.isFull() );
assert( q2.myCapacity == 3 );
cout << " 2 " << flush;
cout << " Passed!" << endl;
}
void ArrayQueueTester::testSetCapacity(){
cout << "Testing setCapacity()..." << flush;
//Test changing capacity on an empty queue
ArrayQueue<int> q1(1);
assert( q1.getCapacity() == 1 );
assert( q1.getSize() == 0 );
assert( q1.isEmpty() );
assert( !q1.isFull() );
//increase the capacity
q1.setCapacity(10);
assert( q1.getCapacity() == 10 );
assert( q1.getSize() == 0 );
assert( q1.isEmpty() );
assert( !q1.isFull() );
cout << " 1a" << flush;
//decrease the capacity
q1.setCapacity(5);
assert( q1.getCapacity() == 5 );
assert( q1.getSize() == 0 );
assert( q1.isEmpty() );
assert( !q1.isFull() );
cout << " 1b" << flush;
//try setting the capacity to zero
try{
q1.setCapacity(0);
cerr << "setCapacity(0) worked!" << endl;
exit(1);
} catch ( QueueException e ) {
//check to make sure nothing was changed
assert( q1.getCapacity() == 5 );
assert( q1.getSize() == 0 );
assert( q1.isEmpty() );
assert( !q1.isFull() );
cout << " 1c" << flush;
}
//Test changing capacity on a queue with items that
//start at the beginning of the array
ArrayQueue<int> q2(5);
for (int i = 0; i < 5; i++){
q2.append(i+1);
}
assert( q2.getCapacity() == 5 );
assert( q2.getSize() == 5 );
assert( !q2.isEmpty() );
assert( q2.isFull() );
assert( q2.getFirst() == 1 );
assert( q2.getLast() == 5 );
//increase the capacity
q2.setCapacity(10);
assert( q2.getCapacity() == 10 );
assert( q2.getSize() == 5 );
assert( !q2.isEmpty() );
assert( !q2.isFull() );
assert( q2.getFirst() == 1 );
assert( q2.getLast() == 5 );
cout << " 2a" << flush;
//check to make sure appending still works
q2.append(6);
assert( q2.getLast() == 6 );
q2.append(7);
q2.append(8);
q2.append(9);
q2.append(10);
assert( q2.getCapacity() == 10 );
assert( q2.getSize() == 10 );
assert( !q2.isEmpty() );
assert( q2.isFull() );
assert( q2.getFirst() == 1 );
assert( q2.getLast() == 10 );
cout << " 2b" << flush;
//check to make sure that removing still works
assert( q2.remove() == 1 );
assert( q2.remove() == 2 );
assert( q2.remove() == 3 );
assert( q2.remove() == 4 );
assert( q2.remove() == 5 );
assert( q2.remove() == 6 );
assert( q2.remove() == 7 );
assert( q2.remove() == 8 );
assert( q2.remove() == 9 );
assert( q2.remove() == 10 );
assert( q2.getCapacity() == 10 );
assert( q2.getSize() == 0 );
assert( q2.isEmpty() );
assert( !q2.isFull() );
cout << " 2c" << flush;
//set up a clean queue before continuing...
ArrayQueue<int> q3(20);
for (int i = 0; i < 5; i++){
q3.append(i+1);
}
assert( q3.getCapacity() == 20 );
assert( q3.getSize() == 5 );
assert( !q3.isEmpty() );
assert( !q3.isFull() );
assert( q3.getFirst() == 1 );
assert( q3.getLast() == 5 );
//decrease the capacity
q3.setCapacity(10);
assert( q3.getCapacity() == 10 );
assert( q3.getSize() == 5 );
assert( !q3.isEmpty() );
assert( !q3.isFull() );
assert( q3.getFirst() == 1 );
assert( q3.getLast() == 5 );
cout << " 2d" << flush;
//check to make sure appending still works
q3.append(6);
assert( q3.getLast() == 6 );
q3.append(7);
q3.append(8);
q3.append(9);
q3.append(10);
assert( q3.getCapacity() == 10 );
assert( q3.getSize() == 10 );
assert( !q3.isEmpty() );
assert( q3.isFull() );
assert( q3.getFirst() == 1 );
assert( q3.getLast() == 10 );
cout << " 2e" << flush;
//check to make sure that removing still works
assert( q3.remove() == 1 );
assert( q3.remove() == 2 );
assert( q3.remove() == 3 );
assert( q3.remove() == 4 );
assert( q3.remove() == 5 );
assert( q3.remove() == 6 );
assert( q3.remove() == 7 );
assert( q3.remove() == 8 );
assert( q3.remove() == 9 );
assert( q3.remove() == 10 );
assert( q3.getCapacity() == 10 );
assert( q3.getSize() == 0 );
assert( q3.isEmpty() );
assert( !q3.isFull() );
cout << " 2f" << flush;
//test setCapacity() on a queue that has items starting
//in the middle of the array, not wrapping around
ArrayQueue<int> q4(5);
for (int i = 0; i < 5; i++){ //HERE
q4.append(i+1);
}
q4.remove();
q4.remove();
assert( q4.getCapacity() == 5 );
assert( q4.getSize() == 3 );
assert( !q4.isEmpty() );
assert( !q4.isFull() );
assert( q4.getFirst() == 3 );
assert( q4.getLast() == 5 );
//increase the capacity
//cout<<q4.getLast()<<flush;
q4.setCapacity(10);
//cout<<" "<<q4.myLastIndex<<flush;
assert( q4.getCapacity() == 10 );
assert( q4.getSize() == 3 );
assert( !q4.isEmpty() );
assert( !q4.isFull() );
assert( q4.getFirst() == 3 );
assert( q4.getLast() == 5 );
cout << " 3a" << flush;
//check to make sure appending still works
q4.append(6);
q4.append(7);
q4.append(8);
q4.append(9);
q4.append(10);
q4.append(11);
q4.append(12);
assert( q4.getCapacity() == 10 );
assert( q4.getSize() == 10 );
assert( !q4.isEmpty() );
assert( q4.isFull() );
assert( q4.getFirst() == 3 );
assert( q4.getLast() == 12 );
cout << " 3b" << flush;
//check to make sure removing still works
assert( q4.remove() == 3 );
//cout<< q4.remove() << flush;
assert( q4.remove() == 4 );
assert( q4.remove() == 5 );
assert( q4.remove() == 6 );
assert( q4.remove() == 7 );
assert( q4.remove() == 8 );
assert( q4.remove() == 9 );
assert( q4.remove() == 10 );
assert( q4.remove() == 11 );
assert( q4.remove() == 12 );
assert( q4.getCapacity() == 10 );
assert( q4.getSize() == 0 );
assert( q4.isEmpty() );
assert( !q4.isFull() );
cout << " 3c" << flush;
//create a clean queue before continuing...
ArrayQueue<int> q5(10);
for (int i = 0; i < 10; i++){
q5.append(i+1);
}
for (int i = 0; i < 7; i++){
q5.remove();
}
assert( q5.getCapacity() == 10 );
assert( q5.getSize() == 3 );
assert( !q5.isEmpty() );
assert( !q5.isFull() );
assert( q5.getFirst() == 8 );
assert( q5.getLast() == 10 );
//reduce the capacity
q5.setCapacity(5);
assert( q5.getCapacity() == 5 );
assert( q5.getSize() == 3 );
assert( !q5.isEmpty() );
assert( !q5.isFull() );
assert( q5.getFirst() == 8 );
assert( q5.getLast() == 10 );
cout << " 3d" << flush;
//check to make sure appending still works
q5.append(11);
q5.append(12);
assert( q5.getCapacity() == 5 );
assert( q5.getSize() == 5 );
assert( !q5.isEmpty() );
assert( q5.isFull() );
assert( q5.getFirst() == 8 );
assert( q5.getLast() == 12 );
cout << " 3e" << flush;
//check to make sure removing still works
assert( q5.remove() == 8 );
cout << q5.getFirst() << flush;
assert( q5.remove() == 9 );
assert( q5.remove() == 10 );
assert( q5.remove() == 11 );
assert( q5.remove() == 12 );
assert( q5.getCapacity() == 5 );
assert( q5.getSize() == 0 );
assert( q5.isEmpty() );
assert( !q5.isFull() );
cout << " 3f" << flush;
//test setCapacity() on a queue with values that
//wrap around the array
ArrayQueue<int> q6(5);
for (int i = 0; i < 5; i++){
q6.append(i+1);
}
q6.remove();
q6.remove();
q6.remove();
q6.append(6);
q6.append(7);
assert( q6.getCapacity() == 5 );
assert( q6.getSize() == 4 );
assert( !q6.isEmpty() );
assert( !q6.isFull() );
assert( q6.getFirst() == 4 );
assert( q6.getLast() == 7 );
//increase the capacity
q6.setCapacity(10);
assert( q6.getCapacity() == 10 );
assert( q6.getSize() == 4 );
assert( !q6.isEmpty() );
assert( !q6.isFull() );
assert( q6.getFirst() == 4 );
assert( q6.getLast() == 7 );
cout << " 4a" << flush;
//check to make sure appending still works
q6.append(8);
q6.append(9);
q6.append(10);
q6.append(11);
q6.append(12);
q6.append(13);
assert( q6.getCapacity() == 10 );
assert( q6.getSize() == 10 );
assert( !q6.isEmpty() );
assert( q6.isFull() );
assert( q6.getFirst() == 4 );
assert( q6.getLast() == 13 );
cout << " 4b" << flush;
//check to make sure removing still works
assert( q6.remove() == 4 );
assert( q6.remove() == 5 );
assert( q6.remove() == 6 );
assert( q6.remove() == 7 );
assert( q6.remove() == 8 );
assert( q6.remove() == 9 );
assert( q6.remove() == 10 );
assert( q6.remove() == 11 );
assert( q6.remove() == 12 );
assert( q6.remove() == 13 );
assert( q6.getCapacity() == 10 );
assert( q6.getSize() == 0 );
assert( q6.isEmpty() );
assert( !q6.isFull() );
cout << " 4c" << flush;
//set up a clean queue before continuing...
ArrayQueue<int> q7(10);
for(int i = 0; i < 10; i++){
q7.append(i+1);
}
for(int i = 0; i < 8; i++){
q7.remove();
}
q7.append(11);
q7.append(12);
assert( q7.getCapacity() == 10 );
assert( q7.getSize() == 4 );
assert( !q7.isEmpty() );
assert( !q7.isFull() );
assert( q7.getFirst() == 9 );
assert( q7.getLast() == 12 );
//reduce the capacity
q7.setCapacity(6);
assert( q7.getCapacity() == 6 );
assert( q7.getSize() == 4 );
assert( !q7.isEmpty() );
assert( !q7.isFull() );
assert( q7.getFirst() == 9 );
assert( q7.getLast() == 12 );
cout << " 4d" << flush;
//check to make sure appending still works
q7.append(13);
q7.append(14);
assert( q7.getCapacity() == 6 );
assert( q7.getSize() == 6 );
assert( !q7.isEmpty() );
assert( q7.isFull() );
assert( q7.getFirst() == 9 );
assert( q7.getLast() == 14 );
cout << " 4e" << flush;
//check to make sure removing still works
assert( q7.remove() == 9 );
assert( q7.remove() == 10 );
assert( q7.remove() == 11 );
assert( q7.remove() == 12 );
assert( q7.remove() == 13 );
assert( q7.remove() == 14 );
assert( q7.getCapacity() == 6 );
assert( q7.getSize() == 0 );
assert( q7.isEmpty() );
assert( !q7.isFull() );
cout << " 4f" << flush;
//try reducing capacity to less than the current size
ArrayQueue<int> q8(10);
for( int i = 0; i < 8; i++){
q8.append(i+1);
}
assert( q8.getCapacity() == 10 );
assert( q8.getSize() == 8 );
assert( !q8.isEmpty() );
assert( !q8.isFull() );
assert( q8.getFirst() == 1 );
assert( q8.getLast() == 8 );
try{
q8.setCapacity(5);
cerr << "setCapacity worked with new capacity < size" << endl;
exit(1);
} catch (QueueException e) {
//check to make sure nothing changed
assert( q8.getCapacity() == 10 );
assert( q8.getSize() == 8 );
assert( !q8.isEmpty() );
assert( !q8.isFull() );
assert( q8.getFirst() == 1 );
assert( q8.getLast() == 8 );
assert( q8.remove() == 1 );
assert( q8.remove() == 2 );
assert( q8.remove() == 3 );
assert( q8.remove() == 4 );
assert( q8.remove() == 5 );
assert( q8.remove() == 6 );
assert( q8.remove() == 7 );
assert( q8.remove() == 8 );
cout << " 5" << flush;
}
// copy a full queue, where myFirst && myLast are not zero,
// so newer items precede older items in the queue
// (thanks to Christpher Hesters).
ArrayQueue<int> q9(3);
q9.append(11);
q9.append(12);
q9.append(13);
assert(q9.remove() == 11);
q9.append(14);
assert(q9.remove() == 12);
q9.append(15);
q9.setCapacity(4);
assert(q9.getCapacity() == 4);
assert(q9.getFirst() == 13);
assert(q9.getLast() == 15);
assert(q9.remove() == 13);
assert(q9.getFirst() == 14);
assert(q9.getLast() == 15);
assert(q9.remove() == 14);
assert(q9.getFirst() == 15);
assert(q9.getLast() == 15);
assert(q9.remove() == 15);
cout << " 6" << flush;
cout << " Passed!" << endl;
}
| [
"bryceallen@dhcp93-151.calvin.edu"
] | bryceallen@dhcp93-151.calvin.edu |
265bd5ad26a8a9132a8c86d54b07b5d5cb0f1df3 | 485a772cc4978fa7711d2680356035b64919c8c3 | /even odd extraction.cpp | 9998473c3248b667b5214be10fbe263b8480fa56 | [] | no_license | saidur301297/C-Programming | 5eec970966be450c3d0ba7ddb4c79552d5c081e2 | 82c4ed07071df7b120f916fe86791a113f887bf3 | refs/heads/master | 2020-08-06T23:38:59.028871 | 2019-10-11T12:19:52 | 2019-10-11T12:19:52 | 213,202,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | #include<iostream>
using namespace std;
int main()
{
int n,i;
cout<<"Please enter a positive number:";
cin>>n;
cout<<"Enter " <<n<<" elements:";
int array[n];
for(i=0;i<n;i++)
cin>>array[i];
int even[n],odd[n],j=0,k=0;
for(i=0;i<n;i++)
if(array[i]%2==0)
even[j++]=array[i];
else
odd[k++]=array[i];
cout<<"Even array elements are: ";
for(i=0;i<j;i++)
cout<<even[i]<<" ";
cout<<"\nOdd array elements are: ";
for(i=0;i<k;i++)
cout<<odd[i]<<" ";
}
| [
"noreply@github.com"
] | noreply@github.com |
92fcf83104a54852457fe6fc38ad5153449e9303 | cdf08df10346f5d4e3b0200c2f59069723e4c812 | /test/heco/heco_runner.cpp | 8d75bff6a00144ad7a5910aa7a40f903b9333fbf | [] | no_license | freesamael/wolf | bf826ff8dc5571fb57ee7f58d50d8eb77482313a | 563aa4ee6955fc83309c49425db5735668ba0954 | refs/heads/master | 2021-03-12T23:44:22.205066 | 2015-07-28T07:02:51 | 2015-07-28T07:02:51 | 27,208,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | cpp | /**
* \file heco_runner.cpp
* \date Jun 20, 2010
* \author samael
*/
#include <CRunner.h>
#include <CSimpleWorkerStealer.h>
using namespace wolf;
int main()
{
CSimpleWorkerStealer stealer(10);
CRunner runner(5566, 7788, &stealer);
runner.run();
return 0;
}
| [
"freesamael@gmail.com"
] | freesamael@gmail.com |
7008e0a1ba0aa4f37694bc5d5606051ebf69465d | 8722f2da8bc1a6b3e16ce5759f67ca292c0a7341 | /src/beast/beast/module/core/native/posix_SharedCode.h | d056f3082f281b90a8eebbd7cbb47a5ca102e736 | [
"ISC",
"BSL-1.0",
"MIT",
"MIT-Wu"
] | permissive | waynezu/vpal20 | 010fbec860b6c4d8c775b8d637730580e842d597 | 8deef35521417cd4405d7bbadd030b89bd4fb91b | refs/heads/master | 2020-12-25T21:35:01.584301 | 2014-10-27T03:58:56 | 2014-10-27T03:58:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,607 | h | //------------------------------------------------------------------------------
/*
Portions of this file are from Vpallab: https://github.com/vpallabs
Copyright (c) 2013 - 2014 - Vpallab.com.
Please visit http://www.vpallab.com/
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
namespace beast
{
CriticalSection::CriticalSection() noexcept
{
pthread_mutexattr_t atts;
pthread_mutexattr_init (&atts);
pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
#if ! BEAST_ANDROID
pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
#endif
pthread_mutex_init (&mutex, &atts);
pthread_mutexattr_destroy (&atts);
}
CriticalSection::~CriticalSection() noexcept { pthread_mutex_destroy (&mutex); }
void CriticalSection::enter() const noexcept { pthread_mutex_lock (&mutex); }
bool CriticalSection::tryEnter() const noexcept { return pthread_mutex_trylock (&mutex) == 0; }
void CriticalSection::exit() const noexcept { pthread_mutex_unlock (&mutex); }
//==============================================================================
void Process::terminate()
{
#if BEAST_ANDROID || BEAST_BSD
// http://www.unix.com/man-page/FreeBSD/2/_exit/
::_exit (EXIT_FAILURE);
#else
std::_Exit (EXIT_FAILURE);
#endif
}
//==============================================================================
const beast_wchar File::separator = '/';
const String File::separatorString ("/");
//==============================================================================
File File::getCurrentWorkingDirectory()
{
HeapBlock<char> heapBuffer;
char localBuffer [1024];
char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
size_t bufferSize = 4096;
while (cwd == nullptr && errno == ERANGE)
{
heapBuffer.malloc (bufferSize);
cwd = getcwd (heapBuffer, bufferSize - 1);
bufferSize += 1024;
}
return File (CharPointer_UTF8 (cwd));
}
bool File::setAsCurrentWorkingDirectory() const
{
return chdir (getFullPathName().toUTF8()) == 0;
}
//==============================================================================
// The unix siginterrupt function is deprecated - this does the same job.
int beast_siginterrupt (int sig, int flag)
{
struct ::sigaction act;
(void) ::sigaction (sig, nullptr, &act);
if (flag != 0)
act.sa_flags &= ~SA_RESTART;
else
act.sa_flags |= SA_RESTART;
return ::sigaction (sig, &act, nullptr);
}
//==============================================================================
namespace
{
#if BEAST_LINUX || \
(BEAST_IOS && ! __DARWIN_ONLY_64_BIT_INO_T) // (this iOS stuff is to avoid a simulator bug)
typedef struct stat64 beast_statStruct;
#define BEAST_STAT stat64
#else
typedef struct stat beast_statStruct;
#define BEAST_STAT stat
#endif
bool beast_stat (const String& fileName, beast_statStruct& info)
{
return fileName.isNotEmpty()
&& BEAST_STAT (fileName.toUTF8(), &info) == 0;
}
// if this file doesn't exist, find a parent of it that does..
bool beast_doStatFS (File f, struct statfs& result)
{
for (int i = 5; --i >= 0;)
{
if (f.exists())
break;
f = f.getParentDirectory();
}
return statfs (f.getFullPathName().toUTF8(), &result) == 0;
}
void updateStatInfoForFile (const String& path, bool* const isDir, std::int64_t* const fileSize,
Time* const modTime, Time* const creationTime, bool* const isReadOnly)
{
if (isDir != nullptr || fileSize != nullptr || modTime != nullptr || creationTime != nullptr)
{
beast_statStruct info;
const bool statOk = beast_stat (path, info);
if (isDir != nullptr) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
if (fileSize != nullptr) *fileSize = statOk ? info.st_size : 0;
if (modTime != nullptr) *modTime = Time (statOk ? (std::int64_t) info.st_mtime * 1000 : 0);
if (creationTime != nullptr) *creationTime = Time (statOk ? (std::int64_t) info.st_ctime * 1000 : 0);
}
if (isReadOnly != nullptr)
*isReadOnly = access (path.toUTF8(), W_OK) != 0;
}
Result getResultForErrno()
{
return Result::fail (String (strerror (errno)));
}
Result getResultForReturnValue (int value)
{
return value == -1 ? getResultForErrno() : Result::ok();
}
int getFD (void* handle) noexcept { return (int) (std::intptr_t) handle; }
void* fdToVoidPointer (int fd) noexcept { return (void*) (std::intptr_t) fd; }
}
bool File::isDirectory() const
{
beast_statStruct info;
return fullPath.isEmpty()
|| (beast_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
}
bool File::exists() const
{
return fullPath.isNotEmpty()
&& access (fullPath.toUTF8(), F_OK) == 0;
}
bool File::existsAsFile() const
{
return exists() && ! isDirectory();
}
std::int64_t File::getSize() const
{
beast_statStruct info;
return beast_stat (fullPath, info) ? info.st_size : 0;
}
//==============================================================================
bool File::hasWriteAccess() const
{
if (exists())
return access (fullPath.toUTF8(), W_OK) == 0;
if ((! isDirectory()) && fullPath.containsChar (separator))
return getParentDirectory().hasWriteAccess();
return false;
}
bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
{
beast_statStruct info;
if (! beast_stat (fullPath, info))
return false;
info.st_mode &= 0777; // Just permissions
if (shouldBeReadOnly)
info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
else
// Give everybody write permission?
info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
return chmod (fullPath.toUTF8(), info.st_mode) == 0;
}
void File::getFileTimesInternal (std::int64_t& modificationTime, std::int64_t& accessTime, std::int64_t& creationTime) const
{
modificationTime = 0;
accessTime = 0;
creationTime = 0;
beast_statStruct info;
if (beast_stat (fullPath, info))
{
modificationTime = (std::int64_t) info.st_mtime * 1000;
accessTime = (std::int64_t) info.st_atime * 1000;
creationTime = (std::int64_t) info.st_ctime * 1000;
}
}
bool File::setFileTimesInternal (std::int64_t modificationTime, std::int64_t accessTime, std::int64_t /*creationTime*/) const
{
beast_statStruct info;
if ((modificationTime != 0 || accessTime != 0) && beast_stat (fullPath, info))
{
struct utimbuf times;
times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
return utime (fullPath.toUTF8(), ×) == 0;
}
return false;
}
bool File::deleteFile() const
{
if (! exists())
return true;
if (isDirectory())
return rmdir (fullPath.toUTF8()) == 0;
return remove (fullPath.toUTF8()) == 0;
}
bool File::moveInternal (const File& dest) const
{
if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
return true;
if (hasWriteAccess() && copyInternal (dest))
{
if (deleteFile())
return true;
dest.deleteFile();
}
return false;
}
Result File::createDirectoryInternal (const String& fileName) const
{
return getResultForReturnValue (mkdir (fileName.toUTF8(), 0777));
}
//=====================================================================
std::int64_t beast_fileSetPosition (void* handle, std::int64_t pos)
{
if (handle != 0 && lseek (getFD (handle), pos, SEEK_SET) == pos)
return pos;
return -1;
}
void FileInputStream::openHandle()
{
const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
if (f != -1)
fileHandle = fdToVoidPointer (f);
else
status = getResultForErrno();
}
void FileInputStream::closeHandle()
{
if (fileHandle != 0)
{
close (getFD (fileHandle));
fileHandle = 0;
}
}
size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
{
std::ptrdiff_t result = 0;
if (fileHandle != 0)
{
result = ::read (getFD (fileHandle), buffer, numBytes);
if (result < 0)
{
status = getResultForErrno();
result = 0;
}
}
return (size_t) result;
}
//==============================================================================
void FileOutputStream::openHandle()
{
if (file.exists())
{
const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
if (f != -1)
{
currentPosition = lseek (f, 0, SEEK_END);
if (currentPosition >= 0)
{
fileHandle = fdToVoidPointer (f);
}
else
{
status = getResultForErrno();
close (f);
}
}
else
{
status = getResultForErrno();
}
}
else
{
const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
if (f != -1)
fileHandle = fdToVoidPointer (f);
else
status = getResultForErrno();
}
}
void FileOutputStream::closeHandle()
{
if (fileHandle != 0)
{
close (getFD (fileHandle));
fileHandle = 0;
}
}
std::ptrdiff_t FileOutputStream::writeInternal (const void* const data, const size_t numBytes)
{
std::ptrdiff_t result = 0;
if (fileHandle != 0)
{
result = ::write (getFD (fileHandle), data, numBytes);
if (result == -1)
status = getResultForErrno();
}
return result;
}
void FileOutputStream::flushInternal()
{
if (fileHandle != 0)
{
if (fsync (getFD (fileHandle)) == -1)
status = getResultForErrno();
#if BEAST_ANDROID
// This stuff tells the OS to asynchronously update the metadata
// that the OS has cached aboud the file - this metadata is used
// when the device is acting as a USB drive, and unless it's explicitly
// refreshed, it'll get out of step with the real file.
const LocalRef<jstring> t (javaString (file.getFullPathName()));
android.activity.callVoidMethod (BeastAppActivity.scanFile, t.get());
#endif
}
}
Result FileOutputStream::truncate()
{
if (fileHandle == 0)
return status;
flush();
return getResultForReturnValue (ftruncate (getFD (fileHandle), (off_t) currentPosition));
}
//==============================================================================
Result RandomAccessFile::nativeOpen (File const& path, Mode mode)
{
bassert (! isOpen ());
Result result (Result::ok ());
if (path.exists())
{
int oflag;
switch (mode)
{
case readOnly:
oflag = O_RDONLY;
break;
default:
case readWrite:
oflag = O_RDWR;
break;
};
const int f = ::open (path.getFullPathName().toUTF8(), oflag, 00644);
if (f != -1)
{
currentPosition = lseek (f, 0, SEEK_SET);
if (currentPosition >= 0)
{
file = path;
fileHandle = fdToVoidPointer (f);
}
else
{
result = getResultForErrno();
::close (f);
}
}
else
{
result = getResultForErrno();
}
}
else if (mode == readWrite)
{
const int f = ::open (path.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
if (f != -1)
{
file = path;
fileHandle = fdToVoidPointer (f);
}
else
{
result = getResultForErrno();
}
}
else
{
// file doesn't exist and we're opening read-only
Result::fail (String (strerror (ENOENT)));
}
return result;
}
void RandomAccessFile::nativeClose ()
{
bassert (isOpen ());
file = File::nonexistent ();
::close (getFD (fileHandle));
fileHandle = nullptr;
currentPosition = 0;
}
Result RandomAccessFile::nativeSetPosition (FileOffset newPosition)
{
bassert (isOpen ());
off_t const actualPosition = lseek (getFD (fileHandle), newPosition, SEEK_SET);
currentPosition = actualPosition;
if (actualPosition != newPosition)
{
// VFALCO NOTE I dislike return from the middle but
// Result::ok() is showing up in the profile
//
return getResultForErrno();
}
return Result::ok();
}
Result RandomAccessFile::nativeRead (void* buffer, ByteCount numBytes, ByteCount* pActualAmount)
{
bassert (isOpen ());
std::ptrdiff_t bytesRead = ::read (getFD (fileHandle), buffer, numBytes);
if (bytesRead < 0)
{
if (pActualAmount != nullptr)
*pActualAmount = 0;
// VFALCO NOTE I dislike return from the middle but
// Result::ok() is showing up in the profile
//
return getResultForErrno();
}
currentPosition += bytesRead;
if (pActualAmount != nullptr)
*pActualAmount = bytesRead;
return Result::ok();
}
Result RandomAccessFile::nativeWrite (void const* data, ByteCount numBytes, size_t* pActualAmount)
{
bassert (isOpen ());
std::ptrdiff_t bytesWritten = ::write (getFD (fileHandle), data, numBytes);
// write(3) says that the actual return will be exactly -1 on
// error, but we will assume anything negative indicates failure.
//
if (bytesWritten < 0)
{
if (pActualAmount != nullptr)
*pActualAmount = 0;
// VFALCO NOTE I dislike return from the middle but
// Result::ok() is showing up in the profile
//
return getResultForErrno();
}
if (pActualAmount != nullptr)
*pActualAmount = bytesWritten;
return Result::ok();
}
Result RandomAccessFile::nativeTruncate ()
{
bassert (isOpen ());
flush();
return getResultForReturnValue (ftruncate (getFD (fileHandle), (off_t) currentPosition));
}
Result RandomAccessFile::nativeFlush ()
{
bassert (isOpen ());
Result result (Result::ok ());
if (fsync (getFD (fileHandle)) == -1)
result = getResultForErrno();
#if BEAST_ANDROID
// This stuff tells the OS to asynchronously update the metadata
// that the OS has cached aboud the file - this metadata is used
// when the device is acting as a USB drive, and unless it's explicitly
// refreshed, it'll get out of step with the real file.
const LocalRef<jstring> t (javaString (file.getFullPathName()));
android.activity.callVoidMethod (BeastAppActivity.scanFile, t.get());
#endif
return result;
}
//==============================================================================
String SystemStats::getEnvironmentVariable (const String& name, const String& defaultValue)
{
if (const char* s = ::getenv (name.toUTF8()))
return String::fromUTF8 (s);
return defaultValue;
}
//==============================================================================
#if BEAST_PROBEASTR_LIVE_BUILD
extern "C" const char* beast_getCurrentExecutablePath();
#endif
File beast_getExecutableFile();
File beast_getExecutableFile()
{
#if BEAST_PROBEASTR_LIVE_BUILD
return File (beast_getCurrentExecutablePath());
#elif BEAST_ANDROID
return File (android.appFile);
#else
struct DLAddrReader
{
static String getFilename()
{
Dl_info exeInfo;
dladdr ((void*) beast_getExecutableFile, &exeInfo);
return CharPointer_UTF8 (exeInfo.dli_fname);
}
};
static String filename (DLAddrReader::getFilename());
return File::getCurrentWorkingDirectory().getChildFile (filename);
#endif
}
//==============================================================================
std::int64_t File::getBytesFreeOnVolume() const
{
struct statfs buf;
if (beast_doStatFS (*this, buf))
return (std::int64_t) buf.f_bsize * (std::int64_t) buf.f_bavail; // Note: this returns space available to non-super user
return 0;
}
std::int64_t File::getVolumeTotalSize() const
{
struct statfs buf;
if (beast_doStatFS (*this, buf))
return (std::int64_t) buf.f_bsize * (std::int64_t) buf.f_blocks;
return 0;
}
String File::getVolumeLabel() const
{
#if BEAST_MAC
struct VolAttrBuf
{
u_int32_t length;
attrreference_t mountPointRef;
char mountPointSpace [MAXPATHLEN];
} attrBuf;
struct attrlist attrList;
zerostruct (attrList); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct)
attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
File f (*this);
for (;;)
{
if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
(int) attrBuf.mountPointRef.attr_length);
const File parent (f.getParentDirectory());
if (f == parent)
break;
f = parent;
}
#endif
return String::empty;
}
int File::getVolumeSerialNumber() const
{
int result = 0;
/* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
char info [512];
#ifndef HDIO_GET_IDENTITY
#define HDIO_GET_IDENTITY 0x030d
#endif
if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
{
DBG (String (info + 20, 20));
result = String (info + 20, 20).trim().getIntValue();
}
close (fd);*/
return result;
}
//==============================================================================
void beast_runSystemCommand (const String&);
void beast_runSystemCommand (const String& command)
{
int result = system (command.toUTF8());
(void) result;
}
String beast_getOutputFromCommand (const String&);
String beast_getOutputFromCommand (const String& command)
{
// slight bodge here, as we just pipe the output into a temp file and read it...
const File tempFile (File::getSpecialLocation (File::tempDirectory)
.getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
beast_runSystemCommand (command + " > " + tempFile.getFullPathName());
String result (tempFile.loadFileAsString());
tempFile.deleteFile();
return result;
}
//==============================================================================
bool DynamicLibrary::open (const String& name)
{
close();
handle = dlopen (name.isEmpty() ? nullptr : name.toUTF8().getAddress(), RTLD_LOCAL | RTLD_NOW);
return handle != nullptr;
}
void DynamicLibrary::close()
{
if (handle != nullptr)
{
dlclose (handle);
handle = nullptr;
}
}
void* DynamicLibrary::getFunction (const String& functionName) noexcept
{
return handle != nullptr ? dlsym (handle, functionName.toUTF8()) : nullptr;
}
} // beast
| [
"meanz1235@gmail.com"
] | meanz1235@gmail.com |
fa5ef282282d3f6b8952562ba66d5985c5689b7f | 78a2dd7e0df27506689f0f5b86737dbeb8966ebd | /src/rt/rust_task_list.cpp | 635ee13667d82c5d996106ba80013bff361c5091 | [
"bzip2-1.0.6",
"BSD-1-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | benjaminjackman/rust | 06cc431763a3051f22e90259640d4e0732c4dcb1 | 7f4ec2c622a8fd6eb6d27a88ae51daa362834519 | refs/heads/master | 2021-01-16T21:49:18.155860 | 2011-01-18T02:09:35 | 2011-01-18T02:09:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | cpp | #include "rust_internal.h"
rust_task_list::rust_task_list (rust_dom *dom, const char* name) :
dom(dom), name(name) {
// Nop;
}
void
rust_task_list::delete_all() {
dom->log(rust_log::TASK, "deleting all %s tasks", name);
while (is_empty() == false) {
rust_task *task = pop_value();
dom->log(rust_log::TASK, "deleting task " PTR, task);
delete task;
}
}
| [
"mbebenita@mozilla.com"
] | mbebenita@mozilla.com |
9fd49b8d0f4258553239f58daa70d84082eebe06 | 0b6397af52f05ff9d0b8dba3672b90fc6a9324f3 | /analyzecore/TestStructuredStorage/ShapeTypeFactory.cpp | bcca145181d9a6e59d34d8b7013e74282da58696 | [] | no_license | lgh710681042/parsecore | 35a9c390d32f714bb8963d46f3f508122c0f4617 | 48cd98ae2fa6dc371a01942ba75ce21966bba09c | refs/heads/master | 2020-07-07T16:14:11.372377 | 2020-05-31T16:03:46 | 2020-05-31T16:03:46 | 203,401,704 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 683 | cpp | #include "stdafx.h"
#include "GlobalDefines.h"
#include "Singleton.h"
#include "Handle.h"
#include "ProtectionBooleans.h"
#include "ShapeType.h"
#include "RectangleType.h"
#include "PictureFrameType.h"
#include "ShapeTypeFactory.h"
ShapeTypeFactory::ShapeTypeFactory()
{
}
ShapeTypeFactory::~ShapeTypeFactory()
{
}
std::shared_ptr<ShapeType> ShapeTypeFactory::CreateShapeType(unsigned long typeCode)
{
shared_ptr<ShapeType> spShapeType = nullptr;
switch (typeCode)
{
case 0x00000001:
{
spShapeType = make_shared<RectangleType>();
}
break;
case 0x0000004b:
{
spShapeType = make_shared<PictureFrameType>();
}
break;
default:
break;
}
return spShapeType;
}
| [
"lgh710681042@gmail.com"
] | lgh710681042@gmail.com |
fdc7034bd053e8670ed12da05b19c0d68b7ece0a | b3f46d9388a1972a84137d58fa7b86132bcd2f56 | /tuan02/tuan 2.C-02.cpp | 303e55cf72af5cbb3ce2967af99fcbaad00ce704 | [] | no_license | lamthienphong-20021567/laptrinhnangcao | c236ab66bd1bc7fca0bf2b63e06efa2d75c7f6cc | 179b3aef7b9d8b456147f0ef98327160308e8a90 | refs/heads/main | 2023-04-28T05:43:10.206585 | 2021-05-13T15:28:00 | 2021-05-13T15:28:00 | 336,136,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cout << "nhap n:";cin >> n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j<i) cout << " ";
if(j>=i)
{
cout << "*";}
}
cout << "\n";
}
return 0;
}
| [
"="
] | = |
17add1d5b1648a5a425c68f141b58707be69c473 | f89b1cf00a14d3315be610a1e2ba1a1fd32bb144 | /784.cpp | 208d571885e289d0865b687379cd6d4a0c2577ae | [] | no_license | IMCG/LeetCode-1 | 2cf7a7b88a232cbd8cb12ab3b4a6ab818eecfb56 | 52d327705ad5ad5dd72aa913c041b31ea6f4daaf | refs/heads/master | 2020-07-26T07:00:57.770329 | 2018-12-29T09:04:22 | 2018-12-29T09:04:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> s_vec;
permutation(s_vec, S, 0);
return s_vec;
}
private:
void permutation (vector<string> &vec, string s, size_t index) {
if (index == s.size())
vec.push_back(move(s));
else {
if (isalpha(s[index])) {
permutation(vec, s, index+1);
if (isupper(s[index])) {
s[index] = tolower(s[index]);
permutation(vec, s, index+1);
}
else {
s[index] = toupper(s[index]);
permutation(vec, s, index+1);
}
}
else
permutation(vec, s, index+1);
}
}
};
| [
"kobe.792244049@qq.com"
] | kobe.792244049@qq.com |
ee240f09323aea607f1bc4a7af2def569c407cbb | 13eb2b8973044567bc879644d703ad1394db85a5 | /1.Window/src/Shader.cpp | b04d90860548437f36b02abe7c0aebe581fe9af7 | [] | no_license | ZacharyBriggs/OpenGL | da62ea23169ac187c2a5aa09870f0d6f2179e790 | ef8abe3b5fc9fa11c88056a217dac3477324b6ab | refs/heads/master | 2020-03-26T22:50:19.496987 | 2019-01-18T17:01:22 | 2019-01-18T17:01:22 | 145,490,823 | 0 | 1 | null | 2018-10-04T22:28:44 | 2018-08-21T01:44:48 | C++ | UTF-8 | C++ | false | false | 2,892 | cpp | #define GLM_FORCE_SWIZZLE
#include "Shader.h"
#include <cstdio>
#include "gl_core_4_4.h"
#include <iostream>
Shader::Shader()
{
m_program = glCreateProgram();
}
Shader::~Shader()
{
}
void Shader::bind()
{
glUseProgram(m_program);
}
void Shader::unbind()
{
glUseProgram(0);
}
//8. Ability to load shaders from file using a Shader class object.
//Takes in the name of the file and the type of the file.
//0 is a vertex shader. 1 is a fragment shader.
void Shader::load(const char * filename, unsigned int type)
{
//Error code incase something goes wrong.
errno_t err;
//Make a file variable so we can find and open the file.
FILE *fp;
//Look for the file and open it for reading
err = fopen_s(&fp, filename, "r");
//We make a buffer of sufficent size to store all the data.
char buf[500];
//A string to appened the buffered data to.
std::string str;
//Open the file and loop through while there is data in the file that hasn't been buffered.
while (std::fgets(buf, sizeof buf, fp))
{
//Depending on the type we append the buffered data to a vertex or fragment string
if (type == 0)
vsStr.append(buf);
if (type == 1)
fsStr.append(buf);
}
//We assign the data to one of the member variables depending on the type.
if (type == 0)
vsSource = vsStr.c_str();
if (type == 1)
fsSource = fsStr.c_str();
}
bool Shader::attach()
{
m_vertexShader = glCreateShader(GL_VERTEX_SHADER);
m_fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(m_vertexShader, 1, (const char**)&vsSource, 0);
glCompileShader(m_vertexShader);
glShaderSource(m_fragmentShader, 1, (const char**)&fsSource, 0);
glCompileShader(m_fragmentShader);
glAttachShader(m_program, m_vertexShader);
glAttachShader(m_program, m_fragmentShader);
glLinkProgram(m_program);
int success = GL_FALSE;
// check that it compiled and linked correctly
glGetProgramiv(m_program, GL_LINK_STATUS, &success);
if (success == GL_FALSE) {
int infoLogLength = 0;
glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &infoLogLength);
char* infoLog = new char[infoLogLength + 1];
glGetProgramInfoLog(m_program, infoLogLength, 0, infoLog);
printf("Error: Failed to link shader program!\n");
printf("%s\n", infoLog);
delete[] infoLog;
}
return true;
}
void Shader::defaultLoad()
{
vsSource = "#version 410\n \
layout(location = 0) in vec4 Position; \
layout(location = 1) in vec4 Color; \
out vec4 vColor; \
uniform mat4 ProjectionViewWorld; \
void main() { vColor = Color; \
gl_Position = ProjectionViewWorld * Position; }";
fsSource = "#version 410\n \
in vec4 vColor; \
out vec4 FragColor; \
void main() { FragColor = vColor; }";
}
unsigned int Shader::getUniform(const char *mvp)
{
return glGetUniformLocation(m_program, mvp);;
}
| [
"zacharybriggs64@gmail.com"
] | zacharybriggs64@gmail.com |
c6de9123f72ca4cce6f6a739c895be45d34198a7 | c4a74feb0c1548c76b66b3e2e943f11b3e9bf69a | /BattlePack.h | 3178be7d2d6dca8ab284ec83d516ee11e3e6b81e | [] | no_license | GreggZumbari/Red-Black-Tree | 3be17ccea6ca9e177b676f77e138c2d300a1d322 | 116ad97a8ff60348c368acc6bd4390fc6866c2c9 | refs/heads/master | 2022-07-17T02:55:18.402658 | 2020-05-19T07:02:31 | 2020-05-19T07:02:31 | 249,117,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,138 | h | //BattlePack.h
/*
Hi. I'm Greggory Hickman, and these are some helpful methods to use in your C++ code.
*/
#include <iostream>
#include <cstring>
#include <math.h>
#define LEN 100
#define BIGLEN 3000
using namespace std;
/*
Clears all data from a cstring. Can be used to empty out a previously used cstring, or to clear any random RAM still present inside.
@author Greggory Hickman, February 2020
*/
void clearCString(char*& in, int len) {
for (int i = 0; i < len; i++) {
in[i] = (char)0;
}
}
/*
Clears all data from an int array. Can be used to empty out a previously used array, or to clear any random RAM still present inside.
@author Greggory Hickman, February 2020
*/
void clearIntArray(int*& in, int len) {
for (int i = 0; i < len; i++) {
in[i] = 0;
}
}
/*
Converts a character terminated cstring of numbers to an array of intergers. Ignores things other than numbers, making them safe to input.
The character that separates each number can be specified. For example, for a traditional zero terminated string, separator should be '0' or (char)48.
This method uses the clearCString method which can be seen above. Please keep that in mind when using this code.
@author Greggory Hickman, February 2020
*/
int* parseZTCString(char* charList, char separator) {
char* current = new char[LEN];
int* numList = new int[LEN];
//Clear pesky leftover ram from pointer arrays
clearCString(current, LEN);
clearIntArray(numList, LEN);
//cout << "Starting charList: " << charList << endl;
//cout << "Starting current: " << current << endl;
//Parse the input
int j = 0; //Iterator for current
int k = 0; //Iterator for numList
for (int i = 0; i < BIGLEN + 1; i++) {
//If we have hit the 100 number max limit
if (k >= LEN - 1) {
break;
}
//If is number
if (charList[i] >= 48 && charList[i] <= 57) {
//Add the digit to the end of the current multi-digit number
current[j] = charList[i];
j++;
}
//If is space
else if (charList[i] == separator) {
if (j != 0) {
//cout << "Space: " << current << endl;
//current contains the number that we want to convert to an integer
int next = 0;
//Iterate backwards through current
for (int l = j - 1; l >= 0; l--) {
//Convert the char* to int one unit place at a time by adding each value * 10^place. For example, when in the hundred's place, place = 2.
next += (current[l] - 48) * round(pow(10, j - l - 1));
}
//cout << "Next: " << next << endl;
numList[k] = next;
j = 0;
k++;
clearCString(current, LEN);
}
}
//If is null
else if (charList[i] == 0) {
if (j != 0) {
//cout << "Null: " << current << endl;
//current contains the number that we want to convert to an integer
int next = 0;
//Iterate backwards through current
for (int l = j - 1; l >= 0; l--) {
//Convert the char* to int one unit place at a time by adding each value * 10^place. For example, when in the hundred's place, place = 2.
next += (current[l] - 48) * round(pow(10, j - l - 1));
}
numList[k] = next;
break;
}
}
}
delete[] current;
return numList;
} | [
"greggory.png@gmail.com"
] | greggory.png@gmail.com |
88d0342aad46aa3930a2488c14f0beb48623e2c7 | 8b8e51e94e61654a3f331b7e4fa6770d1b3dd4d7 | /TnbSectPx/include/SectPx_CmptProfile.hxx | 75f121d3d405244d1d9575f590ac2cd75f7ddf9e | [] | no_license | PayvandH/Tonb | 1ea829d6732a3645bbf117a8857af5600e9a5192 | 6964200f033ab0b53fc3f3bfa8d58ca9578ecc66 | refs/heads/master | 2023-01-12T21:24:30.491648 | 2020-11-13T17:12:09 | 2020-11-13T17:12:09 | 312,663,721 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | hxx | #pragma once
#ifndef _SectPx_CmptProfile_Header
#define _SectPx_CmptProfile_Header
#include <SectPx_RegObj.hxx>
#include <map>
#include <vector>
namespace tnbLib
{
// Forward Declarations
class SectPx_TopoProfile;
class SectPx_CmptProfile
: public SectPx_RegObj
{
/*Private Data*/
std::vector<std::shared_ptr<SectPx_TopoProfile>> theProfiles_;
DECLARE_SAVE_LOAD_HEADER(TnbSectPx_EXPORT);
auto& ChangeProfiles()
{
return theProfiles_;
}
public:
static const char* typeName_;
SectPx_CmptProfile()
{}
Standard_Integer NbProfiles() const
{
return (Standard_Integer)theProfiles_.size();
}
const auto& Profiles() const
{
return theProfiles_;
}
Standard_Boolean IsCmptProfile() const override;
word RegObjTypeName() const override;
sectPxLib::regObjType RegObjType() const override;
};
}
BOOST_CLASS_EXPORT_KEY(tnbLib::SectPx_CmptProfile);
#endif // !_SectPx_CmptProfile_Header
| [
"aasoleimani86@gmail.com"
] | aasoleimani86@gmail.com |
b4c99c69d64ea0b1b481dd04c0a323440228b9bf | 4e77500110fdf83d7a86a329efe0a186fa7b43a6 | /src/core/SkPaint_text.cpp | 21a7c9570bff809c2480df736eaaa6ebb6eb7f9e | [
"BSD-3-Clause"
] | permissive | MonkeyNinja/skia | ba359871bd8c0fc6a55322a72c848a7be5371fd4 | ef4709b7850d0da575010e64f7a4d9eeeefcc83f | refs/heads/master | 2020-04-05T13:10:16.567088 | 2018-11-09T14:37:21 | 2018-11-09T15:41:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,204 | cpp | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPaint.h"
#include "SkColorFilter.h"
#include "SkDraw.h"
#include "SkFontDescriptor.h"
#include "SkGlyphCache.h"
#include "SkGraphics.h"
#include "SkPaintDefaults.h"
#include "SkPaintPriv.h"
#include "SkPathEffect.h"
#include "SkSafeRange.h"
#include "SkScalar.h"
#include "SkScalerContext.h"
#include "SkShader.h"
#include "SkShaderBase.h"
#include "SkStringUtils.h"
#include "SkTLazy.h"
#include "SkTextBlob.h"
#include "SkTextBlobPriv.h"
#include "SkTextFormatParams.h"
#include "SkTextToPathIter.h"
#include "SkTo.h"
#include "SkTypeface.h"
///////////////////////////////////////////////////////////////////////////////
static SkScalar mag2(SkScalar x, SkScalar y) {
return x * x + y * y;
}
static bool tooBig(const SkMatrix& m, SkScalar ma2max) {
return mag2(m[SkMatrix::kMScaleX], m[SkMatrix::kMSkewY]) > ma2max
||
mag2(m[SkMatrix::kMSkewX], m[SkMatrix::kMScaleY]) > ma2max;
}
bool SkPaint::TooBigToUseCache(const SkMatrix& ctm, const SkMatrix& textM, SkScalar maxLimit) {
SkASSERT(!ctm.hasPerspective());
SkASSERT(!textM.hasPerspective());
SkMatrix matrix;
matrix.setConcat(ctm, textM);
return tooBig(matrix, MaxCacheSize2(maxLimit));
}
SkScalar SkPaint::MaxCacheSize2(SkScalar maxLimit) {
// we have a self-imposed maximum, just for memory-usage sanity
const int limit = SkMin32(SkGraphics::GetFontCachePointSizeLimit(), maxLimit);
const SkScalar maxSize = SkIntToScalar(limit);
return maxSize * maxSize;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkGlyphCache.h"
#include "SkUtils.h"
int SkPaint::countText(const void* text, size_t byteLength) const {
SkASSERT(text != nullptr);
switch (this->getTextEncoding()) {
case kUTF8_TextEncoding:
return SkUTF::CountUTF8((const char*)text, byteLength);
case kUTF16_TextEncoding:
return SkUTF::CountUTF16((const uint16_t*)text, byteLength);
case kUTF32_TextEncoding:
return SkToInt(byteLength >> 2);
case kGlyphID_TextEncoding:
return SkToInt(byteLength >> 1);
default:
SkDEBUGFAIL("unknown text encoding");
}
return 0;
}
static SkTypeface::Encoding to_encoding(SkPaint::TextEncoding e) {
static_assert((int)SkTypeface::kUTF8_Encoding == (int)SkPaint::kUTF8_TextEncoding, "");
static_assert((int)SkTypeface::kUTF16_Encoding == (int)SkPaint::kUTF16_TextEncoding, "");
static_assert((int)SkTypeface::kUTF32_Encoding == (int)SkPaint::kUTF32_TextEncoding, "");
return (SkTypeface::Encoding)e;
}
int SkPaint::textToGlyphs(const void* textData, size_t byteLength, uint16_t glyphs[]) const {
SkASSERT(textData != nullptr);
if (nullptr == glyphs) {
return this->countText(textData, byteLength);
}
// if we get here, we have a valid glyphs[] array, so time to fill it in
// handle this encoding before the setup for the glyphcache
if (this->getTextEncoding() == kGlyphID_TextEncoding) {
// we want to ignore the low bit of byteLength
memcpy(glyphs, textData, byteLength >> 1 << 1);
return SkToInt(byteLength >> 1);
}
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(*this);
const void* stop = (const char*)textData + byteLength;
uint16_t* gptr = glyphs;
const SkTypeface::Encoding encoding = to_encoding(this->getTextEncoding());
while (textData < stop) {
SkUnichar unichar = SkUTFN_Next(encoding, &textData, stop);
if (unichar < 0) {
return 0; // bad UTF-N sequence
}
*gptr++ = cache->unicharToGlyph(unichar);
}
return SkToInt(gptr - glyphs);
}
bool SkPaint::containsText(const void* textData, size_t byteLength) const {
if (0 == byteLength) {
return true;
}
SkASSERT(textData != nullptr);
// handle this encoding before the setup for the glyphcache
if (this->getTextEncoding() == kGlyphID_TextEncoding) {
const uint16_t* glyphID = static_cast<const uint16_t*>(textData);
size_t count = byteLength >> 1;
for (size_t i = 0; i < count; i++) {
if (0 == glyphID[i]) {
return false;
}
}
return true;
}
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(*this);
const void* stop = (const char*)textData + byteLength;
const SkTypeface::Encoding encoding = to_encoding(this->getTextEncoding());
while (textData < stop) {
if (0 == cache->unicharToGlyph(SkUTFN_Next(encoding, &textData, stop))) {
return false;
}
}
return true;
}
void SkPaint::glyphsToUnichars(const uint16_t glyphs[], int count, SkUnichar textData[]) const {
if (count <= 0) {
return;
}
SkASSERT(glyphs != nullptr);
SkASSERT(textData != nullptr);
SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(
*this, &props, SkScalerContextFlags::kFakeGammaAndBoostContrast, nullptr);
for (int index = 0; index < count; index++) {
textData[index] = cache->glyphToUnichar(glyphs[index]);
}
}
///////////////////////////////////////////////////////////////////////////////
static const SkGlyph& sk_getMetrics_utf8_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharMetrics(SkUTF::NextUTF8(text, stop));
}
static const SkGlyph& sk_getMetrics_utf16_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharMetrics(
SkUTF::NextUTF16((const uint16_t**)text, (const uint16_t*)stop));
}
static const SkGlyph& sk_getMetrics_utf32_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharMetrics(SkUTF::NextUTF32((const int32_t**)text, (const int32_t*)stop));
}
static const SkGlyph& sk_getMetrics_glyph_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
const uint16_t* ptr = *(const uint16_t**)text;
unsigned glyphID = *ptr;
ptr += 1;
*text = (const char*)ptr;
return cache->getGlyphIDMetrics(glyphID);
}
static const SkGlyph& sk_getAdvance_utf8_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharAdvance(SkUTF::NextUTF8(text, stop));
}
static const SkGlyph& sk_getAdvance_utf16_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharAdvance(
SkUTF::NextUTF16((const uint16_t**)text, (const uint16_t*)stop));
}
static const SkGlyph& sk_getAdvance_utf32_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
return cache->getUnicharAdvance(SkUTF::NextUTF32((const int32_t**)text, (const int32_t*)stop));
}
static const SkGlyph& sk_getAdvance_glyph_next(SkGlyphCache* cache,
const char** text,
const char* stop) {
SkASSERT(cache != nullptr);
SkASSERT(text != nullptr);
const uint16_t* ptr = *(const uint16_t**)text;
unsigned glyphID = *ptr;
ptr += 1;
*text = (const char*)ptr;
return cache->getGlyphIDAdvance(glyphID);
}
SkPaint::GlyphCacheProc SkPaint::GetGlyphCacheProc(TextEncoding encoding,
bool needFullMetrics) {
static const GlyphCacheProc gGlyphCacheProcs[] = {
sk_getMetrics_utf8_next,
sk_getMetrics_utf16_next,
sk_getMetrics_utf32_next,
sk_getMetrics_glyph_next,
sk_getAdvance_utf8_next,
sk_getAdvance_utf16_next,
sk_getAdvance_utf32_next,
sk_getAdvance_glyph_next,
};
unsigned index = encoding;
if (!needFullMetrics) {
index += 4;
}
SkASSERT(index < SK_ARRAY_COUNT(gGlyphCacheProcs));
return gGlyphCacheProcs[index];
}
///////////////////////////////////////////////////////////////////////////////
SkScalar SkPaint::setupForAsPaths() {
constexpr uint32_t flagsToIgnore = SkPaint::kLinearText_Flag |
SkPaint::kLCDRenderText_Flag |
SkPaint::kEmbeddedBitmapText_Flag |
SkPaint::kAutoHinting_Flag;
uint32_t flags = this->getFlags();
// clear the flags we don't care about
flags &= ~flagsToIgnore;
// set the flags we do care about
flags |= SkPaint::kSubpixelText_Flag;
this->setFlags(flags);
this->setHinting(kNo_SkFontHinting);
this->setStyle(SkPaint::kFill_Style);
this->setPathEffect(nullptr);
SkScalar textSize = fTextSize;
this->setTextSize(kCanonicalTextSizeForPaths);
return textSize / kCanonicalTextSizeForPaths;
}
class SkCanonicalizePaint {
public:
SkCanonicalizePaint(const SkPaint& paint) : fPaint(&paint), fScale(0) {
if (paint.isLinearText() || SkDraw::ShouldDrawTextAsPaths(paint, SkMatrix::I())) {
SkPaint* p = fLazy.set(paint);
fScale = p->setupForAsPaths();
fPaint = p;
}
}
const SkPaint& getPaint() const { return *fPaint; }
/**
* Returns 0 if the paint was unmodified, or the scale factor need to
* the original textSize
*/
SkScalar getScale() const { return fScale; }
private:
const SkPaint* fPaint;
SkScalar fScale;
SkTLazy<SkPaint> fLazy;
};
static void set_bounds(const SkGlyph& g, SkRect* bounds) {
bounds->set(SkIntToScalar(g.fLeft),
SkIntToScalar(g.fTop),
SkIntToScalar(g.fLeft + g.fWidth),
SkIntToScalar(g.fTop + g.fHeight));
}
static void join_bounds_x(const SkGlyph& g, SkRect* bounds, SkScalar dx) {
bounds->join(SkIntToScalar(g.fLeft) + dx,
SkIntToScalar(g.fTop),
SkIntToScalar(g.fLeft + g.fWidth) + dx,
SkIntToScalar(g.fTop + g.fHeight));
}
// xyIndex is 0 for fAdvanceX or 1 for fAdvanceY
static SkScalar advance(const SkGlyph& glyph) {
return SkFloatToScalar(glyph.fAdvanceX);
}
SkScalar SkPaint::measure_text(SkGlyphCache* cache,
const char* text, size_t byteLength,
int* count, SkRect* bounds) const {
SkASSERT(count);
if (byteLength == 0) {
*count = 0;
if (bounds) {
bounds->setEmpty();
}
return 0;
}
GlyphCacheProc glyphCacheProc = SkPaint::GetGlyphCacheProc(this->getTextEncoding(),
nullptr != bounds);
int n = 1;
const char* stop = (const char*)text + byteLength;
const SkGlyph* g = &glyphCacheProc(cache, &text, stop);
SkScalar x = advance(*g);
if (nullptr == bounds) {
for (; text < stop; n++) {
x += advance(glyphCacheProc(cache, &text, stop));
}
} else {
set_bounds(*g, bounds);
for (; text < stop; n++) {
g = &glyphCacheProc(cache, &text, stop);
join_bounds_x(*g, bounds, x);
x += advance(*g);
}
}
SkASSERT(text == stop);
*count = n;
return x;
}
SkScalar SkPaint::measureText(const void* textData, size_t length, SkRect* bounds) const {
const char* text = (const char*)textData;
SkASSERT(text != nullptr || length == 0);
SkCanonicalizePaint canon(*this);
const SkPaint& paint = canon.getPaint();
SkScalar scale = canon.getScale();
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(paint);
SkScalar width = 0;
if (length > 0) {
int tempCount;
width = paint.measure_text(cache.get(), text, length, &tempCount, bounds);
if (scale) {
width *= scale;
if (bounds) {
bounds->fLeft *= scale;
bounds->fTop *= scale;
bounds->fRight *= scale;
bounds->fBottom *= scale;
}
}
} else if (bounds) {
// ensure that even if we don't measure_text we still update the bounds
bounds->setEmpty();
}
return width;
}
size_t SkPaint::breakText(const void* textD, size_t length, SkScalar maxWidth,
SkScalar* measuredWidth) const {
if (0 == length || 0 >= maxWidth) {
if (measuredWidth) {
*measuredWidth = 0;
}
return 0;
}
if (0 == fTextSize) {
if (measuredWidth) {
*measuredWidth = 0;
}
return length;
}
SkASSERT(textD != nullptr);
const char* text = (const char*)textD;
const char* stop = text + length;
SkCanonicalizePaint canon(*this);
const SkPaint& paint = canon.getPaint();
SkScalar scale = canon.getScale();
// adjust max in case we changed the textSize in paint
if (scale) {
maxWidth /= scale;
}
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(paint);
GlyphCacheProc glyphCacheProc = SkPaint::GetGlyphCacheProc(paint.getTextEncoding(),
false);
SkScalar width = 0;
while (text < stop) {
const char* curr = text;
SkScalar x = advance(glyphCacheProc(cache.get(), &text, stop));
if ((width += x) > maxWidth) {
width -= x;
text = curr;
break;
}
}
if (measuredWidth) {
if (scale) {
width *= scale;
}
*measuredWidth = width;
}
// return the number of bytes measured
return text - stop + length;
}
///////////////////////////////////////////////////////////////////////////////
SkScalar SkPaint::getFontMetrics(SkFontMetrics* metrics) const {
SkCanonicalizePaint canon(*this);
const SkPaint& paint = canon.getPaint();
SkScalar scale = canon.getScale();
FontMetrics storage;
if (nullptr == metrics) {
metrics = &storage;
}
SkAutoDescriptor ad;
SkScalerContextEffects effects;
auto desc = SkScalerContext::CreateDescriptorAndEffectsUsingPaint(
paint, nullptr, SkScalerContextFlags::kNone, nullptr, &ad, &effects);
{
auto typeface = SkPaintPriv::GetTypefaceOrDefault(paint);
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(*desc, effects, *typeface);
*metrics = cache->getFontMetrics();
}
if (scale) {
SkPaintPriv::ScaleFontMetrics(metrics, scale);
}
return metrics->fDescent - metrics->fAscent + metrics->fLeading;
}
///////////////////////////////////////////////////////////////////////////////
static void set_bounds(const SkGlyph& g, SkRect* bounds, SkScalar scale) {
bounds->set(g.fLeft * scale,
g.fTop * scale,
(g.fLeft + g.fWidth) * scale,
(g.fTop + g.fHeight) * scale);
}
int SkPaint::getTextWidths(const void* textData, size_t byteLength,
SkScalar widths[], SkRect bounds[]) const {
if (0 == byteLength) {
return 0;
}
SkASSERT(textData);
if (nullptr == widths && nullptr == bounds) {
return this->countText(textData, byteLength);
}
SkCanonicalizePaint canon(*this);
const SkPaint& paint = canon.getPaint();
SkScalar scale = canon.getScale();
auto cache = SkStrikeCache::FindOrCreateStrikeExclusive(paint);
GlyphCacheProc glyphCacheProc = SkPaint::GetGlyphCacheProc(paint.getTextEncoding(),
nullptr != bounds);
const char* text = (const char*)textData;
const char* stop = text + byteLength;
int count = 0;
if (scale) {
while (text < stop) {
const SkGlyph& g = glyphCacheProc(cache.get(), &text, stop);
if (widths) {
*widths++ = advance(g) * scale;
}
if (bounds) {
set_bounds(g, bounds++, scale);
}
++count;
}
} else {
while (text < stop) {
const SkGlyph& g = glyphCacheProc(cache.get(), &text, stop);
if (widths) {
*widths++ = advance(g);
}
if (bounds) {
set_bounds(g, bounds++);
}
++count;
}
}
SkASSERT(text == stop);
return count;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkDraw.h"
void SkPaint::getTextPath(const void* textData, size_t length,
SkScalar x, SkScalar y, SkPath* path) const {
SkASSERT(length == 0 || textData != nullptr);
const char* text = (const char*)textData;
if (text == nullptr || length == 0 || path == nullptr) {
return;
}
SkTextToPathIter iter(text, length, *this, false);
SkMatrix matrix;
SkScalar prevXPos = 0;
matrix.setScale(iter.getPathScale(), iter.getPathScale());
matrix.postTranslate(x, y);
path->reset();
SkScalar xpos;
const SkPath* iterPath;
while (iter.next(&iterPath, &xpos)) {
matrix.postTranslate(xpos - prevXPos, 0);
if (iterPath) {
path->addPath(*iterPath, matrix);
}
prevXPos = xpos;
}
}
void SkPaint::getPosTextPath(const void* textData, size_t length,
const SkPoint pos[], SkPath* path) const {
SkASSERT(length == 0 || textData != nullptr);
const char* text = (const char*)textData;
if (text == nullptr || length == 0 || path == nullptr) {
return;
}
SkTextToPathIter iter(text, length, *this, false);
SkMatrix matrix;
SkPoint prevPos;
prevPos.set(0, 0);
matrix.setScale(iter.getPathScale(), iter.getPathScale());
path->reset();
unsigned int i = 0;
const SkPath* iterPath;
while (iter.next(&iterPath, nullptr)) {
matrix.postTranslate(pos[i].fX - prevPos.fX, pos[i].fY - prevPos.fY);
if (iterPath) {
path->addPath(*iterPath, matrix);
}
prevPos = pos[i];
i++;
}
}
template <SkTextInterceptsIter::TextType TextType, typename Func>
int GetTextIntercepts(const SkPaint& paint, const void* text, size_t length,
const SkScalar bounds[2], SkScalar* array, Func posMaker) {
SkASSERT(length == 0 || text != nullptr);
if (!length) {
return 0;
}
const SkPoint pos0 = posMaker(0);
SkTextInterceptsIter iter(static_cast<const char*>(text), length, paint, bounds,
pos0.x(), pos0.y(), TextType);
int i = 0;
int count = 0;
while (iter.next(array, &count)) {
if (TextType == SkTextInterceptsIter::TextType::kPosText) {
const SkPoint pos = posMaker(++i);
iter.setPosition(pos.x(), pos.y());
}
}
return count;
}
int SkPaint::getTextIntercepts(const void* textData, size_t length,
SkScalar x, SkScalar y, const SkScalar bounds[2],
SkScalar* array) const {
return GetTextIntercepts<SkTextInterceptsIter::TextType::kText>(
*this, textData, length, bounds, array, [&x, &y] (int) -> SkPoint {
return SkPoint::Make(x, y);
});
}
int SkPaint::getPosTextIntercepts(const void* textData, size_t length, const SkPoint pos[],
const SkScalar bounds[2], SkScalar* array) const {
return GetTextIntercepts<SkTextInterceptsIter::TextType::kPosText>(
*this, textData, length, bounds, array, [&pos] (int i) -> SkPoint {
return pos[i];
});
}
int SkPaint::getPosTextHIntercepts(const void* textData, size_t length, const SkScalar xpos[],
SkScalar constY, const SkScalar bounds[2],
SkScalar* array) const {
return GetTextIntercepts<SkTextInterceptsIter::TextType::kPosText>(
*this, textData, length, bounds, array, [&xpos, &constY] (int i) -> SkPoint {
return SkPoint::Make(xpos[i], constY);
});
}
int SkPaint::getTextBlobIntercepts(const SkTextBlob* blob, const SkScalar bounds[2],
SkScalar* intervals) const {
int count = 0;
SkPaint runPaint(*this);
SkTextBlobRunIterator it(blob);
while (!it.done()) {
it.applyFontToPaint(&runPaint);
const size_t runByteCount = it.glyphCount() * sizeof(SkGlyphID);
SkScalar* runIntervals = intervals ? intervals + count : nullptr;
switch (it.positioning()) {
case SkTextBlobRunIterator::kDefault_Positioning:
count += runPaint.getTextIntercepts(it.glyphs(), runByteCount, it.offset().x(),
it.offset().y(), bounds, runIntervals);
break;
case SkTextBlobRunIterator::kHorizontal_Positioning:
count += runPaint.getPosTextHIntercepts(it.glyphs(), runByteCount, it.pos(),
it.offset().y(), bounds, runIntervals);
break;
case SkTextBlobRunIterator::kFull_Positioning:
count += runPaint.getPosTextIntercepts(it.glyphs(), runByteCount,
reinterpret_cast<const SkPoint*>(it.pos()),
bounds, runIntervals);
break;
}
it.next();
}
return count;
}
SkRect SkPaint::getFontBounds() const {
SkMatrix m;
m.setScale(fTextSize * fTextScaleX, fTextSize);
m.postSkew(fTextSkewX, 0);
SkTypeface* typeface = SkPaintPriv::GetTypefaceOrDefault(*this);
SkRect bounds;
m.mapRect(&bounds, typeface->getBounds());
return bounds;
}
// return true if the paint is just a single color (i.e. not a shader). If its
// a shader, then we can't compute a const luminance for it :(
static bool just_a_color(const SkPaint& paint, SkColor* color) {
SkColor c = paint.getColor();
const auto* shader = as_SB(paint.getShader());
if (shader && !shader->asLuminanceColor(&c)) {
return false;
}
if (paint.getColorFilter()) {
c = paint.getColorFilter()->filterColor(c);
}
if (color) {
*color = c;
}
return true;
}
SkColor SkPaint::computeLuminanceColor() const {
SkColor c;
if (!just_a_color(*this, &c)) {
c = SkColorSetRGB(0x7F, 0x80, 0x7F);
}
return c;
}
///////////////////////////////////////////////////////////////////////////////
static bool has_thick_frame(const SkPaint& paint) {
return paint.getStrokeWidth() > 0 &&
paint.getStyle() != SkPaint::kFill_Style;
}
SkTextBaseIter::SkTextBaseIter(const char text[], size_t length,
const SkPaint& paint,
bool applyStrokeAndPathEffects)
: fPaint(paint) {
fGlyphCacheProc = SkPaint::GetGlyphCacheProc(paint.getTextEncoding(), true);
fPaint.setLinearText(true);
fPaint.setMaskFilter(nullptr); // don't want this affecting our path-cache lookup
if (fPaint.getPathEffect() == nullptr && !has_thick_frame(fPaint)) {
applyStrokeAndPathEffects = false;
}
// can't use our canonical size if we need to apply patheffects
if (fPaint.getPathEffect() == nullptr) {
fPaint.setTextSize(SkIntToScalar(SkPaint::kCanonicalTextSizeForPaths));
fScale = paint.getTextSize() / SkPaint::kCanonicalTextSizeForPaths;
// Note: fScale can be zero here (even if it wasn't before the divide). It can also
// be very very small. We call sk_ieee_float_divide below to ensure IEEE divide behavior,
// since downstream we will check for the resulting coordinates being non-finite anyway.
// Thus we don't need to check for zero here.
if (has_thick_frame(fPaint)) {
fPaint.setStrokeWidth(sk_ieee_float_divide(fPaint.getStrokeWidth(), fScale));
}
} else {
fScale = SK_Scalar1;
}
if (!applyStrokeAndPathEffects) {
fPaint.setStyle(SkPaint::kFill_Style);
fPaint.setPathEffect(nullptr);
}
// SRGBTODO: Is this correct?
fCache = SkStrikeCache::FindOrCreateStrikeExclusive(
fPaint, nullptr,
SkScalerContextFlags::kFakeGammaAndBoostContrast, nullptr);
SkPaint::Style style = SkPaint::kFill_Style;
sk_sp<SkPathEffect> pe;
if (!applyStrokeAndPathEffects) {
style = paint.getStyle(); // restore
pe = paint.refPathEffect(); // restore
}
fPaint.setStyle(style);
fPaint.setPathEffect(pe);
fPaint.setMaskFilter(paint.refMaskFilter()); // restore
// now compute fXOffset if needed
SkScalar xOffset = 0;
fXPos = xOffset;
fPrevAdvance = 0;
fText = text;
fStop = text + length;
}
bool SkTextToPathIter::next(const SkPath** path, SkScalar* xpos) {
if (fText < fStop) {
const SkGlyph& glyph = fGlyphCacheProc(fCache.get(), &fText, fStop);
fXPos += fPrevAdvance * fScale;
fPrevAdvance = advance(glyph); // + fPaint.getTextTracking();
if (glyph.fWidth) {
if (path) {
*path = fCache->findPath(glyph);
}
} else {
if (path) {
*path = nullptr;
}
}
if (xpos) {
*xpos = fXPos;
}
return true;
}
return false;
}
bool SkTextInterceptsIter::next(SkScalar* array, int* count) {
const SkGlyph& glyph = fGlyphCacheProc(fCache.get(), &fText, fStop);
fXPos += fPrevAdvance * fScale;
fPrevAdvance = advance(glyph); // + fPaint.getTextTracking();
if (fCache->findPath(glyph)) {
fCache->findIntercepts(fBounds, fScale, fXPos, false,
const_cast<SkGlyph*>(&glyph), array, count);
}
return fText < fStop;
}
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
31bed17b22112cd3fffd4a3cbb13fa920f66f1c7 | c675cf015aa2c13d084718fc7e36623f38353836 | /enveomics/sequence.cpp | 9c76f070101458bc827dea035a5293b396b1471a | [
"Artistic-2.0"
] | permissive | ikauser7/nonpareil | 16bc5c7f86d92f70a21c3b24337c2862592d5aef | fb0cdaad38b8fb5e021c50710d261555ac76ede1 | refs/heads/master | 2021-01-17T21:45:22.701564 | 2013-03-31T22:14:15 | 2013-03-31T22:14:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,188 | cpp | // enveomics/sequence.h - Library for sequences on enve-omics software
// @author Luis M. Rodriguez-R <lmrodriguezr at gmail dot com>
// @license artistic 2.0
// @version 1.0
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <string>
#include <bitset>
#include <stdio.h>
#include "universal.h"
#include "sequence.h"
using namespace std;
size_t count_seqs(char *file, const char *format, int &largest_line){
// Vars
ifstream fileh;
unsigned int N=0;
int maxlen=0;
char start;
// Format
if(strcmp(format, "fasta")==0) {start = '>';}
else if(strcmp(format, "fastq")==0) {start = '@';}
else if(strcmp(format, "enveomics-seq")==0){start = '>';}
else {error("Unsupported format", format);}
// Count
fileh.open(file, ios::in);
if(!fileh.is_open()) error("Impossible to open the file", file);
while(fileh.good()){
string line;
getline(fileh, line);
if(line.length() > maxlen) maxlen = line.length();
if(line[0]==start) N++;
if(N==UINT_MAX-1) error("Unable to represent the number of reads, limit reached", UINT_MAX-1);
}
fileh.close();
largest_line = maxlen;
return N;
}
size_t count_seqs(char *file, const char *format){
int dummy;
return count_seqs(file, format, dummy);
}
size_t count_seqs(char *file, int &largest_line){
return count_seqs(file, "fasta", largest_line);
}
size_t count_seqs(char *file){
int dummy;
return count_seqs(file, dummy);
}
size_t build_index(char *sourceFile, char* format, char *&namFileOut, char *&seqFileOut, int &largest_seq){
// Vars
unsigned int N=0;
int maxlen=0;
char start, end, *namFile, *seqFile;
bool inSeq=false;
string seq, name;
ifstream infileh, testseq, testnam;
ofstream seqfileh, namfileh;
// Format
if(strcmp(format, "fasta")==0) {start = '>'; end='\n';}
else if(strcmp(format, "fastq")==0) {start = '@'; end='+';}
else {error("Unsupported format", format);}
// Files
seqFile = new char[strlen(sourceFile)+10];
sprintf(seqFile, "%s.enve-seq", sourceFile);
namFile = new char[strlen(sourceFile)+10];
sprintf(namFile, "%s.enve-nam", sourceFile);
namFileOut = namFile;
seqFileOut = seqFile;
// Check if I need to do it
testseq.open(seqFile, ios::in);
if(testseq.is_open()){
testseq.close();
testnam.open(namFile, ios::in);
if(testnam.is_open()){
testnam.close();
N = count_seqs(seqFile, "enveomics-seq", largest_seq);
return N;
}
}
// Open file streams
infileh.open(sourceFile, ios::in);
if(!infileh.is_open()) error("Cannot open the file", sourceFile);
seqfileh.open(seqFile, ios::out);
if(!seqfileh.is_open()) error("Cannot open the file", seqFile);
namfileh.open(namFile, ios::out);
if(!namfileh.is_open()) error("Cannot open the file", namFile);
// Run
while(!infileh.eof()){
string line;
getline(infileh, line);
if(line[0]==start){
if(seq.length()>0){
namfileh << ">" << ++N << endl << name << endl;
seqfileh << ">" << N << endl << seq << endl;
if(seq.length() > maxlen) maxlen = seq.length();
if(N==UINT_MAX-1) error("Impossible to represent the number of reads while indexing, limit reached", UINT_MAX-1);
}
name = line.substr(1);
seq = (string)"";
inSeq = true;
}else if(line[0]==end) inSeq = false;
else if(inSeq) seq.append(line);
}
if(seq.length()>0){
namfileh << ">" << ++N << endl << name << endl;
seqfileh << ">" << N << endl << seq << endl;
if(seq.length() > maxlen) maxlen = seq.length();
}
// Close file streams
infileh.close();
seqfileh.close();
namfileh.close();
largest_seq = maxlen;
return N;
}
size_t build_index(char *sourceFile, char* format, char *&namFileOut, char *&seqFileOut){
int dummy;
return build_index(sourceFile, format, namFileOut, seqFileOut, dummy);
}
size_t sub_sample_seqs(char *sourceFile, char *destFile, double portion, char *format){
ifstream filein;
ofstream fileout;
char start;
size_t n=0;
string entry;
if(strcmp(format, "fasta")==0) {start = '>';}
else if(strcmp(format, "enveomics-seq")==0) {start = '>';}
else if(strcmp(format, "fastq")==0) {start = '@';}
else {error("Unsupported format", format);}
filein.open(sourceFile, ios::in);
if(!filein.is_open()) error("Impossible to open the input file", sourceFile);
fileout.open(destFile, ios::out);
if(!fileout.is_open()) error("Impossible to open the output file", destFile);
while(filein.good()){
string line;
getline(filein, line);
if(line[0]==start | !filein.good()){
if((entry.size()>0) && (portion>=1 || ((double)rand()/RAND_MAX <= portion))){
n++;
fileout << entry;
}
entry = (string)"";
}
entry.append(line);
entry.append((char *)"\n");
}
fileout.close();
filein.close();
return n;
}
size_t sub_sample_seqs(char *sourceFile, char *destFile, double portion){
return sub_sample_seqs(sourceFile, destFile, portion, (char *)"fasta");
}
int get_seqs(char **&seqs, char *file, int from, int number, int largest_seq, char *format){
// Vars
ifstream filein;
char start;
int n=0, i=0;
string entry;
// Init
if(strcmp(format, "fasta")==0) {start = '>';}
else if(strcmp(format, "enveomics-seq")==0) {start = '>';}
else {error("Unsupported format", format);}
// Open file
filein.open(file, ios::in);
if(!filein.is_open()) error("Impossible to open the input file", file);
// Memory allocation
seqs = new char*[number];
if(!seqs) error("Impossible to allocate memory for that many sequences", number);
for(unsigned int a=0; a<number; a++){
seqs[a] = new char[largest_seq+1];
if(!seqs[a]) error("Impossible to allocate memory for another sequence", a);
}
// Read the file
while(filein.good()){
string line;
getline(filein, line);
if(line[0]==start | !filein.good()){
if(entry.size()>0){
i++;
if(i>=from){
if(entry.length() > largest_seq) error("Found a sequences largest than expected", (int)entry.length());
for(int a=0; a<=entry.length(); a++) seqs[n][a] = entry[a];
n++;
if(n >= number) break;
}
}
entry = (string)"";
}else{
entry.append(line);
//entry.append((char *)"\n");
}
}
// Finalize
filein.close();
return n;
}
int get_seqs(char **&seqs, char *file, int from, int number, int largest_seq){
return get_seqs(seqs, file, from, number, largest_seq, (char *)"fasta");
}
int reverse_complement(char *&out, char *in){
int len = strlen(in);
for(int i=len; i>0; i--)
out[len-i] = in[i]=='A'?'T':
in[i]=='C'?'G':
in[i]=='G'?'C':
in[i]=='T'?'A':
'N';
out[len]=(char)NULL;
return len;
}
#ifdef ENVEOMICS_NUC_T
// The bitset representation of nucleotides (in 2 bits)
nuc_t ctonuc(char c){
nuc_t nuc;
nuc.set(); // 11
if(c=='A') return (~nuc); // 00
if(c=='C') return (nuc>>1); // 01
if(c=='G') return (nuc<<1); // 10
if(c=='T') return nuc; // 11
char letter[] = {c, (char)NULL};
error("Impossible to interpret char as nucleotide", letter);
}
char nuctoc(nuc_t nuc){
char c;
nuc_t nucA = ctonuc('A');
if(nuc==nucA) return 'A';
if(nuc==(nucA>>1)) return 'C';
if(nuc==(nucA<<1)) return 'G';
return 'T';
}
int atonucseq(nucseq_t &nucseq, char *charseq){
int len = strlen(charseq);
for(size_t a=0; a<len; a++) nucseq.seq[a] = ctonuc(charseq[a]);
nucseq.len=len;
return nucseq.len;
}
int nucseqtoa(char *&charseq, nucseq_t nucseq){
for(size_t a=0; a<nucseq.len; a++) charseq[a] = nuctoc(nucseq.seq[a]);
charseq[nucseq.len] = (char)NULL;
return nucseq.len;
}
int reverse_complement(nucseq_t &out, nucseq_t in){
for(size_t i=in.len; i>0; i--) out.seq[in.len-i] = (~in.seq[i]);
out.len = in.len;
return in.len;
}
int seqtoa(char *&charseq, nucseq_t nucseq){
for(size_t i=0; i<nucseq.len; i++) charseq[i] = nuctoc(nucseq.seq[i]);
charseq[nucseq.len] = (char)NULL;
}
#endif
| [
"lmrodriguezr@gmail.com"
] | lmrodriguezr@gmail.com |
9d17b50458c1dfaf02378406bd08e233a1bb3914 | 90393990f256a5ae83c8d3a6b431170e68d8b3bf | /sponza/camera.h | 98dd4f39cbbde081000cb0aa05a34dc11f91b0d0 | [] | no_license | zzb66666666x/LearnOpenGL | 6b83773e0fd21c9001c8b42d0f0200b87abf13ee | cb4a133b67a005706a9c9361691b11b3f0ef188a | refs/heads/master | 2023-06-28T11:34:47.695774 | 2021-08-03T12:34:22 | 2021-08-03T12:34:22 | 371,774,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,359 | h | #ifndef CAMERA_H
#define CAMERA_H
#include "glad.h"
#include "configs.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum Camera_Movement {
FORWARD,
BACKWARD,
LEFT,
RIGHT
};
// Default camera values
const float YAW = -90.0f;
const float PITCH = 0.0f;
const float SPEED = 300.0f;
const float SENSITIVITY = 0.1f;
const float ZOOM = 45.0f;
// An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
class Camera
{
public:
// camera Attributes
glm::vec3 Position;
glm::vec3 Front;
glm::vec3 Up;
glm::vec3 Right;
glm::vec3 WorldUp;
// euler Angles
float Yaw;
float Pitch;
// camera options
float MovementSpeed;
float MouseSensitivity;
float Zoom;
// constructor with vectors
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = position;
WorldUp = up;
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// constructor with scalar values
Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
{
Position = glm::vec3(posX, posY, posZ);
WorldUp = glm::vec3(upX, upY, upZ);
Yaw = yaw;
Pitch = pitch;
updateCameraVectors();
}
// returns the view matrix calculated using Euler Angles and the LookAt Matrix
glm::mat4 GetViewMatrix()
{
return glm::lookAt(Position, Position + Front, Up);
}
// processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void ProcessKeyboard(Camera_Movement direction, float deltaTime)
{
float velocity = MovementSpeed * deltaTime;
if (direction == FORWARD)
Position += Front * velocity;
if (direction == BACKWARD)
Position -= Front * velocity;
if (direction == LEFT)
Position -= Right * velocity;
if (direction == RIGHT)
Position += Right * velocity;
}
// processes input received from a mouse input system. Expects the offset value in both the x and y direction.
void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
{
xoffset *= MouseSensitivity;
yoffset *= MouseSensitivity;
Yaw += xoffset;
Pitch += yoffset;
// make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
}
// update Front, Right and Up Vectors using the updated Euler angles
updateCameraVectors();
}
// processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
void ProcessMouseScroll(float yoffset)
{
Zoom -= (float)yoffset;
if (Zoom < 1.0f)
Zoom = 1.0f;
if (Zoom > 45.0f)
Zoom = 45.0f;
}
private:
// calculates the front vector from the Camera's (updated) Euler Angles
void updateCameraVectors()
{
// calculate the new Front vector
glm::vec3 front;
front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
front.y = sin(glm::radians(Pitch));
front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
Front = glm::normalize(front);
// also re-calculate the Right and Up vector
Right = glm::normalize(glm::cross(Front, WorldUp)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
Up = glm::normalize(glm::cross(Right, Front));
}
};
#endif | [
"18767066589@163.com"
] | 18767066589@163.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.