hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08dd368c4376ab775200bc641d4145ba289bd5c4 | 38,803 | cpp | C++ | src_main/engine/networkstringtable.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 25 | 2018-02-28T15:04:42.000Z | 2021-08-16T03:49:00.000Z | src_main/engine/networkstringtable.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 1 | 2019-09-20T11:06:03.000Z | 2019-09-20T11:06:03.000Z | src_main/engine/networkstringtable.cpp | ArcadiusGFN/SourceEngine2007 | 51cd6d4f0f9ed901cb9b61456eb621a50ce44f55 | [
"bzip2-1.0.6"
] | 9 | 2019-07-31T11:58:20.000Z | 2021-08-31T11:18:15.000Z | // Copyright © 1996-2018, Valve Corporation, All rights reserved.
#include "networkstringtable.h"
#include "baseclient.h"
#include "filesystem_engine.h"
#include "host.h"
#include "net.h"
#include "netmessages.h"
#include "sysexternal.h"
#include "tier0/include/vprof.h"
#include "tier1/bitbuf.h"
#include "tier1/utlbuffer.h"
#include "tier0/include/memdbgon.h"
#define SUBSTRING_BITS 5
struct StringHistoryEntry {
char string[(1 << SUBSTRING_BITS)];
};
static int CountSimilarCharacters(char const *str1, char const *str2) {
int c = 0;
while (*str1 && *str2 && *str1 == *str2 && c < ((1 << SUBSTRING_BITS) - 1)) {
str1++;
str2++;
c++;
}
return c;
}
static int GetBestPreviousString(CUtlVector<StringHistoryEntry> &history,
char const *newstring, int &substringsize) {
int bestindex = -1;
int bestcount = 0;
int c = history.Count();
for (int i = 0; i < c; i++) {
char const *prev = history[i].string;
int similar = CountSimilarCharacters(prev, newstring);
if (similar < 3) continue;
if (similar > bestcount) {
bestcount = similar;
bestindex = i;
}
}
substringsize = bestcount;
return bestindex;
}
bool CNetworkStringTable_LessFunc(FileNameHandle_t const &a,
FileNameHandle_t const &b) {
return a < b;
}
//-----------------------------------------------------------------------------
// Implementation when dictionary strings are filenames
//-----------------------------------------------------------------------------
class CNetworkStringFilenameDict : public INetworkStringDict {
public:
CNetworkStringFilenameDict() {
m_Items.SetLessFunc(CNetworkStringTable_LessFunc);
}
virtual ~CNetworkStringFilenameDict() { Purge(); }
unsigned int Count() { return m_Items.Count(); }
void Purge() { m_Items.RemoveAll(); }
const char *String(int index) {
char szString[SOURCE_MAX_PATH];
g_pFileSystem->String(m_Items.Key(index), szString, sizeof(szString));
return va("%s", szString);
}
bool IsValidIndex(int index) { return m_Items.IsValidIndex(index); }
int Insert(const char *pString) {
FileNameHandle_t fnHandle = g_pFileSystem->FindOrAddFileName(pString);
return m_Items.Insert(fnHandle);
}
int Find(const char *pString) {
FileNameHandle_t fnHandle = g_pFileSystem->FindFileName(pString);
if (!fnHandle) return m_Items.InvalidIndex();
return m_Items.Find(fnHandle);
}
CNetworkStringTableItem &Element(int index) { return m_Items.Element(index); }
const CNetworkStringTableItem &Element(int index) const {
return m_Items.Element(index);
}
private:
CUtlMap<FileNameHandle_t, CNetworkStringTableItem> m_Items;
};
//-----------------------------------------------------------------------------
// Implementation for general purpose strings
//-----------------------------------------------------------------------------
class CNetworkStringDict : public INetworkStringDict {
public:
CNetworkStringDict() {}
virtual ~CNetworkStringDict() { Purge(); }
unsigned int Count() { return m_Items.Count(); }
void Purge() { m_Items.Purge(); }
const char *String(int index) { return m_Items.GetElementName(index); }
bool IsValidIndex(int index) { return m_Items.IsValidIndex(index); }
int Insert(const char *pString) { return m_Items.Insert(pString); }
int Find(const char *pString) { return m_Items.Find(pString); }
CNetworkStringTableItem &Element(int index) { return m_Items.Element(index); }
const CNetworkStringTableItem &Element(int index) const {
return m_Items.Element(index);
}
private:
CUtlDict<CNetworkStringTableItem, int> m_Items;
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : id -
// *tableName -
// maxentries -
//-----------------------------------------------------------------------------
CNetworkStringTable::CNetworkStringTable(TABLEID id, const char *tableName,
int maxentries, int userdatafixedsize,
int userdatanetworkbits,
bool bIsFilenames)
: m_bAllowClientSideAddString(false), m_pItemsClientSide(NULL) {
m_id = id;
int len = strlen(tableName) + 1;
m_pszTableName = new char[len];
assert(m_pszTableName);
assert(tableName);
Q_strncpy(m_pszTableName, tableName, len);
m_changeFunc = NULL;
m_pObject = NULL;
m_nTickCount = 0;
m_pMirrorTable = NULL;
m_nLastChangedTick = 0;
m_bChangeHistoryEnabled = false;
m_bLocked = false;
m_nMaxEntries = maxentries;
m_nEntryBits = Q_log2(m_nMaxEntries);
m_bUserDataFixedSize = userdatafixedsize != 0;
m_nUserDataSize = userdatafixedsize;
m_nUserDataSizeBits = userdatanetworkbits;
if (m_nUserDataSizeBits > CNetworkStringTableItem::MAX_USERDATA_BITS) {
Host_Error(
"String tables user data bits restricted to %i bits, requested %i is "
"too large\n",
CNetworkStringTableItem::MAX_USERDATA_BITS, m_nUserDataSizeBits);
}
if (m_nUserDataSize > CNetworkStringTableItem::MAX_USERDATA_SIZE) {
Host_Error(
"String tables user data size restricted to %i bytes, requested %i is "
"too large\n",
CNetworkStringTableItem::MAX_USERDATA_SIZE, m_nUserDataSize);
}
// Make sure maxentries is power of 2
if ((1 << m_nEntryBits) != maxentries) {
Host_Error(
"String tables must be powers of two in size!, %i is not a power of "
"2\n",
maxentries);
}
if (bIsFilenames) {
m_bIsFilenames = true;
m_pItems = new CNetworkStringFilenameDict;
} else {
m_bIsFilenames = false;
m_pItems = new CNetworkStringDict;
}
}
void CNetworkStringTable::SetAllowClientSideAddString(bool state) {
if (state == m_bAllowClientSideAddString) return;
m_bAllowClientSideAddString = state;
if (m_pItemsClientSide) {
delete m_pItemsClientSide;
m_pItemsClientSide = NULL;
}
if (m_bAllowClientSideAddString) {
m_pItemsClientSide = new CNetworkStringDict;
m_pItemsClientSide->Insert(
"___clientsideitemsplaceholder0___"); // 0 slot can't be used
m_pItemsClientSide->Insert(
"___clientsideitemsplaceholder1___"); // -1 can't be used since it
// looks like the "invalid" index
// from other string lookups
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNetworkStringTable::IsUserDataFixedSize() const {
return m_bUserDataFixedSize;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNetworkStringTable::HasFileNameStrings() const { return m_bIsFilenames; }
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNetworkStringTable::GetUserDataSize() const { return m_nUserDataSize; }
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CNetworkStringTable::GetUserDataSizeBits() const {
return m_nUserDataSizeBits;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CNetworkStringTable::~CNetworkStringTable() {
delete[] m_pszTableName;
delete m_pItems;
delete m_pItemsClientSide;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTable::DeleteAllStrings() {
m_pItems->Purge();
if (m_pItemsClientSide) {
m_pItemsClientSide->Purge();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : i -
// Output : CNetworkStringTableItem
//-----------------------------------------------------------------------------
CNetworkStringTableItem *CNetworkStringTable::GetItem(int i) {
if (i >= 0) {
return &m_pItems->Element(i);
}
Assert(m_pItemsClientSide);
return &m_pItemsClientSide->Element(-i);
}
//-----------------------------------------------------------------------------
// Purpose: Returns the table identifier
// Output : TABLEID
//-----------------------------------------------------------------------------
TABLEID CNetworkStringTable::GetTableId() const { return m_id; }
//-----------------------------------------------------------------------------
// Purpose: Returns the max size of the table
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::GetMaxStrings() const { return m_nMaxEntries; }
//-----------------------------------------------------------------------------
// Purpose: Returns a table, by name
// Output : const char
//-----------------------------------------------------------------------------
const char *CNetworkStringTable::GetTableName() const {
return m_pszTableName;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the number of bits needed to encode an entry index
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::GetEntryBits() const { return m_nEntryBits; }
void CNetworkStringTable::SetTick(int tick_count) {
Assert(tick_count >= m_nTickCount);
m_nTickCount = tick_count;
}
void CNetworkStringTable::Lock(bool bLock) { m_bLocked = bLock; }
pfnStringChanged CNetworkStringTable::GetCallback() { return m_changeFunc; }
#ifndef SHARED_NET_STRING_TABLES
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTable::EnableRollback() {
// stringtable must be empty
Assert(m_pItems->Count() == 0);
m_bChangeHistoryEnabled = true;
}
void CNetworkStringTable::SetMirrorTable(INetworkStringTable *table) {
m_pMirrorTable = table;
}
void CNetworkStringTable::RestoreTick(int tick) {
// TODO optimize this, most of the time the tables doens't really change
m_nLastChangedTick = 0;
int count = m_pItems->Count();
for (int i = 0; i < count; i++) {
// restore tick in all entries
int tickChanged = m_pItems->Element(i).RestoreTick(tick);
if (tickChanged > m_nLastChangedTick) m_nLastChangedTick = tickChanged;
}
}
//-----------------------------------------------------------------------------
// Purpose: updates the mirror table, if set one
// Output : return true if some entries were updates
//-----------------------------------------------------------------------------
void CNetworkStringTable::UpdateMirrorTable(int tick_ack) {
if (!m_pMirrorTable) return;
m_pMirrorTable->SetTick(m_nTickCount); // use same tick
int count = m_pItems->Count();
for (int i = 0; i < count; i++) {
CNetworkStringTableItem *p = &m_pItems->Element(i);
// mirror is up to date
if (p->GetTickChanged() <= tick_ack) continue;
const void *pUserData = p->GetUserData();
int nBytes = p->GetUserDataLength();
if (!nBytes || !pUserData) {
nBytes = 0;
pUserData = NULL;
}
// Check if we are updating an old entry or adding a new one
if (i < m_pMirrorTable->GetNumStrings()) {
m_pMirrorTable->SetStringUserData(i, nBytes, pUserData);
} else {
// Grow the table (entryindex must be the next empty slot)
Assert(i == m_pMirrorTable->GetNumStrings());
char const *pName = m_pItems->String(i);
m_pMirrorTable->AddString(true, pName, nBytes, pUserData);
}
}
}
int CNetworkStringTable::WriteUpdate(CBaseClient *client, bf_write &buf,
int tick_ack) {
CUtlVector<StringHistoryEntry> history;
int entriesUpdated = 0;
int lastEntry = -1;
int count = m_pItems->Count();
for (int i = 0; i < count; i++) {
CNetworkStringTableItem *p = &m_pItems->Element(i);
// Client is up to date
if (p->GetTickChanged() <= tick_ack) continue;
int nStartBit = buf.GetNumBitsWritten();
// Write Entry index
if ((lastEntry + 1) == i) {
buf.WriteOneBit(1);
} else {
buf.WriteOneBit(0);
buf.WriteUBitLong(i, m_nEntryBits);
}
// check if string can use older string as base eg "models/weapons/gun1" &
// "models/weapons/gun2"
char const *pEntry = m_pItems->String(i);
if (p->GetTickCreated() > tick_ack) {
// this item has just been created, send string itself
buf.WriteOneBit(1);
int substringsize = 0;
int bestprevious = GetBestPreviousString(history, pEntry, substringsize);
if (bestprevious != -1) {
buf.WriteOneBit(1);
buf.WriteUBitLong(bestprevious,
5); // history never has more than 32 entries
buf.WriteUBitLong(substringsize, SUBSTRING_BITS);
buf.WriteString(pEntry + substringsize);
} else {
buf.WriteOneBit(0);
buf.WriteString(pEntry);
}
} else {
buf.WriteOneBit(0);
}
// Write the item's user data.
int len;
const void *pUserData = GetStringUserData(i, &len);
if (pUserData && len > 0) {
buf.WriteOneBit(1);
if (IsUserDataFixedSize()) {
// Don't have to send length, it was sent as part of the table
// definition
buf.WriteBits(pUserData, GetUserDataSizeBits());
} else {
buf.WriteUBitLong(len, CNetworkStringTableItem::MAX_USERDATA_BITS);
buf.WriteBits(pUserData, len * 8);
}
} else {
buf.WriteOneBit(0);
}
// limit string history to 32 entries
if (history.Count() > 31) {
history.Remove(0);
}
// add string to string history
StringHistoryEntry she;
Q_strncpy(she.string, pEntry, sizeof(she.string));
history.AddToTail(she);
entriesUpdated++;
lastEntry = i;
if (client && client->IsTracing()) {
int nBits = buf.GetNumBitsWritten() - nStartBit;
client->TraceNetworkMsg(nBits, " [%s] %d:%s ", GetTableName(), i,
GetString(i));
}
}
return entriesUpdated;
}
//-----------------------------------------------------------------------------
// Purpose: Parse string update
//-----------------------------------------------------------------------------
void CNetworkStringTable::ParseUpdate(bf_read &buf, int entries) {
int lastEntry = -1;
CUtlVector<StringHistoryEntry> history;
for (int i = 0; i < entries; i++) {
int entryIndex = lastEntry + 1;
if (!buf.ReadOneBit()) {
entryIndex = buf.ReadUBitLong(GetEntryBits());
}
lastEntry = entryIndex;
if (entryIndex < 0 || entryIndex >= GetMaxStrings()) {
Host_Error("Server sent bogus string index %i for table %s\n", entryIndex,
GetTableName());
}
const char *pEntry = NULL;
char entry[1024];
char substr[1024];
if (buf.ReadOneBit()) {
bool substringcheck = buf.ReadOneBit() ? true : false;
if (substringcheck) {
int index = buf.ReadUBitLong(5);
int bytestocopy = buf.ReadUBitLong(SUBSTRING_BITS);
Q_strncpy(entry, history[index].string, bytestocopy + 1);
buf.ReadString(substr, sizeof(substr));
Q_strncat(entry, substr, sizeof(entry), COPY_ALL_CHARACTERS);
} else {
buf.ReadString(entry, sizeof(entry));
}
pEntry = entry;
}
// Read in the user data.
unsigned char tempbuf[CNetworkStringTableItem::MAX_USERDATA_SIZE];
memset(tempbuf, 0, sizeof(tempbuf));
const void *pUserData = NULL;
int nBytes = 0;
if (buf.ReadOneBit()) {
if (IsUserDataFixedSize()) {
// Don't need to read length, it's fixed length and the length was
// networked down already.
nBytes = GetUserDataSize();
Assert(nBytes > 0);
tempbuf[nBytes - 1] = 0; // be safe, clear last byte
buf.ReadBits(tempbuf, GetUserDataSizeBits());
} else {
nBytes = buf.ReadUBitLong(CNetworkStringTableItem::MAX_USERDATA_BITS);
ErrorIfNot(nBytes <= sizeof(tempbuf),
("CNetworkStringTableClient::ParseUpdate: message too large "
"(%d bytes).",
nBytes));
buf.ReadBytes(tempbuf, nBytes);
}
pUserData = tempbuf;
}
// Check if we are updating an old entry or adding a new one
if (entryIndex < GetNumStrings()) {
SetStringUserData(entryIndex, nBytes, pUserData);
#ifdef _DEBUG
if (pEntry) {
Assert(!Q_strcmp(
pEntry, GetString(entryIndex))); // make sure string didn't change
}
#endif
pEntry = GetString(entryIndex); // string didn't change
} else {
// Grow the table (entryindex must be the next empty slot)
Assert((entryIndex == GetNumStrings()) && (pEntry != NULL));
if (pEntry == NULL) {
Msg("CNetworkStringTable::ParseUpdate: NULL pEntry, table %s, index "
"%i\n",
GetTableName(), entryIndex);
pEntry = ""; // avoid crash because of NULL strings
}
AddString(true, pEntry, nBytes, pUserData);
}
if (history.Count() > 31) {
history.Remove(0);
}
StringHistoryEntry she;
Q_strncpy(she.string, pEntry, sizeof(she.string));
history.AddToTail(she);
}
}
void CNetworkStringTable::CopyStringTable(CNetworkStringTable *table) {
Assert(m_pItems->Count() == 0); // table must be empty before coping
for (unsigned int i = 0; i < table->m_pItems->Count(); i++) {
CNetworkStringTableItem *item = &table->m_pItems->Element(i);
m_nTickCount = item->m_nTickChanged;
AddString(true, table->GetString(i), item->m_nUserDataLength,
item->m_pUserData);
}
}
#endif
void CNetworkStringTable::TriggerCallbacks(int tick_ack) {
if (m_changeFunc == NULL) return;
Plat_TimestampedLog(
"CNetworkStringTable::TriggerCallbacks: Change (%s) start.",
GetTableName());
int count = m_pItems->Count();
for (int i = 0; i < count; i++) {
CNetworkStringTableItem *pItem = &m_pItems->Element(i);
// mirror is up to date
if (pItem->GetTickChanged() <= tick_ack) continue;
int userDataSize;
const void *pUserData = pItem->GetUserData(&userDataSize);
// fire the callback function
(*m_changeFunc)(m_pObject, this, i, GetString(i), pUserData);
}
Plat_TimestampedLog("CNetworkStringTable::TriggerCallbacks: Change (%s) end.",
GetTableName());
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : changeFunc -
//-----------------------------------------------------------------------------
void CNetworkStringTable::SetStringChangedCallback(
void *object, pfnStringChanged changeFunc) {
m_changeFunc = changeFunc;
m_pObject = object;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *client -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNetworkStringTable::ChangedSinceTick(int tick) const {
return (m_nLastChangedTick > tick);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *value -
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::AddString(bool bIsServer, const char *string,
int length /*= -1*/,
const void *userdata /*= NULL*/) {
bool bHasChanged;
CNetworkStringTableItem *item;
if (!string) {
Assert(string);
ConMsg("Warning: Can't add NULL string to table %s\n", GetTableName());
return INVALID_STRING_INDEX;
}
#ifdef _DEBUG
if (m_bLocked) {
DevMsg(
"Warning! CNetworkStringTable::AddString: adding '%s' while locked.\n",
string);
}
#endif
int i = m_pItems->Find(string);
if (!bIsServer) {
if (m_pItems->IsValidIndex(i) && !m_pItemsClientSide) {
bIsServer = true;
}
}
if (!bIsServer && m_pItemsClientSide) {
i = m_pItemsClientSide->Find(string);
if (!m_pItemsClientSide->IsValidIndex(i)) {
// not in list yet, create it now
if (m_pItemsClientSide->Count() >= (unsigned int)GetMaxStrings()) {
// Too many strings, TODO(d.rattman): Print warning message
ConMsg("Warning: Table %s is full, can't add %s\n", GetTableName(),
string);
return INVALID_STRING_INDEX;
}
// create new item
{
MEM_ALLOC_CREDIT();
i = m_pItemsClientSide->Insert(string);
}
item = &m_pItemsClientSide->Element(i);
// set changed ticks
item->m_nTickChanged = m_nTickCount;
#ifndef SHARED_NET_STRING_TABLES
item->m_nTickCreated = m_nTickCount;
if (m_bChangeHistoryEnabled) {
item->EnableChangeHistory();
}
#endif
bHasChanged = true;
} else {
item = &m_pItemsClientSide->Element(i); // item already exists
bHasChanged = false; // not changed yet
}
if (length > -1) {
if (item->SetUserData(m_nTickCount, length, userdata)) {
bHasChanged = true;
}
}
if (bHasChanged && !m_bChangeHistoryEnabled) {
DataChanged(-i, item);
}
// Negate i for returning to client
i = -i;
} else {
// See if it's already there
i = m_pItems->Find(string);
if (!m_pItems->IsValidIndex(i)) {
// not in list yet, create it now
if (m_pItems->Count() >= (unsigned int)GetMaxStrings()) {
// Too many strings, TODO(d.rattman): Print warning message
ConMsg("Warning: Table %s is full, can't add %s\n", GetTableName(),
string);
return INVALID_STRING_INDEX;
}
// create new item
{
MEM_ALLOC_CREDIT();
i = m_pItems->Insert(string);
}
item = &m_pItems->Element(i);
// set changed ticks
item->m_nTickChanged = m_nTickCount;
#ifndef SHARED_NET_STRING_TABLES
item->m_nTickCreated = m_nTickCount;
if (m_bChangeHistoryEnabled) {
item->EnableChangeHistory();
}
#endif
bHasChanged = true;
} else {
item = &m_pItems->Element(i); // item already exists
bHasChanged = false; // not changed yet
}
if (length > -1) {
if (item->SetUserData(m_nTickCount, length, userdata)) {
bHasChanged = true;
}
}
if (bHasChanged && !m_bChangeHistoryEnabled) {
DataChanged(i, item);
}
}
return i;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : stringNumber -
// Output : const char
//-----------------------------------------------------------------------------
const char *CNetworkStringTable::GetString(int stringNumber) {
INetworkStringDict *dict = m_pItems;
if (m_pItemsClientSide && stringNumber < -1) {
dict = m_pItemsClientSide;
stringNumber = -stringNumber;
}
Assert(stringNumber >= 0 && stringNumber < (int)dict->Count());
if (stringNumber >= 0 && stringNumber < (int)dict->Count()) {
return dict->String(stringNumber);
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : stringNumber -
// length -
// *userdata -
//-----------------------------------------------------------------------------
void CNetworkStringTable::SetStringUserData(int stringNumber, int length /*=0*/,
const void *userdata /*= 0*/) {
#ifdef _DEBUG
if (m_bLocked) {
DevMsg(
"Warning! CNetworkStringTable::SetStringUserData: changing entry %i "
"while locked.\n",
stringNumber);
}
#endif
INetworkStringDict *dict = m_pItems;
int saveStringNumber = stringNumber;
if (m_pItemsClientSide && stringNumber < -1) {
dict = m_pItemsClientSide;
stringNumber = -stringNumber;
}
assert((length == 0 && userdata == NULL) || (length > 0 && userdata != NULL));
assert(stringNumber >= 0 && stringNumber < (int)dict->Count());
CNetworkStringTableItem *p = &dict->Element(stringNumber);
assert(p);
if (p->SetUserData(m_nTickCount, length, userdata)) {
// Mark changed
DataChanged(saveStringNumber, p);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *item -
//-----------------------------------------------------------------------------
void CNetworkStringTable::DataChanged(int stringNumber,
CNetworkStringTableItem *item) {
Assert(item);
if (!item) return;
// Mark table as changed
m_nLastChangedTick = m_nTickCount;
// Invoke callback if one was installed
#ifndef SHARED_NET_STRING_TABLES // but not if client & server share the same
// containers, we trigger that later
if (m_changeFunc != NULL) {
int userDataSize;
const void *pUserData = item->GetUserData(&userDataSize);
(*m_changeFunc)(m_pObject, this, stringNumber, GetString(stringNumber),
pUserData);
}
#endif
}
#ifndef SHARED_NET_STRING_TABLES
void CNetworkStringTable::WriteStringTable(CUtlBuffer &buf) {
int numstrings = GetNumStrings();
buf.PutInt(numstrings);
for (int i = 0; i < numstrings; i++) {
buf.PutString(GetString(i));
int userDataSize;
const void *pUserData = GetStringUserData(i, &userDataSize);
if (userDataSize > 0) {
buf.PutChar(1);
buf.PutShort((short)userDataSize);
buf.Put(pUserData, userDataSize);
} else {
buf.PutChar(0);
}
}
}
bool CNetworkStringTable::ReadStringTable(CUtlBuffer &buf) {
DeleteAllStrings();
int numstrings = buf.GetInt();
for (int i = 0; i < numstrings; i++) {
char stringname[4096];
buf.GetString(stringname, sizeof(stringname));
if (buf.GetChar() == 1) {
int userDataSize = (int)buf.GetShort();
Assert(userDataSize > 0);
uint8_t *data = new byte[userDataSize + 4];
Assert(data);
buf.Get(data, userDataSize);
AddString(true, stringname, userDataSize, data);
delete[] data;
} else {
AddString(true, stringname);
}
}
return true;
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
// Input : stringNumber -
// length -
// Output : const void
//-----------------------------------------------------------------------------
const void *CNetworkStringTable::GetStringUserData(int stringNumber,
int *length) {
INetworkStringDict *dict = m_pItems;
if (m_pItemsClientSide && stringNumber < -1) {
dict = m_pItemsClientSide;
stringNumber = -stringNumber;
}
CNetworkStringTableItem *p;
assert(stringNumber >= 0 && stringNumber < (int)dict->Count());
p = &dict->Element(stringNumber);
assert(p);
return p->GetUserData(length);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::GetNumStrings() const { return m_pItems->Count(); }
//-----------------------------------------------------------------------------
// Purpose:
// Input : stringTable -
// *string -
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::FindStringIndex(char const *string) {
int i = m_pItems->Find(string);
if (m_pItems->IsValidIndex(i)) return i;
return INVALID_STRING_INDEX;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTable::Dump() {
ConMsg("Table %s\n", GetTableName());
ConMsg(" %i/%i items\n", GetNumStrings(), GetMaxStrings());
for (int i = 0; i < GetNumStrings(); i++) {
ConMsg(" %i : %s\n", i, GetString(i));
}
if (m_pItemsClientSide) {
for (int i = 0; i < (int)m_pItemsClientSide->Count(); i++) {
ConMsg(" %i : %s\n", i, m_pItemsClientSide->String(i));
}
}
ConMsg("\n");
}
#ifndef SHARED_NET_STRING_TABLES
bool CNetworkStringTable::WriteBaselines(SVC_CreateStringTable &msg,
char *msg_buffer,
int msg_buffer_size) {
msg.m_DataOut.StartWriting(msg_buffer, msg_buffer_size);
msg.m_bIsFilenames = m_bIsFilenames;
msg.m_szTableName = GetTableName();
msg.m_nMaxEntries = GetMaxStrings();
msg.m_nNumEntries = GetNumStrings();
msg.m_bUserDataFixedSize = IsUserDataFixedSize();
msg.m_nUserDataSize = GetUserDataSize();
msg.m_nUserDataSizeBits = GetUserDataSizeBits();
// tick = -1 ensures that all entries are updated = baseline
int entries = WriteUpdate(NULL, msg.m_DataOut, -1);
return entries == msg.m_nNumEntries;
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CNetworkStringTableContainer::CNetworkStringTableContainer() {
m_bAllowCreation = false;
m_bLocked = true;
m_nTickCount = 0;
m_bEnableRollback = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CNetworkStringTableContainer::~CNetworkStringTableContainer() {
RemoveAllTables();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::AllowCreation(bool state) {
m_bAllowCreation = state;
}
bool CNetworkStringTableContainer::Lock(bool bLock) {
bool oldLock = m_bLocked;
m_bLocked = bLock;
// Determine if an update is needed
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
table->Lock(bLock);
}
return oldLock;
}
void CNetworkStringTableContainer::SetAllowClientSideAddString(
INetworkStringTable *table, bool bAllowClientSideAddString) {
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *t = (CNetworkStringTable *)GetTable(i);
if (t == table) {
t->SetAllowClientSideAddString(bAllowClientSideAddString);
return;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *tableName -
// maxentries -
// Output : TABLEID
//-----------------------------------------------------------------------------
INetworkStringTable *CNetworkStringTableContainer::CreateStringTableEx(
const char *tableName, int maxentries, int userdatafixedsize /*= 0*/,
int userdatanetworkbits /*= 0*/, bool bIsFilenames /*= false */) {
if (!m_bAllowCreation) {
Sys_Error("Tried to create string table '%s' at wrong time\n", tableName);
return NULL;
}
CNetworkStringTable *pTable = (CNetworkStringTable *)FindTable(tableName);
if (pTable != NULL) {
Sys_Error("Tried to create string table '%s' twice\n", tableName);
return NULL;
}
if (m_Tables.Count() >= MAX_TABLES) {
Sys_Error("Only %i string tables allowed, can't create'%s'", MAX_TABLES,
tableName);
return NULL;
}
TABLEID id = m_Tables.Count();
pTable = new CNetworkStringTable(id, tableName, maxentries, userdatafixedsize,
userdatanetworkbits, bIsFilenames);
Assert(pTable);
#ifndef SHARED_NET_STRING_TABLES
if (m_bEnableRollback) {
pTable->EnableRollback();
}
#endif
pTable->SetTick(m_nTickCount);
m_Tables.AddToTail(pTable);
return pTable;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *tableName -
//-----------------------------------------------------------------------------
INetworkStringTable *CNetworkStringTableContainer::FindTable(
const char *tableName) const {
for (int i = 0; i < m_Tables.Count(); i++) {
if (!Q_stricmp(tableName, m_Tables[i]->GetTableName())) return m_Tables[i];
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : stringTable -
// Output : CNetworkStringTableServer
//-----------------------------------------------------------------------------
INetworkStringTable *CNetworkStringTableContainer::GetTable(
TABLEID stringTable) const {
if (stringTable < 0 || stringTable >= m_Tables.Count()) return NULL;
return m_Tables[stringTable];
}
int CNetworkStringTableContainer::GetNumTables() const {
return m_Tables.Count();
}
#ifndef SHARED_NET_STRING_TABLES
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::WriteBaselines(bf_write &buf) {
SVC_CreateStringTable msg;
char msg_buffer[NET_MAX_PAYLOAD];
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
if (!table->WriteBaselines(msg, msg_buffer, sizeof(msg_buffer))) {
Host_Error("Index error writing string table baseline %s\n",
table->GetTableName());
}
if (!msg.WriteToBuffer(buf)) {
Host_Error("Overflow error writing string table baseline %s\n",
table->GetTableName());
}
}
}
void CNetworkStringTableContainer::WriteStringTables(CUtlBuffer &buf) {
int numTables = m_Tables.Size();
buf.PutInt(numTables);
for (int i = 0; i < numTables; i++) {
CNetworkStringTable *table = m_Tables[i];
buf.PutString(table->GetTableName());
table->WriteStringTable(buf);
}
}
bool CNetworkStringTableContainer::ReadStringTables(CUtlBuffer &buf) {
int numTables = buf.GetInt();
for (int i = 0; i < numTables; i++) {
char tablename[256];
buf.GetString(tablename, sizeof(tablename));
// Find this table by name
CNetworkStringTable *table = (CNetworkStringTable *)FindTable(tablename);
Assert(table);
// Now read the data for the table
if (!table->ReadStringTable(buf)) {
Host_Error("Error reading string table %s\n", tablename);
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *cl -
// *msg -
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::WriteUpdateMessage(CBaseClient *client,
int tick_ack,
bf_write &buf) {
VPROF_BUDGET("CNetworkStringTableContainer::WriteUpdateMessage",
VPROF_BUDGETGROUP_OTHER_NETWORKING);
char buffer[NET_MAX_PAYLOAD];
// Determine if an update is needed
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
if (!table) continue;
if (!table->ChangedSinceTick(tick_ack)) continue;
SVC_UpdateStringTable msg;
msg.m_DataOut.StartWriting(buffer, NET_MAX_PAYLOAD);
msg.m_nTableID = table->GetTableId();
msg.m_nChangedEntries = table->WriteUpdate(client, msg.m_DataOut, tick_ack);
Assert(msg.m_nChangedEntries > 0); // don't send unnecessary empty updates
msg.WriteToBuffer(buf);
if (client && client->IsTracing()) {
client->TraceNetworkData(buf, "StringTable %s", table->GetTableName());
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *cl -
// *msg -
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::DirectUpdate(int tick_ack) {
VPROF_BUDGET("CNetworkStringTableContainer::DirectUpdate",
VPROF_BUDGETGROUP_OTHER_NETWORKING);
// Determine if an update is needed
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
Assert(table);
if (!table->ChangedSinceTick(tick_ack)) continue;
table->UpdateMirrorTable(tick_ack);
}
}
void CNetworkStringTableContainer::EnableRollback(bool bState) {
// we can't dis/enable rollback if we already created tabled
Assert(m_Tables.Count() == 0);
m_bEnableRollback = bState;
}
void CNetworkStringTableContainer::RestoreTick(int tick) {
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
Assert(table);
table->RestoreTick(tick);
}
}
#endif
void CNetworkStringTableContainer::TriggerCallbacks(int tick_ack) {
// Determine if an update is needed
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
Assert(table);
if (!table->ChangedSinceTick(tick_ack)) continue;
table->TriggerCallbacks(tick_ack);
}
}
void CNetworkStringTableContainer::SetTick(int tick_count) {
Assert(tick_count > 0);
m_nTickCount = tick_count;
// Determine if an update is needed
for (int i = 0; i < m_Tables.Count(); i++) {
CNetworkStringTable *table = (CNetworkStringTable *)GetTable(i);
Assert(table);
table->SetTick(tick_count);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::RemoveAllTables() {
while (m_Tables.Count() > 0) {
CNetworkStringTable *table = m_Tables[0];
m_Tables.Remove(0);
delete table;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNetworkStringTableContainer::Dump() {
for (int i = 0; i < m_Tables.Count(); i++) {
m_Tables[i]->Dump();
}
}
| 30.243959 | 80 | 0.55055 | [
"object"
] |
08e1062641d6c007c1c67064827c11cece3fbd77 | 6,414 | cc | C++ | content/browser/bluetooth/bluetooth_allowed_devices_map.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | content/browser/bluetooth/bluetooth_allowed_devices_map.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | content/browser/bluetooth/bluetooth_allowed_devices_map.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 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 "content/browser/bluetooth/bluetooth_allowed_devices_map.h"
#include <string>
#include <vector>
#include "base/logging.h"
#include "base/optional.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "content/browser/bluetooth/bluetooth_blocklist.h"
#include "content/common/bluetooth/web_bluetooth_device_id.h"
using device::BluetoothUUID;
namespace content {
BluetoothAllowedDevicesMap::BluetoothAllowedDevicesMap() {}
BluetoothAllowedDevicesMap::~BluetoothAllowedDevicesMap() {}
const WebBluetoothDeviceId& BluetoothAllowedDevicesMap::AddDevice(
const url::Origin& origin,
const std::string& device_address,
const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options) {
DVLOG(1) << "Adding a device to Map of Allowed Devices.";
// "Unique" Origins generate the same key in maps, therefore are not
// supported.
CHECK(!origin.unique());
auto device_address_to_id_map = origin_to_device_address_to_id_map_[origin];
auto id_iter = device_address_to_id_map.find(device_address);
if (id_iter != device_address_to_id_map.end()) {
DVLOG(1) << "Device already in map of allowed devices.";
const auto& device_id = id_iter->second;
AddUnionOfServicesTo(
options, &origin_to_device_id_to_services_map_[origin][device_id]);
return origin_to_device_address_to_id_map_[origin][device_address];
}
const WebBluetoothDeviceId device_id = GenerateUniqueDeviceId();
DVLOG(1) << "Id generated for device: " << device_id;
origin_to_device_address_to_id_map_[origin][device_address] = device_id;
origin_to_device_id_to_address_map_[origin][device_id] = device_address;
AddUnionOfServicesTo(
options, &origin_to_device_id_to_services_map_[origin][device_id]);
CHECK(device_id_set_.insert(device_id).second);
return origin_to_device_address_to_id_map_[origin][device_address];
}
void BluetoothAllowedDevicesMap::RemoveDevice(
const url::Origin& origin,
const std::string& device_address) {
const WebBluetoothDeviceId* device_id_ptr =
GetDeviceId(origin, device_address);
DCHECK(device_id_ptr != nullptr);
// We make a copy because we are going to remove the original value from its
// map.
WebBluetoothDeviceId device_id = *device_id_ptr;
// 1. Remove from all three maps.
CHECK(origin_to_device_address_to_id_map_[origin].erase(device_address));
CHECK(origin_to_device_id_to_address_map_[origin].erase(device_id));
CHECK(origin_to_device_id_to_services_map_[origin].erase(device_id));
// 2. Remove empty map for origin.
if (origin_to_device_address_to_id_map_[origin].empty()) {
CHECK(origin_to_device_address_to_id_map_.erase(origin));
CHECK(origin_to_device_id_to_address_map_.erase(origin));
CHECK(origin_to_device_id_to_services_map_.erase(origin));
}
// 3. Remove from set of ids.
CHECK(device_id_set_.erase(device_id));
}
const WebBluetoothDeviceId* BluetoothAllowedDevicesMap::GetDeviceId(
const url::Origin& origin,
const std::string& device_address) {
auto address_map_iter = origin_to_device_address_to_id_map_.find(origin);
if (address_map_iter == origin_to_device_address_to_id_map_.end()) {
return nullptr;
}
const auto& device_address_to_id_map = address_map_iter->second;
auto id_iter = device_address_to_id_map.find(device_address);
if (id_iter == device_address_to_id_map.end()) {
return nullptr;
}
return &(id_iter->second);
}
const std::string& BluetoothAllowedDevicesMap::GetDeviceAddress(
const url::Origin& origin,
const WebBluetoothDeviceId& device_id) {
auto id_map_iter = origin_to_device_id_to_address_map_.find(origin);
if (id_map_iter == origin_to_device_id_to_address_map_.end()) {
return base::EmptyString();
}
const auto& device_id_to_address_map = id_map_iter->second;
auto id_iter = device_id_to_address_map.find(device_id);
return id_iter == device_id_to_address_map.end() ? base::EmptyString()
: id_iter->second;
}
bool BluetoothAllowedDevicesMap::IsOriginAllowedToAccessAtLeastOneService(
const url::Origin& origin,
const WebBluetoothDeviceId& device_id) const {
auto id_map_iter = origin_to_device_id_to_services_map_.find(origin);
if (id_map_iter == origin_to_device_id_to_services_map_.end()) {
return false;
}
const auto& device_id_to_services_map = id_map_iter->second;
auto id_iter = device_id_to_services_map.find(device_id);
return id_iter == device_id_to_services_map.end() ? false
: !id_iter->second.empty();
}
bool BluetoothAllowedDevicesMap::IsOriginAllowedToAccessService(
const url::Origin& origin,
const WebBluetoothDeviceId& device_id,
const BluetoothUUID& service_uuid) const {
if (BluetoothBlocklist::Get().IsExcluded(service_uuid)) {
return false;
}
auto id_map_iter = origin_to_device_id_to_services_map_.find(origin);
if (id_map_iter == origin_to_device_id_to_services_map_.end()) {
return false;
}
const auto& device_id_to_services_map = id_map_iter->second;
auto id_iter = device_id_to_services_map.find(device_id);
return id_iter == device_id_to_services_map.end()
? false
: base::ContainsKey(id_iter->second, service_uuid);
}
WebBluetoothDeviceId BluetoothAllowedDevicesMap::GenerateUniqueDeviceId() {
WebBluetoothDeviceId device_id = WebBluetoothDeviceId::Create();
while (base::ContainsKey(device_id_set_, device_id)) {
LOG(WARNING) << "Generated repeated id.";
device_id = WebBluetoothDeviceId::Create();
}
return device_id;
}
void BluetoothAllowedDevicesMap::AddUnionOfServicesTo(
const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options,
std::unordered_set<BluetoothUUID, device::BluetoothUUIDHash>*
unionOfServices) {
if (options->filters) {
for (const auto& filter : options->filters.value()) {
if (!filter->services) {
continue;
}
for (const BluetoothUUID& uuid : filter->services.value()) {
unionOfServices->insert(uuid);
}
}
}
for (const BluetoothUUID& uuid : options->optional_services) {
unionOfServices->insert(uuid);
}
}
} // namespace content
| 34.299465 | 79 | 0.746336 | [
"vector"
] |
08e317979333bbb9b62f4fd565e137d1c56a5527 | 746 | hpp | C++ | d20tempest/include/communication/tcp_client.hpp | tempestjam/d20tempest | 99c69ca1615b77aade96a4fa566139dabef98fa3 | [
"Apache-2.0"
] | null | null | null | d20tempest/include/communication/tcp_client.hpp | tempestjam/d20tempest | 99c69ca1615b77aade96a4fa566139dabef98fa3 | [
"Apache-2.0"
] | 2 | 2019-06-16T21:41:43.000Z | 2019-06-22T00:49:10.000Z | d20tempest/include/communication/tcp_client.hpp | tempestjam/d20tempest | 99c69ca1615b77aade96a4fa566139dabef98fa3 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <memory>
#include <gsl/gsl>
#include <uvw.hpp>
#include "communication/iclient.hpp"
namespace d20tempest::communication
{
class TCPClientImpl;
class TCPClient : public IClient
{
private:
std::shared_ptr<TCPClientImpl> m_impl;
public:
TCPClient(gsl::not_null<uvw::TCPHandle*> sock, const uint64_t connectionID);
~TCPClient();
virtual void OnMessage(const std::string& path, ClientMessageHandler handler) override;
virtual void OnLeave(ClientDisconnectedHandler handler) override;
virtual void Send(std::vector<std::byte>& msg) override;
virtual void Send(std::vector<std::byte>&& msg) override;
uint64_t ConnectionId() const;
};
} | 25.724138 | 95 | 0.684987 | [
"vector"
] |
08e76053ef6a22eab28e44dc3d33d9623dc04519 | 11,772 | cpp | C++ | Lib/Runtime/Compartment.cpp | auto-ndp/WAVM | 32d75d59ba206dbd84ccfc91fe33a68b6b986b4d | [
"BSD-3-Clause"
] | null | null | null | Lib/Runtime/Compartment.cpp | auto-ndp/WAVM | 32d75d59ba206dbd84ccfc91fe33a68b6b986b4d | [
"BSD-3-Clause"
] | null | null | null | Lib/Runtime/Compartment.cpp | auto-ndp/WAVM | 32d75d59ba206dbd84ccfc91fe33a68b6b986b4d | [
"BSD-3-Clause"
] | null | null | null | #include <stddef.h>
#include <atomic>
#include <memory>
#include <vector>
#include "RuntimePrivate.h"
#include "WAVM/Inline/Assert.h"
#include "WAVM/Inline/BasicTypes.h"
#include "WAVM/Inline/Timing.h"
#include "WAVM/Platform/Memory.h"
#include "WAVM/Platform/RWMutex.h"
#include "WAVM/Runtime/Runtime.h"
#include "WAVM/RuntimeABI/RuntimeABI.h"
#ifdef WAVM_HAS_TRACY
#include <Tracy.hpp>
#endif
using namespace WAVM;
using namespace WAVM::Runtime;
Runtime::Compartment::Compartment(std::string&& inDebugName,
struct CompartmentRuntimeData* inRuntimeData,
U8* inUnalignedRuntimeData)
: GCObject(ObjectKind::compartment, this, std::move(inDebugName))
, runtimeData(inRuntimeData)
, unalignedRuntimeData(inUnalignedRuntimeData)
, tables(0, maxTables - 1)
, memories(0, maxMemories - 1)
// Use UINTPTR_MAX as an invalid ID for globals, exception types, and instances.
, globals(0, UINTPTR_MAX - 1)
, exceptionTypes(0, UINTPTR_MAX - 1)
, instances(0, UINTPTR_MAX - 1)
, contexts(0, maxContexts - 1)
, foreigns(0, UINTPTR_MAX - 1)
{
runtimeData->compartment = this;
}
Runtime::Compartment::~Compartment()
{
Platform::RWMutex::ExclusiveLock compartmentLock(mutex);
WAVM_ASSERT(!memories.size());
WAVM_ASSERT(!tables.size());
WAVM_ASSERT(!exceptionTypes.size());
WAVM_ASSERT(!globals.size());
WAVM_ASSERT(!instances.size());
WAVM_ASSERT(!contexts.size());
WAVM_ASSERT(!foreigns.size());
Platform::freeAlignedVirtualPages(unalignedRuntimeData,
compartmentReservedBytes >> Platform::getBytesPerPageLog2(),
compartmentRuntimeDataAlignmentLog2);
Platform::deregisterVirtualAllocation(offsetof(CompartmentRuntimeData, contexts));
}
static CompartmentRuntimeData* initCompartmentRuntimeData(U8*& outUnalignedRuntimeData)
{
CompartmentRuntimeData* runtimeData
= (CompartmentRuntimeData*)Platform::allocateAlignedVirtualPages(
compartmentReservedBytes >> Platform::getBytesPerPageLog2(),
compartmentRuntimeDataAlignmentLog2,
outUnalignedRuntimeData);
WAVM_ERROR_UNLESS(Platform::commitVirtualPages(
(U8*)runtimeData,
offsetof(CompartmentRuntimeData, contexts) >> Platform::getBytesPerPageLog2()));
Platform::registerVirtualAllocation(offsetof(CompartmentRuntimeData, contexts));
return runtimeData;
}
Compartment* Runtime::createCompartment(std::string&& debugName)
{
U8* unalignedRuntimeData = nullptr;
CompartmentRuntimeData* runtimeData = initCompartmentRuntimeData(unalignedRuntimeData);
if(!runtimeData) { return nullptr; }
return new Compartment(std::move(debugName), runtimeData, unalignedRuntimeData);
}
Compartment* Runtime::cloneCompartment(const Compartment* compartment, std::string&& debugName)
{
Compartment* newCompartment;
U8* unalignedRuntimeData = nullptr;
CompartmentRuntimeData* runtimeData = initCompartmentRuntimeData(unalignedRuntimeData);
if(!runtimeData) { return nullptr; }
{
#ifdef WAVM_HAS_TRACY
ZoneNamedN(_zone_nc, "new Compartment", true);
#endif
newCompartment = new Compartment(std::move(debugName), runtimeData, unalignedRuntimeData);
;
}
Runtime::cloneCompartmentInto(*newCompartment, compartment, std::move(debugName));
return newCompartment;
}
namespace {
template<class T = Runtime::GCObject*>
void clearIndexMap(Runtime::Compartment* ownerCompartment,
WAVM::IndexMap<WAVM::Uptr, T>& indexMap)
{
Platform::RWMutex::ExclusiveLock lock(ownerCompartment->mutex);
for(T p : indexMap)
{
Runtime::GCObject* gp = p;
if(gp->compartment == ownerCompartment)
{
if(gp->numRootReferences.load() != 0)
{
throw std::runtime_error("Removed GCObject still has root references alive");
}
delete p;
}
}
indexMap = WAVM::IndexMap<WAVM::Uptr, T>(indexMap.getMinIndex(), indexMap.getMaxIndex());
}
template<class T = Runtime::GCObject*>
void clearRemainingIndexMap(Runtime::Compartment* ownerCompartment,
WAVM::IndexMap<WAVM::Uptr, T>& indexMap,
const WAVM::HashSet<WAVM::Uptr>& ignoreList,
std::vector<WAVM::Uptr>& removeList)
{
Platform::RWMutex::ExclusiveLock lock(ownerCompartment->mutex);
removeList.clear();
for(auto it = indexMap.begin(); it != indexMap.end(); ++it)
{
const WAVM::Uptr idx = it.getIndex();
if(!ignoreList.contains(idx)) { removeList.push_back(idx); }
}
for(WAVM::Uptr idx : removeList)
{
T p = *indexMap.get(idx);
Runtime::GCObject* gp = p;
if(gp->compartment == ownerCompartment)
{
if(gp->numRootReferences.load() != 0)
{
throw std::runtime_error("Removed GCObject still has root references alive");
}
delete p;
}
indexMap.removeOrFail(idx);
}
}
}
WAVM_API void Runtime::cloneCompartmentInto(Compartment& targetCompartment,
const Compartment* oldCompartment,
std::string&& debugName)
{
#ifdef WAVM_HAS_TRACY
ZoneNamedNS(_zone_root, "Runtime::cloneCompartmentInto", 6, true);
#endif
Platform::RWMutex::ShareableLock compartmentLock(oldCompartment->mutex);
Timing::Timer timer;
WAVM::HashSet<WAVM::Uptr> ignoreIndexList(32);
std::vector<WAVM::Uptr> removeList;
removeList.reserve(32);
// Reset structures
clearIndexMap(&targetCompartment, targetCompartment.contexts);
clearIndexMap(&targetCompartment, targetCompartment.foreigns);
// Clone tables.
ignoreIndexList.clear();
for(auto it = oldCompartment->tables.begin(); it != oldCompartment->tables.end(); ++it)
{
const WAVM::Uptr idx = it.getIndex();
ignoreIndexList.addOrFail(idx);
if(targetCompartment.tables.contains(idx))
{
const Table* oldTable = *it;
Table* newTable = *targetCompartment.tables.get(idx);
cloneTableInto(newTable, oldTable, &targetCompartment);
}
else
{
Table* newTable = cloneTable(*it, &targetCompartment);
WAVM_ASSERT(newTable->id == (*it)->id);
}
}
clearRemainingIndexMap(
&targetCompartment, targetCompartment.memories, ignoreIndexList, removeList);
// Clone memories.
// for(Memory* memory : oldCompartment->memories)
ignoreIndexList.clear();
for(auto it = oldCompartment->memories.begin(); it != oldCompartment->memories.end(); ++it)
{
const WAVM::Uptr idx = it.getIndex();
ignoreIndexList.addOrFail(idx);
if(targetCompartment.memories.contains(idx))
{
const Memory* oldMemory = *it;
Memory* newMemory = *targetCompartment.memories.get(idx);
cloneMemoryInto(newMemory, oldMemory, &targetCompartment);
}
else
{
Memory* newMemory = cloneMemory(*it, &targetCompartment);
WAVM_ASSERT(newMemory->id == (*it)->id);
}
}
clearRemainingIndexMap(
&targetCompartment, targetCompartment.memories, ignoreIndexList, removeList);
// Clone globals.
clearIndexMap(&targetCompartment, targetCompartment.globals);
{
#ifdef WAVM_HAS_TRACY
ZoneNamedN(_zone_mcg, "memcpy Globals", true);
#endif
targetCompartment.globalDataAllocationMask = oldCompartment->globalDataAllocationMask;
memcpy(targetCompartment.initialContextMutableGlobals,
oldCompartment->initialContextMutableGlobals,
sizeof(targetCompartment.initialContextMutableGlobals));
}
for(Global* global : oldCompartment->globals)
{
#ifdef WAVM_HAS_TRACY
ZoneNamedN(_zone_cg, "clone Global", true);
#endif
Global* newGlobal = cloneGlobal(global, &targetCompartment);
WAVM_ASSERT(newGlobal->id == global->id);
WAVM_ASSERT(newGlobal->mutableGlobalIndex == global->mutableGlobalIndex);
}
// Clone exception types.
clearIndexMap(&targetCompartment, targetCompartment.exceptionTypes);
for(ExceptionType* exceptionType : oldCompartment->exceptionTypes)
{
#ifdef WAVM_HAS_TRACY
ZoneNamedN(_zone_cet, "clone ExceptionType", true);
#endif
ExceptionType* newExceptionType = cloneExceptionType(exceptionType, &targetCompartment);
WAVM_ASSERT(newExceptionType->id == exceptionType->id);
}
// Clone instances.
clearIndexMap(&targetCompartment, targetCompartment.instances);
for(Instance* instance : oldCompartment->instances)
{
#ifdef WAVM_HAS_TRACY
ZoneNamedN(_zone_ci, "clone Instance", true);
#endif
Instance* newInstance = cloneInstance(instance, &targetCompartment);
WAVM_ASSERT(newInstance->id == instance->id);
}
Timing::logTimer("Cloned compartment", timer);
}
Object* Runtime::remapToClonedCompartment(const Object* object, const Compartment* newCompartment)
{
if(!object) { return nullptr; }
if(object->kind == ObjectKind::function) { return const_cast<Object*>(object); }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
switch(object->kind)
{
case ObjectKind::table: return newCompartment->tables[asTable(object)->id];
case ObjectKind::memory: return newCompartment->memories[asMemory(object)->id];
case ObjectKind::global: return newCompartment->globals[asGlobal(object)->id];
case ObjectKind::exceptionType:
return newCompartment->exceptionTypes[asExceptionType(object)->id];
case ObjectKind::instance: return newCompartment->instances[asInstance(object)->id];
case ObjectKind::function:
case ObjectKind::context:
case ObjectKind::compartment:
case ObjectKind::foreign:
case ObjectKind::invalid:
default: WAVM_UNREACHABLE();
};
}
Function* Runtime::remapToClonedCompartment(const Function* function,
const Compartment* newCompartment)
{
return const_cast<Function*>(function);
}
Table* Runtime::remapToClonedCompartment(const Table* table, const Compartment* newCompartment)
{
if(!table) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->tables[table->id];
}
Memory* Runtime::remapToClonedCompartment(const Memory* memory, const Compartment* newCompartment)
{
if(!memory) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->memories[memory->id];
}
Global* Runtime::remapToClonedCompartment(const Global* global, const Compartment* newCompartment)
{
if(!global) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->globals[global->id];
}
ExceptionType* Runtime::remapToClonedCompartment(const ExceptionType* exceptionType,
const Compartment* newCompartment)
{
if(!exceptionType) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->exceptionTypes[exceptionType->id];
}
Instance* Runtime::remapToClonedCompartment(const Instance* instance,
const Compartment* newCompartment)
{
if(!instance) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->instances[instance->id];
}
Foreign* Runtime::remapToClonedCompartment(const Foreign* foreign,
const Compartment* newCompartment)
{
if(!foreign) { return nullptr; }
Platform::RWMutex::ShareableLock compartmentLock(newCompartment->mutex);
return newCompartment->foreigns[foreign->id];
}
bool Runtime::isInCompartment(const Object* object, const Compartment* compartment)
{
if(object->kind == ObjectKind::function)
{
// The function may be in multiple compartments, but if this compartment maps the function's
// instanceId to a Instance with the LLVMJIT LoadedModule that contains this
// function, then the function is in this compartment.
Function* function = (Function*)object;
// Treat functions with instanceId=UINTPTR_MAX as if they are in all compartments.
if(function->instanceId == UINTPTR_MAX) { return true; }
Platform::RWMutex::ShareableLock compartmentLock(compartment->mutex);
if(!compartment->instances.contains(function->instanceId)) { return false; }
Instance* instance = compartment->instances[function->instanceId];
return instance->jitModule.get() == function->mutableData->jitModule;
}
else
{
GCObject* gcObject = (GCObject*)object;
return gcObject->compartment == compartment;
}
}
| 33.634286 | 98 | 0.754417 | [
"object",
"vector"
] |
08e94b2ec498f7583fc78e2a56f126c33bb98e38 | 1,982 | cpp | C++ | RTCPi/tests/testfiles/set_date.cpp | abelectronicsuk/ABElectronics_CPP_Libraries | ff9e884d95d6ff6797b5628683fdac5bb13db267 | [
"MIT"
] | 9 | 2017-11-12T02:11:11.000Z | 2022-01-29T16:57:38.000Z | RTCPi/tests/testfiles/set_date.cpp | abelectronicsuk/ABElectronics_CPP_Libraries | ff9e884d95d6ff6797b5628683fdac5bb13db267 | [
"MIT"
] | 2 | 2019-03-04T10:11:34.000Z | 2020-07-01T12:50:37.000Z | RTCPi/tests/testfiles/set_date.cpp | abelectronicsuk/ABElectronics_CPP_Libraries | ff9e884d95d6ff6797b5628683fdac5bb13db267 | [
"MIT"
] | 9 | 2017-08-03T00:04:58.000Z | 2021-09-03T12:04:38.000Z | /*
* set_date.cpp
*
* RTCPi class > set_date function test program
*
*/
#include <stdio.h>
#include <stdexcept>
#include <unistd.h>
#include <iostream>
#include "../../../UnitTest/testlibs.cpp"
#include "../../ABE_RTCPi.h"
using namespace ABElectronics_CPP_Libraries;
using namespace std;
int main(int argc, char **argv)
{
TestLibs test;
test.start_test("RTCPi class > set_date()");
RTCPi rtc; // new RTCPi object
struct tm datetime; // create a tm struct to store the date
// set the date
datetime.tm_sec = 31; // seconds
datetime.tm_min = 26; // minutes
datetime.tm_hour = 17;// hours
datetime.tm_wday = 4;// dayofweek
datetime.tm_mday = 10;// day
datetime.tm_mon = 06;// month - 1
datetime.tm_year = 120; // years since 1900
rtc.set_date(datetime); // send the date to the RTC Pi
uint8_t seconds = test.i2c_emulator_read_byte_data(test.DS1307_SECONDS);
uint8_t minutes = test.i2c_emulator_read_byte_data(test.DS1307_MINUTES);
uint8_t hours = test.i2c_emulator_read_byte_data(test.DS1307_HOURS);
uint8_t dayofweek = test.i2c_emulator_read_byte_data(test.DS1307_DAYOFWEEK);
uint8_t day = test.i2c_emulator_read_byte_data(test.DS1307_DAY);
uint8_t month = test.i2c_emulator_read_byte_data(test.DS1307_MONTH);
uint8_t year = test.i2c_emulator_read_byte_data(test.DS1307_YEAR);
if (seconds != 0x31){
test.test_fail("failed to set seconds");
}
if (minutes != 0x26){
test.test_fail("failed to set minutes");
}
if (hours != 0x17){
test.test_fail("failed to set hours");
}
if (dayofweek != 0x04){
test.test_fail("failed to set dayofweek");
}
if (day != 0x10){
test.test_fail("failed to set day");
}
if (month != 0x07){
test.test_fail("failed to set month");
}
if (year != 0x20){
test.test_fail("failed to set year");
}
test.test_outcome();
(void)argc;
(void)argv;
return (0);
}
| 24.775 | 80 | 0.660444 | [
"object"
] |
08f1267b15f097fcd29f5e60c57503b9a2c81598 | 7,205 | cpp | C++ | base/src/work/BasicProcessor.cpp | BeeeOn/gateway-frc | b5bcebd6dc068394906e35d989ed48dc65e9ebaf | [
"BSD-3-Clause"
] | null | null | null | base/src/work/BasicProcessor.cpp | BeeeOn/gateway-frc | b5bcebd6dc068394906e35d989ed48dc65e9ebaf | [
"BSD-3-Clause"
] | null | null | null | base/src/work/BasicProcessor.cpp | BeeeOn/gateway-frc | b5bcebd6dc068394906e35d989ed48dc65e9ebaf | [
"BSD-3-Clause"
] | null | null | null | #include <Poco/Exception.h>
#include <Poco/Thread.h>
#include <Poco/Logger.h>
#include "di/Injectable.h"
#include "work/BasicProcessor.h"
#include "work/WorkAccess.h"
#include "work/WorkExecutor.h"
#include "work/WorkRepository.h"
#include "work/WorkRunner.h"
#include "work/WorkScheduler.h"
BEEEON_OBJECT_BEGIN(BeeeOn, BasicProcessor)
BEEEON_OBJECT_CASTABLE(WorkScheduler)
BEEEON_OBJECT_CASTABLE(StoppableRunnable)
BEEEON_OBJECT_REF("repository", &BasicProcessor::setRepository)
BEEEON_OBJECT_REF("runnerFactory", &BasicProcessor::setRunnerFactory)
BEEEON_OBJECT_REF("executors", &BasicProcessor::registerExecutor)
BEEEON_OBJECT_NUMBER("minThreads", &BasicProcessor::setMinThreads)
BEEEON_OBJECT_NUMBER("maxThreads", &BasicProcessor::setMaxThreads)
BEEEON_OBJECT_NUMBER("threadIdleTime", &BasicProcessor::setThreadIdleTime)
BEEEON_OBJECT_HOOK("done", &BasicProcessor::init)
BEEEON_OBJECT_END(BeeeOn, BasicProcessor)
using namespace std;
using namespace Poco;
using namespace BeeeOn;
BasicProcessor::BasicProcessor():
m_repository(&EmptyWorkRepository::instance()),
m_runnerFactory(&NullWorkRunnerFactory::instance()),
m_shouldStop(0),
m_current(NULL),
m_minThreads(1),
m_maxThreads(16),
m_threadIdleTime(100)
{
}
void BasicProcessor::setRepository(WorkRepository *repository)
{
m_repository = repository? repository : &EmptyWorkRepository::instance();
}
void BasicProcessor::setRunnerFactory(WorkRunnerFactory *factory)
{
m_runnerFactory = factory? factory : &NullWorkRunnerFactory::instance();
}
void BasicProcessor::setMinThreads(int min)
{
if (min < 0)
throw InvalidArgumentException("minThreads must be non-negative");
m_minThreads = min;
}
void BasicProcessor::setMaxThreads(int max)
{
if (max < 0)
throw InvalidArgumentException("maxThreads must be non-negative");
m_maxThreads = max;
}
void BasicProcessor::setThreadIdleTime(int ms)
{
if (ms <= 0)
throw InvalidArgumentException("threadIdleTime must be greater then zero");
if (ms > 0 && ms < 1000) {
logger().warning("threadIdleTime's granularity is 1000 ms, treating "
+ to_string(ms) + " as zero",
__FILE__, __LINE__);
}
m_threadIdleTime = ms / 1000;
}
void BasicProcessor::registerExecutor(WorkExecutor *executor)
{
m_executors.push_back(executor);
}
void BasicProcessor::init()
{
initQueue();
initPool();
}
void BasicProcessor::initQueue()
{
vector<Work::Ptr> all;
m_repository->loadScheduled(all);
FastMutex::ScopedLock guard(m_queue.lock());
for (auto &work : all) {
if (work->state() == Work::STATE_EXECUTED) {
if (logger().debug()) {
logger().debug("work " + *work
+ " in state executed is marked as failed",
__FILE__, __LINE__);
}
// locking is unnecessary as this is to be called only during
// initialization when the BasicProcessor is inactive.
work->setState(Work::STATE_FAILED);
m_repository->store(work);
continue;
}
else if (work->state() >= Work::STATE_FINISHED)
continue;
m_queue.pushUnlocked(work);
}
}
void BasicProcessor::initPool()
{
if (m_pool.isNull()) {
logger().notice("creating thread pool min: "
+ to_string(m_minThreads)
+ " max: "
+ to_string(m_maxThreads),
__FILE__, __LINE__);
m_pool = new ThreadPool(
m_minThreads,
m_maxThreads,
m_threadIdleTime
);
}
}
ThreadPool &BasicProcessor::pool()
{
initPool();
return *m_pool;
}
void BasicProcessor::run()
{
if (m_current != NULL)
return;
m_current = Thread::current();
if (m_current == NULL)
throw IllegalStateException("called outside of thread",
__FILE__, __LINE__);
m_current->setName("BasicProcessor");
while (!m_shouldStop) {
try {
dispatch();
}
catch (const Poco::Exception &e) {
logger().log(e, __FILE__, __LINE__);
}
catch (const std::exception &e) {
logger().critical(e.what(), __FILE__, __LINE__);
break;
}
catch (...) {
logger().critical("failed to dispatch", __FILE__, __LINE__);
break;
}
}
}
void BasicProcessor::stop()
{
m_shouldStop = 1;
notify();
}
void BasicProcessor::dispatch()
{
Work::Ptr work = m_queue.pop();
if (work.isNull()) {
if (logger().debug()) {
logger().debug("no work in the queue",
__FILE__, __LINE__);
}
return;
}
if (Work::timestampValid(work->finished())) {
if (logger().debug()) {
logger().debug("work " + *work
+ " has finished timestamp, skipping",
__FILE__, __LINE__);
}
return;
}
if (work->state() >= Work::STATE_FINISHED) {
logger().warning("work " + *work + " is done, ignoring...",
__FILE__, __LINE__);
return;
}
WorkExecutor *executor = NULL;
for (auto one : m_executors) {
if (!one->accepts(work))
continue;
executor = one;
break;
}
if (executor == NULL) {
logger().warning("no executor for work " + *work,
__FILE__, __LINE__);
work->setState(Work::STATE_FAILED);
m_repository->store(work);
return;
}
if (logger().debug())
logger().debug("executing work " + *work, __FILE__, __LINE__);
execute(executor, work);
}
void BasicProcessor::execute(WorkExecutor *executor, Work::Ptr work)
{
WorkRunner *runner(m_runnerFactory->create(*this));
if (runner == NULL) {
logger().critical("runner was created as NULL",
__FILE__, __LINE__);
return;
}
if (logger().debug()) {
logger().debug("having runner, executing work " + *work + " in thread",
__FILE__, __LINE__);
}
runner->setExecutor(executor);
runner->setWork(work);
runner->setRepository(m_repository);
try {
while (!executeInThread(*runner, "Work:" + *work)) {
logger().warning("no thread to execute work " + *work);
m_current->trySleep(100);
}
} catch (...) {
// WorkRunner did not started otherwise it
// would delete itself automatically
delete runner;
throw;
}
}
bool BasicProcessor::executeInThread(Runnable &runnable, const string &name)
{
if (logger().debug())
logger().debug("executing thread " + name, __FILE__, __LINE__);
try {
pool().start(runnable, name);
} catch (Poco::NoThreadAvailableException &e) {
return false;
}
return true;
}
void BasicProcessor::schedule(Work::Ptr work)
{
if (logger().debug()) {
logger().debug("schedule work " + *work,
__FILE__, __LINE__);
}
FastMutex::ScopedLock guard(m_queue.lock());
m_queue.pushUnlocked(work);
m_repository->store(work);
wakeUpSelf();
}
void BasicProcessor::wakeup(Work::Ptr work)
{
if (logger().debug()) {
logger().debug("wakeup work " + *work,
__FILE__, __LINE__);
}
FastMutex::ScopedLock guard(m_queue.lock());
m_queue.wakeupUnlocked(work);
m_repository->store(work);
wakeUpSelf();
}
void BasicProcessor::cancel(Work::Ptr work)
{
if (logger().debug()) {
logger().debug("cancel work " + *work,
__FILE__, __LINE__);
}
FastMutex::ScopedLock guard(m_queue.lock());
// lock the work to cancel it safely
WorkWriting accessGuard(work, __FILE__, __LINE__);
m_queue.cancelUnlocked(work);
work->setState(Work::STATE_CANCELED, accessGuard);
m_repository->store(work);
wakeUpSelf();
}
void BasicProcessor::notify()
{
if (logger().debug()) {
logger().debug("notify work processor",
__FILE__, __LINE__);
}
m_queue.notify();
wakeUpSelf();
}
void BasicProcessor::wakeUpSelf()
{
if(m_current)
m_current->wakeUp();
}
| 21.067251 | 77 | 0.696183 | [
"vector"
] |
08f9b0b792b59f69f1f545084c9bb57d458389a0 | 7,796 | hpp | C++ | include/fl/filter/gaussian/transform/unscented_transform.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | include/fl/filter/gaussian/transform/unscented_transform.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | include/fl/filter/gaussian/transform/unscented_transform.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file unscented_transform.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#pragma once
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/filter/gaussian/transform/point_set_transform.hpp>
#include <fl/distribution/joint_distribution.hpp>
#include <functional>
namespace fl
{
/**
* \ingroup point_set_transform
*
* This is the Unscented Transform used in the Unscented Kalman Filter
* \cite wan2000unscented . It implememnts the PointSetTransform interface.
*/
class UnscentedTransform
: public PointSetTransform<UnscentedTransform>,
public Descriptor
{
public:
/**
* Creates a UnscentedTransform
*
* \param alpha UT Scaling parameter alpha (distance to the mean)
* \param beta UT Scaling parameter beta (2.0 is optimal for Gaussian)
* \param kappa UT Scaling parameter kappa (higher order parameter)
*/
UnscentedTransform(Real alpha = 0.5, Real beta = 2., Real kappa = 0.)
: PointSetTransform<UnscentedTransform>(this),
alpha_(alpha),
beta_(beta),
kappa_(kappa)
{
}
/**
* \copydoc PointSetTransform::forward(const Gaussian&,
* PointSet&) const
*
* \throws WrongSizeException
* \throws ResizingFixedSizeEntityException
*/
template <typename Gaussian_, typename PointSet_>
void forward(const Gaussian_& gaussian,
PointSet_& point_set) const
{
forward(gaussian, gaussian.dimension(), 0, point_set);
}
/**
* \copydoc PointSetTransform::forward(const Gaussian&,
* PointSet&) const
*
* \throws WrongSizeException
* \throws ResizingFixedSizeEntityException
*/
template <typename Gaussian_, typename PointSet_>
void operator()(const Gaussian_& gaussian,
PointSet_& point_set) const
{
forward(gaussian, gaussian.dimension(), 0, point_set);
}
/**
* \copydoc PointSetTransform::forward(const Gaussian&,
* int global_dimension,
* int dimension_offset,
* PointSet&) const
*
* \throws WrongSizeException
* \throws ResizingFixedSizeEntityException
*/
template <typename Gaussian_, typename PointSet_>
void forward(const Gaussian_& gaussian,
int global_dimension,
int dimension_offset,
PointSet_& point_set) const
{
typedef typename Traits<PointSet_>::Point Point;
typedef typename Traits<PointSet_>::Weight Weight;
const Real dim = Real(global_dimension);
const int point_count = number_of_points(dim);
assert(point_count > 0);
/**
* \internal
*
* \remark
* A PointSet with a fixed number of points must have the
* correct number of points which is required by this transform
*/
if (IsFixed<Traits<PointSet_>::NumberOfPoints>() &&
Traits<PointSet_>::NumberOfPoints != point_count)
{
fl_throw(
WrongSizeException("Incompatible number of points of the"
" specified fixed-size PointSet"));
}
// will resize of transform size is different from point count.
point_set.resize(point_count);
auto&& covariance_sqrt = gaussian.square_root() * gamma_factor(dim);
Point point_shift;
const Point& mean = gaussian.mean();
// set the first point
point_set.point(0, mean, Weight{weight_mean_0(dim), weight_cov_0(dim)});
// compute the remaining points
Weight weight_i{weight_mean_i(dim), weight_cov_i(dim)};
// use squential loops to enable loop unrolling
const int start_1 = 1;
const int limit_1 = start_1 + dimension_offset;
const int limit_2 = limit_1 + gaussian.dimension();
const int limit_3 = global_dimension;
for (int i = start_1; i < limit_1; ++i)
{
point_set.point(i, mean, weight_i);
point_set.point(global_dimension + i, mean, weight_i);
}
for (int i = limit_1; i < limit_2; ++i)
{
point_shift = covariance_sqrt.col(i - dimension_offset - 1);
point_set.point(i, mean + point_shift, weight_i);
point_set.point(global_dimension + i, mean - point_shift, weight_i);
}
for (int i = limit_2; i <= limit_3; ++i)
{
point_set.point(i, mean, weight_i);
point_set.point(global_dimension + i, mean, weight_i);
}
}
/**
* \copydoc PointSetTransform::forward(const Gaussian&,
* int global_dimension,
* int dimension_offset,
* PointSet&) const
*
* \throws WrongSizeException
* \throws ResizingFixedSizeEntityException
*/
template <typename Gaussian_, typename PointSet_>
void operator()(const Gaussian_& gaussian,
int global_dimension,
int dimension_offset,
PointSet_& point_set) const
{
forward(gaussian, global_dimension, dimension_offset, point_set);
}
/**
* \return Number of points generated by this transform
*
* \param dimension Dimension of the Gaussian
*/
static constexpr int number_of_points(int dimension)
{
return (dimension != Eigen::Dynamic) ? 2 * dimension + 1 : Eigen::Dynamic;
}
public:
/** \cond INTERNAL */
/**
* \returninternalean weight
*
* \param dim Dimension of the Gaussian
*/
Real weight_mean_0(Real dim) const
{
return lambda_scalar(dim) / (dim + lambda_scalar(dim));
}
/**
* \return First covariance weight
*
* \param dim Dimension of the Gaussian
*/
Real weight_cov_0(Real dim) const
{
//alpha_ = 1./dim;
return weight_mean_0(dim) + (1 - alpha_ * alpha_ + beta_);
}
/**
* \return i-th mean weight
*
* \param dimension Dimension of the Gaussian
*/
Real weight_mean_i(Real dim) const
{
return 1. / (2. * (dim + lambda_scalar(dim)));
}
/**
* \return i-th covariance weight
*
* \param dimension Dimension of the Gaussian
*/
Real weight_cov_i(Real dim) const
{
return weight_mean_i(dim);
}
/**
* \param dim Dimension of the Gaussian
*/
Real lambda_scalar(Real dim) const
{
//alpha_ = 1./dim;
return alpha_ * alpha_ * (dim + kappa_) - dim;
}
/**
* \param dim Dimension of the Gaussian
*/
Real gamma_factor(Real dim) const
{
return std::sqrt(dim + lambda_scalar(dim));
}
/** \endcond */
virtual std::string name() const
{
return "UnscentedTransform";
}
virtual std::string description() const
{
return name();
}
protected:
/** \cond INTERNAL */
mutable Real alpha_;
Real beta_;
Real kappa_;
/** \endcond */
};
}
| 27.743772 | 82 | 0.584787 | [
"transform"
] |
1c016108a9a6f3ba78a79989227b868352b404f3 | 2,667 | cpp | C++ | ArrhythmiaStudio/src/MainWindow.cpp | Reimnop/ArrhythmiaStudio | d8b63992d9d461a495b33f7e6dfef62607a4f152 | [
"MIT"
] | 6 | 2021-10-04T03:06:12.000Z | 2022-02-14T09:32:59.000Z | ArrhythmiaStudio/src/MainWindow.cpp | Reimnop/ArrhythmiaStudio | d8b63992d9d461a495b33f7e6dfef62607a4f152 | [
"MIT"
] | null | null | null | ArrhythmiaStudio/src/MainWindow.cpp | Reimnop/ArrhythmiaStudio | d8b63992d9d461a495b33f7e6dfef62607a4f152 | [
"MIT"
] | 1 | 2021-12-04T17:59:22.000Z | 2021-12-04T17:59:22.000Z | #include "MainWindow.h"
#include "logic/GameManager.h"
#include "helper.h"
#include "bass/bass.h"
void MainWindow::glfwErrorCallback(int error_code, const char* description)
{
LOG4CXX_ERROR(logger, "GLFW: " << description);
}
void MainWindow::glDebugCallback(GLenum source, GLenum type, unsigned int id, GLenum severity, GLsizei length, const char* message, const void* userParam)
{
std::string msgStr = std::string(message, length);
switch (severity)
{
case GL_DEBUG_SEVERITY_LOW:
LOG4CXX_DEBUG(logger, "OpenGL: " << msgStr.c_str());
break;
case GL_DEBUG_SEVERITY_MEDIUM:
LOG4CXX_WARN(logger, "OpenGL: " << msgStr.c_str());
break;
case GL_DEBUG_SEVERITY_HIGH:
LOG4CXX_ERROR(logger, "OpenGL: " << msgStr.c_str());
break;
}
}
MainWindow* MainWindow::inst;
MainWindow::MainWindow()
{
if (inst)
{
return;
}
inst = this;
glfwSetErrorCallback(glfwErrorCallback);
// Init GLFW
LOG4CXX_ASSERT(logger, glfwInit(), "GLFW initialization failed!");
// Create window
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
window = glfwCreateWindow(1600, 900, STRINGIFY(PROJECT_NAME), NULL, NULL);
LOG4CXX_ASSERT(logger, window, "Window creation failed!");
glfwMakeContextCurrent(window);
LOG4CXX_ASSERT(logger, gladLoadGLLoader((GLADloadproc)glfwGetProcAddress), "GLAD initialization failed!");
glfwSwapInterval(1);
// Intialize OpenGL debug callback
glDebugMessageCallback(glDebugCallback, nullptr);
glEnable(GL_DEBUG_OUTPUT);
#ifdef DEBUG_CALLBACK_SYNCHRONOUS
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
#endif
// Initialize audio
BASS_Init(-1, 44100, BASS_DEVICE_STEREO, NULL, NULL);
// Initialize other things with onLoad
onLoad();
}
MainWindow::~MainWindow()
{
glfwTerminate();
BASS_Free();
}
void MainWindow::onLoad()
{
new Scene();
renderer = new Renderer(window);
gameManager = new GameManager(window);
}
void MainWindow::run()
{
while (!glfwWindowShouldClose(window))
{
float currentTime = glfwGetTime();
deltaTime = currentTime - time;
time = currentTime;
glfwPollEvents();
onUpdateFrame();
onRenderFrame();
}
}
void MainWindow::onUpdateFrame() const
{
gameManager->update();
// Update renderer last
renderer->update();
}
void MainWindow::onRenderFrame() const
{
int width, height;
glfwGetWindowSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderer->render();
glfwSwapBuffers(window);
}
| 20.835938 | 154 | 0.748031 | [
"render"
] |
1c13def0772af8bd33c23e453b3af26ffc90057c | 31,244 | cpp | C++ | ros/src/computing/planning/motion/packages/driving_planner/nodes/velocity_set/velocity_set.cpp | efernandez/Autoware | 0208514ff8f50a64fd434a60275cb1da2b06d84a | [
"BSD-3-Clause"
] | 1 | 2016-03-28T12:58:00.000Z | 2016-03-28T12:58:00.000Z | ros/src/computing/planning/motion/packages/driving_planner/nodes/velocity_set/velocity_set.cpp | efernandez/Autoware | 0208514ff8f50a64fd434a60275cb1da2b06d84a | [
"BSD-3-Clause"
] | null | null | null | ros/src/computing/planning/motion/packages/driving_planner/nodes/velocity_set/velocity_set.cpp | efernandez/Autoware | 0208514ff8f50a64fd434a60275cb1da2b06d84a | [
"BSD-3-Clause"
] | 3 | 2017-05-16T20:15:14.000Z | 2019-07-01T09:20:22.000Z | /*
* Copyright (c) 2015, Nagoya University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Autoware nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/Point.h>
#include <nav_msgs/Odometry.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <std_msgs/String.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int32.h>
#include <runtime_manager/ConfigVelocitySet.h>
#include <iostream>
#include "waypoint_follower/lane.h"
#include "waypoint_follower/libwaypoint_follower.h"
#include "libvelocity_set.h"
static const int LOOP_RATE = 10;
static geometry_msgs::TwistStamped _current_twist;
static geometry_msgs::PoseStamped _current_pose; // pose of sensor
static geometry_msgs::PoseStamped _control_pose; // pose of base_link
static geometry_msgs::PoseStamped _sim_ndt_pose;
static pcl::PointCloud<pcl::PointXYZ> _vscan;
static const std::string pedestrian_sound = "pedestrian";
static bool _pose_flag = false;
static bool _path_flag = false;
static bool _vscan_flag = false;
static int _obstacle_waypoint = -1;
static double _deceleration_search_distance = 30;
static double _search_distance = 60;
static int _closest_waypoint = -1;
static double _current_vel = 0.0; // subscribe estimated_vel_mps
static CrossWalk vmap;
static ObstaclePoints g_obstacle;
static bool g_sim_mode;
/* Config Parameter */
static double _detection_range = 0; // if obstacle is in this range, stop
static double _deceleration_range = 1.8; // if obstacle is in this range, decelerate
static double _deceleration_minimum = kmph2mps(4.0); // until this speed
static int _threshold_points = 15;
static double _detection_height_top = 2.0; //actually +2.0m
static double _detection_height_bottom = -2.0;
static double _cars_distance = 15.0; // meter: stopping distance from cars (using DPM)
static double _pedestrians_distance = 10.0; // meter: stopping distance from pedestrians (using DPM)
static double _others_distance = 8.0; // meter: stopping distance from obstacles (using VSCAN)
static double _decel = 1.5; // (m/s) deceleration
static double _velocity_change_limit = 2.778; // (m/s) about 10 km/h
static double _velocity_limit = 12.0; //(m/s) limit velocity for waypoints
static double _temporal_waypoints_size = 100.0; // meter
static double _velocity_offset = 1.389; // (m/s)
//Publisher
static ros::Publisher _range_pub;
static ros::Publisher _deceleration_range_pub;
static ros::Publisher _sound_pub;
static ros::Publisher _safety_waypoint_pub;
static ros::Publisher _temporal_waypoints_pub;
static ros::Publisher _crosswalk_points_pub;
static ros::Publisher _obstacle_pub;
static WayPoints _path_dk;
class PathVset: public WayPoints{
private:
waypoint_follower::lane temporal_waypoints_;
public:
void changeWaypoints(int stop_waypoint);
void avoidSuddenBraking();
void avoidSuddenAceleration();
void setDeceleration();
bool checkWaypoint(int num, const char *name) const;
void setTemporalWaypoints();
waypoint_follower::lane getTemporalWaypoints() const { return temporal_waypoints_; }
};
static PathVset _path_change;
//===============================
// class function
//===============================
// check if waypoint number is valid
bool PathVset::checkWaypoint(int num, const char *name) const
{
if (num < 0 || num >= getSize()){
std::cout << name << ": invalid waypoint number" << std::endl;
return false;
}
return true;
}
// set about '_temporal_waypoints_size' meter waypoints from closest waypoint
void PathVset::setTemporalWaypoints()
{
if (_closest_waypoint < 0)
return;
int size = (int)(_temporal_waypoints_size/getInterval())+1;
temporal_waypoints_.waypoints.clear();
temporal_waypoints_.header = current_waypoints_.header;
temporal_waypoints_.increment = current_waypoints_.increment;
// push current pose
waypoint_follower::waypoint current_point;
current_point.pose = _control_pose;
if (g_sim_mode)
current_point.pose = _current_pose;
current_point.twist = current_waypoints_.waypoints[_closest_waypoint].twist;
current_point.dtlane = current_waypoints_.waypoints[_closest_waypoint].dtlane;
temporal_waypoints_.waypoints.push_back(current_point);
for (int i = 0; i < size; i++) {
if (_closest_waypoint+i >= getSize())
return;
temporal_waypoints_.waypoints.push_back(current_waypoints_.waypoints[_closest_waypoint+i]);
}
return;
}
void PathVset::setDeceleration()
{
int velocity_change_range = 5;
double intervel = getInterval();
double temp1 = _current_vel*_current_vel;
double temp2 = 2*_decel*intervel;
for (int i = 0; i < velocity_change_range; i++) {
if (!checkWaypoint(_closest_waypoint+i, "setDeceleration"))
continue;
double waypoint_velocity = current_waypoints_.waypoints[_closest_waypoint+i].twist.twist.linear.x;
double changed_vel = temp1 - temp2;
if (changed_vel < 0) {
changed_vel = _deceleration_minimum * _deceleration_minimum;
}
if (sqrt(changed_vel) > waypoint_velocity || _deceleration_minimum > waypoint_velocity)
continue;
if (sqrt(changed_vel) < _deceleration_minimum) {
current_waypoints_.waypoints[_closest_waypoint+i].twist.twist.linear.x = _deceleration_minimum;
continue;
}
current_waypoints_.waypoints[_closest_waypoint+i].twist.twist.linear.x = sqrt(changed_vel);
}
return;
}
void PathVset::avoidSuddenAceleration()
{
double changed_vel;
double interval = getInterval();
double temp1 = _current_vel*_current_vel;
double temp2 = 2*_decel*interval;
for (int i = 0; ; i++) {
if (!checkWaypoint(_closest_waypoint+i, "avoidSuddenAceleration"))
return;
changed_vel = sqrt(temp1 + temp2*(double)(i+1)) + _velocity_offset;
if (changed_vel > current_waypoints_.waypoints[_closest_waypoint+i].twist.twist.linear.x)
return;
current_waypoints_.waypoints[_closest_waypoint+i].twist.twist.linear.x = changed_vel;
}
return;
}
void PathVset::avoidSuddenBraking()
{
int i = 0;
int fill_in_zero = 20;
int fill_in_vel = 15;
int examin_range = 1; // need to change according to waypoint interval?
int num;
double interval = getInterval();
double changed_vel;
for (int j = -1; j < examin_range; j++) {
if (!checkWaypoint(_closest_waypoint+j, "avoidSuddenBraking"))
return;
if (getWaypointVelocityMPS(_closest_waypoint+j) < _current_vel - _velocity_change_limit) // we must change waypoints
break;
if (j == examin_range-1) // we don't have to change waypoints
return;
}
std::cout << "====avoid sudden braking====" << std::endl;
std::cout << "vehicle is decelerating..." << std::endl;
std::cout << "closest_waypoint: " << _closest_waypoint << std::endl;
// fill in waypoints velocity behind vehicle
for (num = _closest_waypoint-1; fill_in_vel > 0; fill_in_vel--) {
if (!checkWaypoint(num-fill_in_vel, "avoidSuddenBraking"))
continue;
current_waypoints_.waypoints[num-fill_in_vel].twist.twist.linear.x = _current_vel;
}
// decelerate gradually
double temp1 = (_current_vel-_velocity_change_limit+1.389)*(_current_vel-_velocity_change_limit+1.389);
double temp2 = 2*_decel*interval;
for (num = _closest_waypoint-1; ; num++) {
if (num >= getSize())
return;
if (!checkWaypoint(num, "avoidSuddenBraking"))
continue;
changed_vel = temp1 - temp2*(double)i; // sqrt(v^2 - 2*a*x)
if (changed_vel <= 0)
break;
current_waypoints_.waypoints[num].twist.twist.linear.x = sqrt(changed_vel);
i++;
}
for (int j = 0; j < fill_in_zero; j++) {
if (!checkWaypoint(num+j, "avoidSuddenBraking"))
continue;
current_waypoints_.waypoints[num+j].twist.twist.linear.x = 0.0;
}
std::cout << "====changed waypoints====" << std::endl;
return;
}
void PathVset::changeWaypoints(int stop_waypoint)
{
int i = 0;
int close_waypoint_threshold = 4;
int fill_in_zero = 20;
double changed_vel;
double interval = getInterval();
// change waypoints to decelerate
for (int num = stop_waypoint; num > _closest_waypoint - close_waypoint_threshold; num--){
if (!checkWaypoint(num, "changeWaypoints"))
continue;
changed_vel = sqrt(2.0*_decel*(interval*i)); // sqrt(2*a*x)
//std::cout << "changed_vel[" << num << "]: " << mps2kmph(changed_vel) << " (km/h)";
//std::cout << " distance: " << (_obstacle_waypoint-num)*interval << " (m)";
//std::cout << " current_vel: " << mps2kmph(_current_vel) << std::endl;
waypoint_follower::waypoint initial_waypoint = _path_dk.getCurrentWaypoints().waypoints[num];
if (changed_vel > _velocity_limit || //
changed_vel > initial_waypoint.twist.twist.linear.x){ // avoid acceleration
//std::cout << "too large velocity!!" << std::endl;
current_waypoints_.waypoints[num].twist.twist.linear.x = initial_waypoint.twist.twist.linear.x;
} else {
current_waypoints_.waypoints[num].twist.twist.linear.x = changed_vel;
}
i++;
}
// fill in 0
for (int j = 1; j < fill_in_zero; j++){
if (!checkWaypoint(stop_waypoint+j, "changeWaypoints"))
continue;
current_waypoints_.waypoints[stop_waypoint+j].twist.twist.linear.x = 0.0;
}
std::cout << "---changed waypoints---" << std::endl;
return;
}
//===============================
// class function
//===============================
//===============================
// Callback
//===============================
void ConfigCallback(const runtime_manager::ConfigVelocitySetConstPtr &config)
{
_velocity_limit = kmph2mps(config->velocity_limit);
_others_distance = config->others_distance;
_cars_distance = config->cars_distance;
_pedestrians_distance = config->pedestrians_distance;
_detection_range = config->detection_range;
_threshold_points = config->threshold_points;
_detection_height_top = config->detection_height_top;
_detection_height_bottom = config->detection_height_bottom;
_decel = config->deceleration;
_velocity_change_limit = kmph2mps(config->velocity_change_limit);
_velocity_offset = kmph2mps(config->velocity_offset);
_deceleration_range = config->deceleration_range;
_deceleration_minimum = kmph2mps(config->deceleration_minimum);
_temporal_waypoints_size = config->temporal_waypoints_size;
}
void EstimatedVelCallback(const std_msgs::Float32ConstPtr &msg)
{
if (g_sim_mode)
return;
_current_vel = msg->data;
}
void BaseWaypointCallback(const waypoint_follower::laneConstPtr &msg)
{
ROS_INFO("subscribed base_waypoint\n");
_path_dk.setPath(*msg);
_path_change.setPath(*msg);
if (_path_flag == false) {
std::cout << "waypoint subscribed" << std::endl;
_path_flag = true;
}
}
void ObjPoseCallback(const visualization_msgs::MarkerConstPtr &msg)
{
ROS_INFO("subscribed obj_pose\n");
}
static void VscanCallback(const sensor_msgs::PointCloud2ConstPtr &msg)
{
pcl::PointCloud<pcl::PointXYZ> vscan_raw;
pcl::fromROSMsg(*msg, vscan_raw);
_vscan.clear();
for (const auto &v : vscan_raw) {
if (v.x == 0 && v.y == 0)
continue;
if (v.z > _detection_height_top || v.z < _detection_height_bottom)
continue;
_vscan.push_back(v);
}
if (_vscan_flag == false) {
std::cout << "vscan subscribed" << std::endl;
_vscan_flag = true;
}
}
static void ControlCallback(const geometry_msgs::PoseStampedConstPtr &msg)
{
_control_pose.header = msg->header;
_control_pose.pose = msg->pose;
}
static void LocalizerCallback(const geometry_msgs::PoseStampedConstPtr &msg)
{
if (g_sim_mode) {
_sim_ndt_pose.header = msg->header;
_sim_ndt_pose.pose = msg->pose;
return;
}
_current_pose.header = msg->header;
_current_pose.pose = msg->pose;
if (_pose_flag == false) {
std::cout << "pose subscribed" << std::endl;
_pose_flag = true;
}
}
static void OdometryPoseCallback(const nav_msgs::OdometryConstPtr &msg)
{
//
// effective for testing.
//
if (!g_sim_mode)
return;
_current_pose.header = msg->header;
_current_pose.pose = msg->pose.pose;
_current_vel = msg->twist.twist.linear.x;
if (_pose_flag == false) {
std::cout << "pose subscribed" << std::endl;
_pose_flag = true;
}
}
//===============================
// Callback
//===============================
static void DisplayObstacle(const EControl &kind)
{
visualization_msgs::Marker marker;
marker.header.frame_id = "/map";
marker.header.stamp = ros::Time();
marker.ns = "my_namespace";
marker.id = 0;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.position = g_obstacle.getObstaclePoint(kind);
if (kind == OTHERS)
marker.pose.position = g_obstacle.getPreviousDetection();
marker.pose.orientation = _current_pose.pose.orientation;
marker.scale.x = 1.0;
marker.scale.y = 1.0;
marker.scale.z = 2.0;
marker.color.a = 0.7;
if (kind == STOP) {
marker.color.r = 1.0;
marker.color.g = 0.0;
marker.color.b = 0.0;
} else {
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 0.0;
}
marker.lifetime = ros::Duration(0.1);
marker.frame_locked = true;
_obstacle_pub.publish(marker);
}
static void DisplayDetectionRange(const int &crosswalk_id, const int &num, const EControl &kind)
{
// set up for marker array
visualization_msgs::MarkerArray marker_array;
visualization_msgs::Marker crosswalk_marker;
visualization_msgs::Marker waypoint_marker_stop;
visualization_msgs::Marker waypoint_marker_decelerate;
visualization_msgs::Marker stop_line;
crosswalk_marker.header.frame_id = "/map";
crosswalk_marker.header.stamp = ros::Time();
crosswalk_marker.id = 0;
crosswalk_marker.type = visualization_msgs::Marker::SPHERE_LIST;
crosswalk_marker.action = visualization_msgs::Marker::ADD;
waypoint_marker_stop = crosswalk_marker;
waypoint_marker_decelerate = crosswalk_marker;
stop_line = crosswalk_marker;
stop_line.type = visualization_msgs::Marker::CUBE;
// set each namespace
crosswalk_marker.ns = "Crosswalk Detection";
waypoint_marker_stop.ns = "Stop Detection";
waypoint_marker_decelerate.ns = "Decelerate Detection";
stop_line.ns = "Stop Line";
// set scale and color
double scale = 2*_detection_range;
waypoint_marker_stop.scale.x = scale;
waypoint_marker_stop.scale.y = scale;
waypoint_marker_stop.scale.z = scale;
waypoint_marker_stop.color.a = 0.2;
waypoint_marker_stop.color.r = 0.0;
waypoint_marker_stop.color.g = 1.0;
waypoint_marker_stop.color.b = 0.0;
waypoint_marker_stop.frame_locked = true;
scale = 2*(_detection_range + _deceleration_range);
waypoint_marker_decelerate.scale.x = scale;
waypoint_marker_decelerate.scale.y = scale;
waypoint_marker_decelerate.scale.z = scale;
waypoint_marker_decelerate.color.a = 0.15;
waypoint_marker_decelerate.color.r = 1.0;
waypoint_marker_decelerate.color.g = 1.0;
waypoint_marker_decelerate.color.b = 0.0;
waypoint_marker_decelerate.frame_locked = true;
if (_obstacle_waypoint > -1) {
stop_line.pose.position = _path_dk.getWaypointPosition(_obstacle_waypoint);
stop_line.pose.orientation = _path_dk.getWaypointOrientation(_obstacle_waypoint);
}
stop_line.pose.position.z += 1.0;
stop_line.scale.x = 0.1;
stop_line.scale.y = 15.0;
stop_line.scale.z = 2.0;
stop_line.color.a = 0.3;
stop_line.color.r = 1.0;
stop_line.color.g = 0.0;
stop_line.color.b = 0.0;
stop_line.lifetime = ros::Duration(0.1);
stop_line.frame_locked = true;
if (crosswalk_id > 0)
scale = vmap.getDetectionPoints(crosswalk_id).width;
crosswalk_marker.scale.x = scale;
crosswalk_marker.scale.y = scale;
crosswalk_marker.scale.z = scale;
crosswalk_marker.color.a = 0.5;
crosswalk_marker.color.r = 0.0;
crosswalk_marker.color.g = 1.0;
crosswalk_marker.color.b = 0.0;
crosswalk_marker.frame_locked = true;
// set marker points coordinate
for (int i = 0; i < _search_distance; i++) {
if (num < 0 || i+num > _path_dk.getSize() - 1)
break;
geometry_msgs::Point point;
point = _path_dk.getWaypointPosition(num+i);
waypoint_marker_stop.points.push_back(point);
if (i > _deceleration_search_distance)
continue;
waypoint_marker_decelerate.points.push_back(point);
}
if (crosswalk_id > 0) {
for (const auto &p : vmap.getDetectionPoints(crosswalk_id).points)
crosswalk_marker.points.push_back(p);
}
// publish marker
marker_array.markers.push_back(crosswalk_marker);
marker_array.markers.push_back(waypoint_marker_stop);
marker_array.markers.push_back(waypoint_marker_decelerate);
if (kind == STOP)
marker_array.markers.push_back(stop_line);
_range_pub.publish(marker_array);
marker_array.markers.clear();
}
static int FindCrossWalk()
{
if (!vmap.set_points || _closest_waypoint < 0)
return -1;
double find_distance = 2.0*2.0; // meter
double ignore_distance = 20.0*20.0; // meter
// Find near cross walk
for (int num = _closest_waypoint; num < _closest_waypoint+_search_distance; num++) {
geometry_msgs::Point waypoint = _path_dk.getWaypointPosition(num);
waypoint.z = 0.0; // ignore Z axis
for (int i = 1; i < vmap.getSize(); i++) {
// ignore far crosswalk
geometry_msgs::Point crosswalk_center = vmap.getDetectionPoints(i).center;
crosswalk_center.z = 0.0;
if (CalcSquareOfLength(crosswalk_center, waypoint) > ignore_distance)
continue;
for (auto p : vmap.getDetectionPoints(i).points) {
p.z = waypoint.z;
if (CalcSquareOfLength(p, waypoint) < find_distance) {
vmap.setDetectionCrossWalkID(i);
return num;
}
}
}
}
vmap.setDetectionCrossWalkID(-1);
return -1; // no near crosswalk
}
static EControl CrossWalkDetection(const int &crosswalk_id)
{
double search_radius = vmap.getDetectionPoints(crosswalk_id).width / 2;
// Search each calculated points in the crosswalk
for (const auto &p : vmap.getDetectionPoints(crosswalk_id).points) {
geometry_msgs::Point detection_point = calcRelativeCoordinate(p, _current_pose.pose);
if (g_sim_mode)
detection_point = calcRelativeCoordinate(p, _sim_ndt_pose.pose);
tf::Vector3 detection_vector = point2vector(detection_point);
detection_vector.setZ(0.0);
int stop_count = 0; // the number of points in the detection area
for (const auto &vscan : _vscan) {
tf::Vector3 vscan_vector(vscan.x, vscan.y, 0.0);
double distance = tf::tfDistance(vscan_vector, detection_vector);
if (distance < search_radius) {
stop_count++;
geometry_msgs::Point vscan_temp;
vscan_temp.x = vscan.x;
vscan_temp.y = vscan.y;
vscan_temp.z = vscan.z;
if (g_sim_mode)
g_obstacle.setStopPoint(calcAbsoluteCoordinate(vscan_temp, _sim_ndt_pose.pose));
else
g_obstacle.setStopPoint(calcAbsoluteCoordinate(vscan_temp, _current_pose.pose));
}
if (stop_count > _threshold_points)
return STOP;
}
g_obstacle.clearStopPoints();
}
return KEEP; // find no obstacles
}
static EControl vscanDetection()
{
if (_vscan.empty() == true || _closest_waypoint < 0)
return KEEP;
int decelerate_or_stop = -10000;
int decelerate2stop_waypoints = 15;
for (int i = _closest_waypoint; i < _closest_waypoint + _search_distance; i++) {
g_obstacle.clearStopPoints();
if (!g_obstacle.isDecided())
g_obstacle.clearDeceleratePoints();
decelerate_or_stop++;
if (decelerate_or_stop > decelerate2stop_waypoints ||
(decelerate_or_stop >= 0 && i >= _path_dk.getSize()-1) ||
(decelerate_or_stop >= 0 && i == _closest_waypoint+_search_distance-1))
return DECELERATE;
if (i > _path_dk.getSize() - 1 )
return KEEP;
// Detection for cross walk
if (i == vmap.getDetectionWaypoint()) {
if (CrossWalkDetection(vmap.getDetectionCrossWalkID()) == STOP) {
_obstacle_waypoint = i;
return STOP;
}
}
// waypoint seen by vehicle
geometry_msgs::Point waypoint = calcRelativeCoordinate(_path_dk.getWaypointPosition(i),
_current_pose.pose);
tf::Vector3 tf_waypoint = point2vector(waypoint);
tf_waypoint.setZ(0);
int stop_point_count = 0;
int decelerate_point_count = 0;
for (pcl::PointCloud<pcl::PointXYZ>::const_iterator item = _vscan.begin(); item != _vscan.end(); item++) {
tf::Vector3 vscan_vector((double) item->x, (double) item->y, 0);
// for simulation
if (g_sim_mode) {
tf::Transform transform;
tf::poseMsgToTF(_sim_ndt_pose.pose, transform);
geometry_msgs::Point world2vscan = vector2point(transform * vscan_vector);
vscan_vector = point2vector(calcRelativeCoordinate(world2vscan, _current_pose.pose));
vscan_vector.setZ(0);
}
// 2D distance between waypoint and vscan points(obstacle)
// ---STOP OBSTACLE DETECTION---
double dt = tf::tfDistance(vscan_vector, tf_waypoint);
if (dt < _detection_range) {
stop_point_count++;
geometry_msgs::Point vscan_temp;
vscan_temp.x = item->x;
vscan_temp.y = item->y;
vscan_temp.z = item->z;
if (g_sim_mode)
g_obstacle.setStopPoint(calcAbsoluteCoordinate(vscan_temp, _sim_ndt_pose.pose));
else
g_obstacle.setStopPoint(calcAbsoluteCoordinate(vscan_temp, _current_pose.pose));
}
if (stop_point_count > _threshold_points) {
_obstacle_waypoint = i;
return STOP;
}
// without deceleration range
if (_deceleration_range < 0.01)
continue;
// deceleration search runs "decelerate_search_distance" waypoints from closest
if (i > _closest_waypoint+_deceleration_search_distance || decelerate_or_stop >= 0)
continue;
// ---DECELERATE OBSTACLE DETECTION---
if (dt > _detection_range && dt < _detection_range + _deceleration_range) {
bool count_flag = true;
// search overlaps between DETECTION range and DECELERATION range
for (int waypoint_search = -5; waypoint_search <= 5; waypoint_search++) {
if (i+waypoint_search < 0 || i+waypoint_search >= _path_dk.getSize() || !waypoint_search)
continue;
geometry_msgs::Point temp_waypoint = calcRelativeCoordinate(
_path_dk.getWaypointPosition(i+waypoint_search),
_current_pose.pose);
tf::Vector3 waypoint_vector = point2vector(temp_waypoint);
waypoint_vector.setZ(0);
// if there is a overlap, give priority to DETECTION range
if (tf::tfDistance(vscan_vector, waypoint_vector) < _detection_range) {
count_flag = false;
break;
}
}
if (count_flag) {
decelerate_point_count++;
geometry_msgs::Point vscan_temp;
vscan_temp.x = item->x;
vscan_temp.y = item->y;
vscan_temp.z = item->z;
if (g_sim_mode)
g_obstacle.setDeceleratePoint(calcAbsoluteCoordinate(vscan_temp, _sim_ndt_pose.pose));
else
g_obstacle.setDeceleratePoint(calcAbsoluteCoordinate(vscan_temp, _current_pose.pose));
}
}
// found obstacle to DECELERATE
if (decelerate_point_count > _threshold_points) {
_obstacle_waypoint = i;
decelerate_or_stop = 0; // for searching near STOP obstacle
g_obstacle.setDecided(true);
}
}
}
return KEEP; //no obstacles
}
static void SoundPlay()
{
std_msgs::String string;
string.data = pedestrian_sound;
_sound_pub.publish(string);
}
static EControl ObstacleDetection()
{
static int false_count = 0;
static EControl prev_detection = KEEP;
std::cout << "closest_waypoint : " << _closest_waypoint << std::endl;
std::cout << "current_velocity : " << mps2kmph(_current_vel) << std::endl;
EControl vscan_result = vscanDetection();
DisplayDetectionRange(vmap.getDetectionCrossWalkID(), _closest_waypoint, vscan_result);
if (prev_detection == KEEP) {
if (vscan_result != KEEP) { // found obstacle
DisplayObstacle(vscan_result);
std::cout << "obstacle waypoint : " << _obstacle_waypoint << std::endl << std::endl;
prev_detection = vscan_result;
//SoundPlay();
false_count = 0;
return vscan_result;
} else { // no obstacle
prev_detection = KEEP;
return vscan_result;
}
} else { //prev_detection = STOP or DECELERATE
if (vscan_result != KEEP) { // found obstacle
DisplayObstacle(vscan_result);
std::cout << "obstacle waypoint : " << vscan_result << std::endl << std::endl;
prev_detection = vscan_result;
false_count = 0;
return vscan_result;
} else { // no obstacle
false_count++;
std::cout << "false_count : "<< false_count << std::endl;
//fail-safe
if (false_count >= LOOP_RATE/2) {
_obstacle_waypoint = -1;
false_count = 0;
prev_detection = KEEP;
return vscan_result;
} else {
std::cout << "obstacle waypoint : " << _obstacle_waypoint << std::endl << std::endl;
DisplayObstacle(OTHERS);
return prev_detection;
}
}
}
}
static void ChangeWaypoint(EControl detection_result)
{
int obs = _obstacle_waypoint;
if (obs != -1){
std::cout << "====got obstacle waypoint====" << std::endl;
std::cout << "=============================" << std::endl;
}
if (detection_result == STOP){ // STOP for obstacle
// stop_waypoint is about _others_distance meter away from obstacles
int stop_waypoint = obs - ((int)(_others_distance / _path_change.getInterval()));
std::cout << "stop_waypoint: " << stop_waypoint << std::endl;
// change waypoints to stop by the stop_waypoint
_path_change.changeWaypoints(stop_waypoint);
_path_change.avoidSuddenBraking();
_path_change.setTemporalWaypoints();
_temporal_waypoints_pub.publish(_path_change.getTemporalWaypoints());
} else if (detection_result == DECELERATE) { // DECELERATE for obstacles
_path_change.setPath(_path_dk.getCurrentWaypoints());
_path_change.setDeceleration();
_path_change.setTemporalWaypoints();
_temporal_waypoints_pub.publish(_path_change.getTemporalWaypoints());
} else { // ACELERATE or KEEP
_path_change.setPath(_path_dk.getCurrentWaypoints());
_path_change.avoidSuddenAceleration();
_path_change.avoidSuddenBraking();
_path_change.setTemporalWaypoints();
_temporal_waypoints_pub.publish(_path_change.getTemporalWaypoints());
}
return;
}
//======================================
// main
//======================================
int main(int argc, char **argv)
{
int i = 0;///
ros::init(argc, argv, "velocity_set");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
ros::Subscriber localizer_sub = nh.subscribe("localizer_pose", 1, LocalizerCallback);
ros::Subscriber control_pose_sub = nh.subscribe("control_pose", 1, ControlCallback);
ros::Subscriber odometry_subscriber = nh.subscribe("odom_pose", 10, OdometryPoseCallback);
ros::Subscriber vscan_sub = nh.subscribe("vscan_points", 1, VscanCallback);
ros::Subscriber base_waypoint_sub = nh.subscribe("base_waypoints", 1, BaseWaypointCallback);
ros::Subscriber obj_pose_sub = nh.subscribe("obj_pose", 1, ObjPoseCallback);
ros::Subscriber estimated_vel_sub = nh.subscribe("estimated_vel_mps", 1, EstimatedVelCallback);
ros::Subscriber config_sub = nh.subscribe("config/velocity_set", 10, ConfigCallback);
//------------------ Vector Map ----------------------//
ros::Subscriber sub_dtlane = nh.subscribe("vector_map_info/cross_walk", 1,
&CrossWalk::CrossWalkCallback, &vmap);
ros::Subscriber sub_area = nh.subscribe("vector_map_info/area_class", 1,
&CrossWalk::AreaclassCallback, &vmap);
ros::Subscriber sub_line = nh.subscribe("vector_map_info/line_class", 1,
&CrossWalk::LineclassCallback, &vmap);
ros::Subscriber sub_point = nh.subscribe("vector_map_info/point_class", 1,
&CrossWalk::PointclassCallback, &vmap);
//----------------------------------------------------//
_range_pub = nh.advertise<visualization_msgs::MarkerArray>("detection_range", 0);
_sound_pub = nh.advertise<std_msgs::String>("sound_player", 10);
_temporal_waypoints_pub = nh.advertise<waypoint_follower::lane>("temporal_waypoints", 1000, true);
static ros::Publisher closest_waypoint_pub;
closest_waypoint_pub = nh.advertise<std_msgs::Int32>("closest_waypoint", 1000);
_obstacle_pub = nh.advertise<visualization_msgs::Marker>("obstacle", 0);
private_nh.param<bool>("sim_mode", g_sim_mode, false);
ROS_INFO_STREAM("sim_mode : " << g_sim_mode);
ros::Rate loop_rate(LOOP_RATE);
while (ros::ok()) {
ros::spinOnce();
if (vmap.loaded_all && !vmap.set_points)
vmap.setCrossWalkPoints();
if (_pose_flag == false || _path_flag == false) {
std::cout << "\rtopic waiting \rtopic waiting";
for (int j = 0; j < i; j++) {std::cout << ".";}
i++;
i = i%10;
std::cout << std::flush;
loop_rate.sleep();
continue;
}
_closest_waypoint = getClosestWaypoint(_path_change.getCurrentWaypoints(), _current_pose.pose);
closest_waypoint_pub.publish(_closest_waypoint);
vmap.setDetectionWaypoint(FindCrossWalk());
EControl detection_result = ObstacleDetection();
ChangeWaypoint(detection_result);
loop_rate.sleep();
}
return 0;
}
| 32.923077 | 120 | 0.692741 | [
"vector",
"transform"
] |
1c14521aeeb72c2b41ff19617ac834ca97c2fcd3 | 19,664 | cpp | C++ | src/server_state.cpp | f-list/fserv | 8be87d74410321834f5758d567a101df65c9bceb | [
"BSD-2-Clause"
] | 9 | 2015-09-12T16:09:34.000Z | 2019-06-07T23:35:57.000Z | src/server_state.cpp | f-list/fserv | 8be87d74410321834f5758d567a101df65c9bceb | [
"BSD-2-Clause"
] | 17 | 2015-01-18T08:10:26.000Z | 2018-07-26T09:59:43.000Z | src/server_state.cpp | f-list/fserv | 8be87d74410321834f5758d567a101df65c9bceb | [
"BSD-2-Clause"
] | 7 | 2015-04-07T17:53:33.000Z | 2017-12-26T19:40:38.000Z | /*
* Copyright (c) 2011-2013, "Kira"
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "precompiled_headers.hpp"
#include "server_state.hpp"
#include "channel.hpp"
#include "fjson.hpp"
#include "logging.hpp"
#include "redis.hpp"
#include "server.hpp"
#include "sha1.hpp"
#include <string>
#include <iostream>
#include <fstream>
conptrmap_t ServerState::connectionMap;
concountmap_t ServerState::connectionCountMap;
chanptrmap_t ServerState::channelMap;
conptrlist_t ServerState::unidentifiedList;
oplist_t ServerState::opList;
banlist_t ServerState::banList;
timeoutmap_t ServerState::timeoutList;
altwatchmap_t ServerState::altWatchList;
staffcallmap_t ServerState::staffCallList;
chanoplist_t ServerState::channelOpList;
conptrset_t ServerState::staffCallTargets;
scopset_t ServerState::superCopList;
long ServerState::userCount = 0;
long ServerState::maxUserCount = 0;
long ServerState::channelSeed = 0;
bool ServerState::fsaveFile(const char* name, string& contents) {
std::ofstream file;
file.open(name, std::ios::trunc);
if (file.is_open()) {
file << contents;
} else {
LOG(WARNING) << "Failed to open file " << name << " for writing.";
return false;
}
file.close();
return true;
}
string ServerState::floadFile(const char* name) {
std::string contents;
std::string buffer;
std::ifstream file(name);
while (file.good()) {
std::getline(file, buffer);
contents.append(buffer);
}
file.close();
return contents;
}
void ServerState::loadChannels() {
DLOG(INFO) << "Loading channels.";
string contents = floadFile("./channels.json");
json_error_t jserror;
json_t* root = json_loads(contents.c_str(), 0, &jserror);
if (!root) {
LOG(ERROR) << "Failed to parse channel json. Error: " << &jserror.text;
return;
}
json_t* pubchans = json_object_get(root, "public");
if (!json_is_array(pubchans)) {
LOG(ERROR) << "Failed to find the public channels node.";
return;
}
size_t size = json_array_size(pubchans);
for (size_t i = 0; i < size; ++i) {
json_t* chan = json_array_get(pubchans, i);
string name = json_string_value(json_object_get(chan, "name"));
removeChannel(name);
Channel* chanptr = new Channel(name, CT_PUBLIC);
chanptr->loadChannel(chan);
addChannel(name, chanptr);
}
json_t* privchans = json_object_get(root, "private");
if (!json_is_array(privchans)) {
LOG(ERROR) << "Failed to find the private channels node.";
return;
}
size = json_array_size(privchans);
for (size_t i = 0; i < size; ++i) {
json_t* chan = json_array_get(privchans, i);
string name = json_string_value(json_object_get(chan, "name"));
removeChannel(name);
Channel* chanptr = new Channel(name, CT_PUBPRIVATE);
chanptr->loadChannel(chan);
addChannel(name, chanptr);
}
json_decref(root);
}
void ServerState::saveChannels() {
DLOG(INFO) << "Saving channels.";
json_t* root = json_object();
json_t* publicarray = json_array();
json_t* privatearray = json_array();
for (chanptrmap_t::const_iterator i = channelMap.begin(); i != channelMap.end(); ++i) {
ChannelPtr chan = i->second;
if (chan->getType() == CT_PUBLIC) {
json_array_append_new(publicarray, chan->saveChannel());
} else if (chan->getType() == CT_PUBPRIVATE) {
json_array_append_new(privatearray, chan->saveChannel());
}
}
json_object_set_new_nocheck(root, "public", publicarray);
json_object_set_new_nocheck(root, "private", privatearray);
const char* chanstr = json_dumps(root, JSON_INDENT(4));
string contents = chanstr;
free((void*) chanstr);
json_decref(root);
fsaveFile("./channels.json", contents);
}
void ServerState::cleanupChannels() {
chanptrmap_t chans = getChannels();
chans.clear();
}
void ServerState::removeUnusedChannels() {
const chanptrmap_t chans = getChannels();
list<string> toremove;
time_t timeout = time(NULL)-(60 * 60 * 24);
for (chanptrmap_t::const_iterator i = chans.begin(); i != chans.end(); ++i) {
i->second->updateParticipantCount();
if (i->second->getType() == CT_PUBPRIVATE) {
if ((i->second->getParticipantCount() <= 0) && (i->second->getLastActivity() < timeout)) {
toremove.push_back(i->first);
}
}
}
for (list<string>::const_iterator i = toremove.begin(); i != toremove.end(); ++i) {
string channel = (*i);
removeChannel(channel);
}
DLOG(INFO) << "Removed " << toremove.size() << " unused channels.";
}
void ServerState::loadStringList(string filename, stringFunctionTarget target, clearFunction clear) {
string contents = floadFile(filename.c_str());
json_error_t jserror;
json_t* root = json_loads(contents.c_str(), 0, &jserror);
if (!json_is_array(root)) {
LOG(WARNING) << "Failed to parse the ops list json. Error: " << jserror.text;
return;
}
clear();
size_t size = json_array_size(root);
for (size_t i = 0; i < size; ++i) {
json_t* jop = json_array_get(root, i);
if (!json_is_string(jop)) {
LOG(WARNING) << "Failed to parse an op value because it was not a string.";
continue;
}
string op = json_string_value(jop);
target(op);
}
json_decref(root);
}
void ServerState::loadOps() {
DLOG(INFO) << "Loading ops.";
loadStringList("./ops.json", &addOp, &clearOps);
DLOG(INFO) << "Loading super cops.";
loadStringList("./scops.json", &addSuperCop, &clearSuperCops);
}
void ServerState::saveSCops() {
DLOG(INFO) << "Saving super cops.";
json_t* root = json_array();
for(auto itr = superCopList.begin(); itr != superCopList.end(); ++itr) {
json_array_append_new(root, json_string_nocheck(itr->c_str()));
}
const char* opstr = json_dumps(root, JSON_INDENT(4));
string contents = opstr;
free((void*) opstr);
json_decref(root);
fsaveFile("./scops.json", contents);
}
void ServerState::saveOps() {
DLOG(INFO) << "Saving ops.";
json_t* root = json_array();
for (oplist_t::const_iterator i = opList.begin(); i != opList.end(); ++i) {
json_array_append_new(root, json_string_nocheck(i->c_str()));
}
const char* opstr = json_dumps(root, JSON_INDENT(4));
string contents = opstr;
free((void*) opstr);
json_decref(root);
fsaveFile("./ops.json", contents);
saveSCops();
}
void ServerState::loadBans() {
DLOG(INFO) << "Loading bans.";
string contents = floadFile("./bans.json");
json_t* root = json_loads(contents.c_str(), 0, 0);
if (!json_is_object(root)) {
LOG(WARNING) << "Could not load the ban list from disk.";
return;
}
json_t* bans = json_object_get(root, "bans");
if (!json_is_array(bans)) {
LOG(WARNING) << "Could not find the bans node for the ban list.";
return;
}
size_t size = json_array_size(bans);
for (size_t i = 0; i < size; ++i) {
json_t* ban = json_array_get(bans, i);
if (!json_is_object(ban)) {
LOG(WARNING) << "Ban node is not an object.";
continue;
}
json_t* banid = json_object_get(ban, "id");
if (!json_is_integer(banid)) {
LOG(WARNING) << "Ban failed to parse because the ban id was not an integer.";
continue;
}
json_t* banchar = json_object_get(ban, "character");
if (!json_is_string(banchar)) {
LOG(WARNING) << "Ban failed to parse because the ban character was not a string.";
continue;
}
banList[json_integer_value(banid)] = json_string_value(banchar);
}
json_t* timeouts = json_object_get(root, "timeouts");
if (!json_is_array(timeouts)) {
LOG(ERROR) << "Could not find the timeouts node for the ban list.";
return;
}
size = json_array_size(timeouts);
for (size_t i = 0; i < size; ++i) {
json_t* timeout = json_array_get(timeouts, i);
if (!json_is_object(timeout)) {
LOG(WARNING) << "Timeout node is not an object.";
continue;
}
TimeoutRecord to;
json_t* tochar = json_object_get(timeout, "character");
if (!json_is_string(tochar)) {
LOG(WARNING) << "Timeout character is not a string.";
continue;
}
json_t* toend = json_object_get(timeout, "end");
if (!json_is_integer(toend)) {
LOG(WARNING) << "Timeout end is not an integer.";
continue;
}
json_t* toid = json_object_get(timeout, "id");
if (!json_is_integer(toid)) {
LOG(WARNING) << "Timeout id is not an integer.";
continue;
}
to.character = json_string_value(tochar);
to.end = json_integer_value(toend);
timeoutList[json_integer_value(toid)] = to;
}
json_decref(root);
}
void ServerState::saveBans() {
DLOG(INFO) << "Saving bans.";
for (timeoutmap_t::iterator i = timeoutList.begin(); i != timeoutList.end(); ) {
if (i->second.end < time(0)) {
timeoutList.erase(i++);
} else {
++i;
}
}
json_t* root = json_object();
json_t* array = json_array();
for (banlist_t::const_iterator i = banList.begin(); i != banList.end(); ++i) {
json_t* ban = json_object();
json_object_set_new_nocheck(ban, "id",
json_integer(i->first)
);
json_object_set_new_nocheck(ban, "character",
json_string_nocheck(i->second.c_str())
);
json_array_append_new(array, ban);
}
json_object_set_new_nocheck(root, "bans", array);
array = json_array();
for (timeoutmap_t::const_iterator i = timeoutList.begin(); i != timeoutList.end(); ++i) {
json_t* timeout = json_object();
json_object_set_new_nocheck(timeout, "id",
json_integer(i->first)
);
json_object_set_new_nocheck(timeout, "end",
json_integer(i->second.end)
);
json_object_set_new_nocheck(timeout, "character",
json_string_nocheck(i->second.character.c_str())
);
json_array_append_new(array, timeout);
}
json_object_set_new_nocheck(root, "timeouts", array);
const char* banstr = json_dumps(root, JSON_INDENT(4));
string contents = banstr;
free((void*) banstr);
json_decref(root);
fsaveFile("./bans.json", contents);
}
void ServerState::sendUserListToRedis() {
RedisRequest* req = new RedisRequest;
req->key = Redis::onlineUsersKey;
req->method = REDIS_DEL;
req->updateContext = RCONTEXT_ONLINE;
if (!Redis::addRequest(req)) {
delete req;
return;
}
req = new RedisRequest;
req->key = Redis::onlineUsersKey;
req->method = REDIS_SADD;
req->updateContext = RCONTEXT_ONLINE;
for (conptrmap_t::const_iterator i = connectionMap.begin(); i != connectionMap.end(); ++i) {
req->values.push(i->second->characterName);
}
if (!Redis::addRequest(req))
delete req;
}
void ServerState::addUnidentified(ConnectionPtr con) {
unidentifiedList.push_back(con);
}
void ServerState::removedUnidentified(ConnectionPtr con) {
unidentifiedList.remove(con);
}
void ServerState::addConnection(string& name, ConnectionPtr con) {
connectionCountMap[(int) con->clientAddress.sin_addr.s_addr] += 1;
//DLOG(INFO) << "IP " << (int)con->clientAddress.sin_addr.s_addr << " now has " << connectionCountMap[(int)con->clientAddress.sin_addr.s_addr] << " connections.";
connectionMap[name] = con;
++userCount;
if (userCount > maxUserCount)
maxUserCount = userCount;
}
void ServerState::removeConnection(string& name) {
if (connectionMap.find(name) != connectionMap.end()) {
int addr = (int) connectionMap[name]->clientAddress.sin_addr.s_addr;
connectionCountMap[addr] -= 1;
//DLOG(INFO) << "IP " << addr << " now has " << connectionCountMap[addr] << " connections.";
if (connectionCountMap[addr] <= 0) {
//DLOG(INFO) << "IP " << addr << " has been removed because it no longer has any connections.";
connectionCountMap.erase(addr);
}
// Need to remove staff call target if there is one, or connections get leaked..
staffCallTargets.erase(connectionMap[name]);
connectionMap.erase(name);
--userCount;
}
}
ConnectionPtr ServerState::getConnection(string& name) {
if (connectionMap.find(name) != connectionMap.end())
return connectionMap[name];
return 0;
}
const int ServerState::getConnectionIPCount(ConnectionPtr con) {
return connectionCountMap[(int) con->clientAddress.sin_addr.s_addr];
}
string ServerState::generatePrivateChannelID(ConnectionPtr con, string& title) {
while (true) {
char buf[1024];
bzero(&buf[0], sizeof (buf));
int size = snprintf(&buf[0], sizeof (buf), "%s%s%f%ld", title.c_str(),
con->characterName.c_str(), (float) Server::getEventTime(),
++ServerState::channelSeed);
string namehash(&buf[0], size);
bzero(&buf[0], sizeof (buf));
namehash = thirdparty::SHA1HashString(namehash);
snprintf(&buf[0], sizeof (buf), "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
(unsigned char) namehash[0], (unsigned char) namehash[1],
(unsigned char) namehash[2], (unsigned char) namehash[3],
(unsigned char) namehash[4], (unsigned char) namehash[5],
(unsigned char) namehash[6], (unsigned char) namehash[7],
(unsigned char) namehash[8], (unsigned char) namehash[9]);
namehash = string(&buf[0], 20);
namehash = "ADH-" + namehash;
string lname = namehash;
int nameSize = lname.size();
for (int i = 0; i < nameSize; ++i) {
lname[i] = (char) tolower(lname[i]);
}
Channel* chan = ServerState::getChannel(lname).get();
if (chan == 0) {
return namehash;
}
}
}
void ServerState::addChannel(string& name, Channel* channel) {
string lname = name;
int size = lname.size();
for (int i = 0; i < size; ++i) {
lname[i] = (char) tolower(lname[i]);
}
ChannelPtr chan(channel);
channelMap[lname] = chan;
}
void ServerState::removeChannel(string& name) {
if (channelMap.find(name) != channelMap.end()) {
channelMap.erase(name);
}
}
ChannelPtr ServerState::getChannel(string& name) {
if (channelMap.find(name) != channelMap.end())
return channelMap[name];
return 0;
}
void ServerState::addOp(string& op) {
opList.insert(op);
}
void ServerState::removeOp(string& op) {
opList.erase(op);
}
bool ServerState::isOp(string& op) {
return opList.count(op) > 0;
}
void ServerState::addBan(string& character, long accountid) {
banList[accountid] = character;
}
bool ServerState::removeBan(string& character) {
for (banlist_t::iterator i = banList.begin(); i != banList.end(); ++i) {
if (i->second == character) {
banList.erase(i);
return true;
}
}
return false;
}
bool ServerState::isBanned(long accountid) {
return banList.count(accountid) > 0;
}
void ServerState::addTimeout(string& character, long accountid, int length) {
TimeoutRecord to;
to.character = character;
to.end = time(0) + length;
timeoutList[accountid] = to;
}
void ServerState::removeTimeout(string& character) {
for (timeoutmap_t::iterator i = timeoutList.begin(); i != timeoutList.end(); ++i) {
if (i->second.character == character) {
timeoutList.erase(i);
return;
}
}
}
bool ServerState::isTimedOut(long accountid, int& end) {
if (timeoutList.find(accountid) != timeoutList.end()) {
end = timeoutList[accountid].end;
return true;
}
return false;
}
void ServerState::addAltWatch(long accountid, AltWatchRecord& record) {
altWatchList[accountid] = record;
}
void ServerState::removeAltWatch(long accountid) {
altWatchList.erase(accountid);
}
AltWatchRecord ServerState::getAltWatch(long int accountid) {
if (altWatchList.find(accountid) != altWatchList.end())
return altWatchList[accountid];
AltWatchRecord record;
record.account_id = 0;
record.end = 0;
return record;
}
void ServerState::cleanAltWatchList() {
time_t now = time(NULL);
list<long> to_erase;
for (altwatchmap_t::const_iterator i = altWatchList.begin(); i != altWatchList.end(); ++i) {
if (i->second.end < now)
to_erase.push_back(i->first);
}
for (list<long>::const_iterator i = to_erase.begin(); i != to_erase.end(); ++i) {
altWatchList.erase(*i);
}
}
void ServerState::addStaffCall(string& callid, StaffCallRecord& record) {
staffCallList[callid] = record;
}
void ServerState::removeStaffCall(string& callid) {
staffCallList.erase(callid);
}
StaffCallRecord ServerState::getStaffCall(string& callid) {
if (staffCallList.find(callid) != staffCallList.end())
return staffCallList[callid];
StaffCallRecord record;
record.action = "invalid";
return record;
}
void ServerState::addStaffCallTarget(ConnectionPtr con) {
staffCallTargets.insert(con);
}
void ServerState::removeStaffCallTarget(ConnectionPtr con) {
staffCallTargets.erase(con);
}
void ServerState::rebuildChannelOpList() {
channelOpList.clear();
const chanptrmap_t chans = getChannels();
for (chanptrmap_t::const_iterator i = chans.begin(); i != chans.end(); ++i) {
if (i->second->getType() == CT_PUBLIC) {
ChannelPtr chan = i->second;
const chmodmap_t mods = chan->getModRecords();
for (chmodmap_t::const_iterator m = mods.begin(); m != mods.end(); ++m) {
if (m->first != "") {
channelOpList.insert(m->first);
}
}
}
}
}
bool ServerState::isChannelOp(string& name) {
return channelOpList.count(name) > 0;
}
| 33.671233 | 166 | 0.630238 | [
"object"
] |
1c14cc26b07509ab6e0793d6b0b3ef0155d8663a | 637 | cpp | C++ | codeforces/round-255/div-2/dzy_loves_hash.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | codeforces/round-255/div-2/dzy_loves_hash.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | codeforces/round-255/div-2/dzy_loves_hash.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
#include <vector>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int buckets;
unsigned int numbers;
cin >> buckets >> numbers;
vector<bool> is_full(buckets);
for (unsigned int i {0}; i < numbers; ++i)
{
unsigned int number;
cin >> number;
if (is_full[number % buckets])
{
cout << i + 1 << '\n';
return 0;
}
is_full[number % buckets] = true;
}
cout << -1 << '\n';
return 0;
}
| 15.166667 | 46 | 0.540031 | [
"vector"
] |
1c2d4f62a1735827268cbb8854810c8cf993a99c | 4,728 | hpp | C++ | src/method/method_invoke.hpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/method/method_invoke.hpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/method/method_invoke.hpp | Yechan0815/cubrid | da09d9e60b583d0b7ce5f665429f397976728d99 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
*
* Copyright 2016 CUBRID Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _METHOD_INVOKE_HPP_
#define _METHOD_INVOKE_HPP_
#ident "$Id$"
#if !defined (SERVER_MODE) && !defined (SA_MODE)
#error Belongs to server module
#endif /* !defined (SERVER_MODE) && !defined (SA_MODE) */
#include <vector>
#include <unordered_map>
#include <queue>
#include "dbtype.h" /* db_value_* */
#include "method_def.hpp" /* method_sig_node */
#include "method_query_cursor.hpp"
#include "method_struct_invoke.hpp" /* cubmethod::header */
#include "mem_block.hpp" /* cubmem::block, cubmem::extensible_block */
#include "porting.h" /* SOCKET */
#if defined (SA_MODE)
#include "query_method.hpp"
#endif
// thread_entry.hpp
namespace cubthread
{
class entry;
}
namespace cubmethod
{
// forward declarations
class method_invoke_group;
class method_invoke
{
public:
method_invoke () = delete; // Not DefaultConstructible
method_invoke (method_invoke_group *group, method_sig_node *sig) : m_group (group), m_method_sig (sig) {}
virtual ~method_invoke () {};
method_invoke (method_invoke &&other) = delete; // Not MoveConstructible
method_invoke (const method_invoke ©) = delete; // Not CopyConstructible
method_invoke &operator= (method_invoke &&other) = delete; // Not MoveAssignable
method_invoke &operator= (const method_invoke ©) = delete; // Not CopyAssignable
virtual int invoke (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base) = 0;
virtual int get_return (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base,
DB_VALUE &result) = 0;
uint64_t get_id ()
{
return (uint64_t) this;
}
protected:
method_invoke_group *m_group;
method_sig_node *m_method_sig;
};
class method_invoke_builtin : public method_invoke
{
public:
method_invoke_builtin () = delete;
method_invoke_builtin (method_invoke_group *group, method_sig_node *method_sig);
int invoke (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base) override;
int get_return (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base,
DB_VALUE &result) override;
};
class method_invoke_java : public method_invoke
{
public:
method_invoke_java () = delete;
method_invoke_java (method_invoke_group *group, method_sig_node *method_sig);
~method_invoke_java ();
int invoke (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base) override;
int get_return (cubthread::entry *thread_p, std::vector<std::reference_wrapper<DB_VALUE>> &arg_base,
DB_VALUE &result) override;
private:
int alloc_response (cubthread::entry *thread_p);
int receive_result (std::vector<std::reference_wrapper<DB_VALUE>> &arg_base,
DB_VALUE &returnval);
int receive_error ();
int callback_dispatch (cubthread::entry &thread_ref);
int callback_get_db_parameter (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_prepare (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_execute (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_fetch (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_oid_get (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_oid_put (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_oid_cmd (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_collection_cmd (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_make_outresult (cubthread::entry &thread_ref, packing_unpacker &unpacker);
int callback_get_generated_keys (cubthread::entry &thread_ref, packing_unpacker &unpacker);
void erase_query_cursor (const std::uint64_t query_id);
static int bypass_block (SOCKET socket, cubmem::block &b);
cubmethod::header *m_header;
};
} // namespace cubmethod
#endif /* _METHOD_INVOKE_HPP_ */
| 35.818182 | 115 | 0.721447 | [
"vector"
] |
1c33788388d89377a30dc74eaad8cbff164ebe8c | 1,306 | cpp | C++ | mhscript/commands/ScriptBlock.cpp | Mishin870/MHSCpp | 14be871a18cb9ea8fe915671c1110922f0037f33 | [
"MIT"
] | null | null | null | mhscript/commands/ScriptBlock.cpp | Mishin870/MHSCpp | 14be871a18cb9ea8fe915671c1110922f0037f33 | [
"MIT"
] | null | null | null | mhscript/commands/ScriptBlock.cpp | Mishin870/MHSCpp | 14be871a18cb9ea8fe915671c1110922f0037f33 | [
"MIT"
] | null | null | null | //
// Created by Mishin870 on 28.07.2018.
//
#include "ScriptBlock.h"
#include "../engine/ScriptLoader.h"
#include "ScriptUtils.h"
ScriptBlock::ScriptBlock(Stream *stream) {
this->commands = loadBlock(stream, this->commandsCount);
this->isRoot = stream->readByte() == 1;
if (this->isRoot) {
this->functionsCount = stream->readInt();
this->functions = new LocalFunction*[this->functionsCount];
unsigned int i;
for (i = 0; i < this->functionsCount; i++) {
this->functions[i] = new LocalFunction(stream);
}
} else {
this->functionsCount = 0;
this->functions = nullptr;
}
}
ScriptBlock::~ScriptBlock() {
unsigned int i;
for (i = 0; i < this->commandsCount; i++) {
delete this->commands[i];
}
delete[] this->commands;
if (this->isRoot) {
for (i = 0; i < this->functionsCount; i++) {
delete this->functions[i];
}
delete[] this->functions;
}
}
Object *ScriptBlock::execute(Engine *engine) {
unsigned int i;
if (this->isRoot) {
for (i = 0; i < this->functionsCount; i++) {
LocalFunction* function = this->functions[i];
engine->setLocalFunction(function->getName(), function);
}
}
for (i = 0; i < this->commandsCount; i++) {
executeVoid(this->commands[i], engine);
}
return nullptr;
}
CommandType ScriptBlock::getType() {
return CT_SCRIPT_BLOCK;
}
| 22.517241 | 61 | 0.653905 | [
"object"
] |
1c3db3a1756a3155cf5c7c5b3f40539896f0a2bd | 12,455 | cpp | C++ | src/battle_map.cpp | Turtwiggy/Dwarf-and-Blade | 2e3bd3eb169bf3b62665d74437f806d52c415fb5 | [
"MIT"
] | null | null | null | src/battle_map.cpp | Turtwiggy/Dwarf-and-Blade | 2e3bd3eb169bf3b62665d74437f806d52c415fb5 | [
"MIT"
] | null | null | null | src/battle_map.cpp | Turtwiggy/Dwarf-and-Blade | 2e3bd3eb169bf3b62665d74437f806d52c415fb5 | [
"MIT"
] | null | null | null | #include "battle_map.hpp"
#include "battle_map_ai.hpp"
entt::entity battle_map::create_battle(entt::registry& registry, random_state& rng, vec2i dim, level_info::types type)
{
entt::entity res = registry.create();
tilemap tmap;
tmap.create(dim);
//Create background tiles
{
for (int y = 0; y < dim.y(); y++)
{
for (int x = 0; x < dim.x(); x++)
{
sprite_handle handle = get_sprite_handle_of(rng, tiles::BASE);
//handle.base_colour = clamp(rand_det_s(rng.rng, 0.7, 1.3) * handle.base_colour * 0.1, 0, 1);
//handle.base_colour.w() = 1;
tilemap_position tmap_pos;
tmap_pos.pos = vec2i{ x, y };
render_descriptor desc;
desc.pos = camera::tile_to_world(vec2f{ tmap_pos.pos.x(), tmap_pos.pos.y() });
desc.depress_on_hover = true;
//desc.angle = rand_det_s(rng.rng, 0.f, 2 * M_PI);
entt::entity base = registry.create();
registry.assign<sprite_handle>(base, handle);
registry.assign<tilemap_position>(base, tmap_pos);
registry.assign<render_descriptor>(base, desc);
registry.assign<battle_tag>(base, battle_tag());
//registry.assign<mouse_interactable>(base, mouse_interactable());
tmap.add(base, { x, y });
}
}
}
//Decor
std::vector<tiles::type> decoration =
{
tiles::GRASS
};
//distribute_entities(registry, tmap, rng, dim, type, 20, decoration, 0);
//Scenery
std::vector<tiles::type> scenery =
{
tiles::TREE_1, tiles::TREE_2, tiles::TREE_ROUND, tiles::ROCKS, tiles::BRAMBLE
};
//distribute_entities(registry, tmap, rng, dim, type, 1, scenery, -1);
registry.assign<tilemap>(res, tmap);
registry.assign<battle_tag>(res, battle_tag());
registry.assign<battle_map_state>(res, battle_map_state());
return res;
}
void battle_map::distribute_entities(entt::registry& registry, tilemap& tmap, random_state& rng, vec2i dim, level_info::types type, int percentage, const std::vector<tiles::type>& scenery, float path_cost)
{
for (int y = 0; y < dim.y(); y++)
{
for (int x = 0; x < dim.x(); x++)
{
if (!(rand_det_s(rng.rng, 0, 100) < percentage))
continue;
int random_element = rand_det_s(rng.rng, 0.f, scenery.size());
random_element = clamp(random_element, 0, (int)scenery.size() - 1);
tiles::type type = scenery[random_element];
sprite_handle handle = get_sprite_handle_of(rng, type);
handle.base_colour.w() = 1;
tilemap_position trans;
trans.pos = vec2i{ x, y };
collidable coll;
coll.cost = path_cost;
auto base = create_scenery(registry, handle, trans, coll);
tmap.add(base, { x, y });
}
}
}
entt::entity battle_map::create_battle_unit(entt::registry& registry, sprite_handle handle, tilemap_position transform, team t)
{
entt::entity res = registry.create();
render_descriptor desc;
desc.pos = camera::tile_to_world(vec2f{ transform.pos.x(), transform.pos.y() });
desc.depress_on_hover = true;
registry.assign<sprite_handle>(res, handle);
registry.assign<render_descriptor>(res, desc);
registry.assign<tilemap_position>(res, transform);
registry.assign<mouse_interactable>(res, mouse_interactable());
damageable d;
d.max_hp = 10;
d.cur_hp = d.max_hp;
registry.assign<damageable>(res, d);
registry.assign<team>(res, t);
battle_unit_info info;
info.damage = 10;
registry.assign<battle_unit_info>(res, info);
registry.assign<battle_tag>(res, battle_tag());
return res;
}
entt::entity create_battle_unit_at(entt::registry& registry, random_state& rng, vec2i pos, int team_id)
{
tilemap_position transform;
transform.pos = pos;
team base_team;
base_team.type = team::NUMERIC;
base_team.t = team_id;
sprite_handle handle = get_sprite_handle_of(rng, tiles::SOLDIER_SPEAR);
handle.base_colour *= team::colours.at(team_id);
entt::entity unit = battle_map::create_battle_unit(registry, handle, transform, base_team);
return unit;
}
entt::entity battle_map::create_obstacle(entt::registry& registry, sprite_handle handle, tilemap_position transform, int path_cost)
{
entt::entity res = registry.create();
render_descriptor desc;
desc.pos = camera::tile_to_world(vec2f{ transform.pos.x(), transform.pos.y() });
desc.depress_on_hover = true;
registry.assign<sprite_handle>(res, handle);
registry.assign<render_descriptor>(res, desc);
registry.assign<mouse_interactable>(res, mouse_interactable());
collidable c;
c.cost = path_cost;
registry.assign<collidable>(res, c);
// registry.assign<battle_unit>(res, battle_unit());
return res;
}
entt::entity create_obstacle_at(entt::registry& registry, random_state& rng, vec2i pos, tilemap& map, sprite_handle handle, int path_cost)
{
tilemap_position transform;
transform.pos = pos;
entt::entity obstacle = battle_map::create_obstacle(registry, handle, transform, path_cost);
map.add(obstacle, pos);
}
void battle_map::battle_map_state::update_ai(entt::registry& registry, entt::entity& map, float delta_time, random_state& rng)
{
auto view = registry.view<battle_tag, tilemap_position, render_descriptor, sprite_handle, wandering_ai> ();
tilemap& tmap = registry.get<tilemap>(map);
for (auto ent : view)
{
auto& ai = view.get<wandering_ai>(ent);
auto& desc = view.get<render_descriptor>(ent);
ai.tick_ai(registry, delta_time, tmap, ent, rng);
ai.tick_animation(delta_time, desc);
}
}
void battle_map::battle_map_state::battle_editor(entt::registry& registry, entt::entity& map, random_state& rng, render_window& win, camera& cam, vec2f mpos)
{
battle_map_state& state = registry.get<battle_map::battle_map_state>(map);
tilemap& tmap = registry.get<tilemap>(map);
bool mouse_clicked = ImGui::IsMouseClicked(0) && !ImGui::IsAnyWindowHovered() && !ImGui::GetIO().WantCaptureMouse;
bool mouse_hovering = !ImGui::IsAnyWindowHovered();
if (mouse_clicked)
{
vec2f clamped_tile = clamp(
cam.screen_to_tile(win, mpos),
vec2f{ 0, 0 },
vec2f{ tmap.dim.x() - 1, tmap.dim.y() - 1 });
vec2i clamped_i_tile = vec2i{ (int)clamped_tile.x(), (int)clamped_tile.y() };
printf(" clicked tile: %d %d \n", clamped_i_tile.x(), clamped_i_tile.y());
if (state.current_item == combobox_items::OBSTACLES)
{
sprite_handle handle = get_sprite_handle_of(rng, tiles::type::CACTUS);
create_obstacle_at(registry, rng, clamped_i_tile, tmap, handle, -1);
}
if (state.current_item == combobox_items::ENEMY_UNITS)
{
vec2i half = tmap.dim / 2;
//add enemy
vec2i start_pos = clamped_i_tile;
vec2i dest_pos = tmap.dim - 1;
entt::entity enemy_unit = create_battle_unit_at(registry, rng, start_pos, 1);
wandering_ai ai;
ai.destination_xy = dest_pos;
registry.assign<wandering_ai>(enemy_unit, ai);
collidable coll;
coll.cost = 150;
registry.assign<collidable>(enemy_unit, coll);
tmap.add(enemy_unit, start_pos);
}
if (state.current_item == combobox_items::PLAYER_UNITS)
{
vec2i half = tmap.dim / 2;
//add enemy
vec2i start_pos = clamped_i_tile;
vec2i dest_pos = tmap.dim - 1;
entt::entity player_unit = create_battle_unit_at(registry, rng, start_pos, 0);
wandering_ai ai;
ai.destination_xy = dest_pos;
registry.assign<wandering_ai>(player_unit, ai);
collidable coll;
coll.cost = 150;
registry.assign<collidable>(player_unit, coll);
tmap.add(player_unit, start_pos);
}
}
std::string battle_editor_label = "Battle Editor ##" + std::to_string((int)map);
ImGui::Begin(battle_editor_label.c_str());
if (ImGui::BeginCombo("##combo", state.current_item_str.c_str())) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < state.items.size(); n++)
{
bool is_selected = (state.current_item_str == state.items[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(state.items[n].c_str(), is_selected))
{
printf("Selected! \n");
state.current_item_str = state.items[n];
state.current_item = combobox_str_to_item(state.current_item_str);
}
if (is_selected)
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
ImGui::EndCombo();
}
ImGui::End();
}
void battle_map::battle_map_state::unit_editor(entt::registry& registry, entt::entity& map, random_state& rng, render_window& win, camera& cam, vec2f mpos)
{
battle_map_state& state = registry.get<battle_map::battle_map_state>(map);
tilemap& tmap = registry.get<tilemap>(map);
//iterate over everything tilemap
//check if entities have required components
std::string unit_editor_label = "Unit Editor ##" + std::to_string((int)map);
ImGui::Begin(unit_editor_label.c_str());
auto view = registry.view<battle_tag, battle_unit_info, render_descriptor, sprite_handle, damageable, wandering_ai, tilemap_position>();
int id = 0;
for (auto ent : view)
{
auto& ai = view.get<wandering_ai>(ent);
auto& health = view.get<damageable>(ent);
auto& tmap_pos = view.get<tilemap_position>(ent);
auto& info = view.get<battle_unit_info>(ent);
if (health.cur_hp <= 0)
continue;
std::string name = "Unit name: STEVE";
ImGui::Text(name.c_str());
std::string hp = "Unit hp: " + std::to_string(health.cur_hp);
ImGui::Text(hp.c_str());
std::string attack = "Unit attack: " + std::to_string(info.damage);
ImGui::Text(attack.c_str());
std::string position = "Unit position (x): "
+ std::to_string(tmap_pos.pos.x())
+ " (y): " + std::to_string(tmap_pos.pos.y());
ImGui::Text(position.c_str());
std::string kills = "Unit kills: " + std::to_string(info.kills);
ImGui::Text(kills.c_str());
std::string button_label = "Destroy unit!##" + std::to_string(id);
if (ImGui::Button(button_label.c_str()))
{
tmap.remove(ent, tmap_pos.pos);
health.damage_amount(health.max_hp);
};
id += 1;
}
ImGui::End();
}
void battle_map::battle_map_state::debug_combat(entt::registry& registry, entt::entity& map, random_state& rng, render_window& win, camera& cam, vec2f mpos)
{
battle_map_state& state = registry.get<battle_map::battle_map_state>(map);
tilemap& tmap = registry.get<tilemap>(map);
std::string gamemode_editor_label = "Gamemode Editor ##" + std::to_string((int)map);
ImGui::Begin(gamemode_editor_label.c_str());
if (ImGui::BeginCombo("##combo", state.current_gamemode_str.c_str())) // The second parameter is the label previewed before opening the combo.
{
for (int n = 0; n < state.gamemodes.size(); n++)
{
bool is_selected = (state.current_gamemode_str == state.gamemodes[n]); // You can store your selection however you want, outside or inside your objects
if (ImGui::Selectable(state.gamemodes[n].c_str(), is_selected))
{
printf("Selected! \n");
state.current_gamemode_str = state.gamemodes[n];
state.current_gamemode = combobox_str_to_gamemode(state.current_gamemode_str);
}
if (is_selected)
ImGui::SetItemDefaultFocus(); // You may set the initial focus when opening the combo (scrolling + for keyboard navigation support)
}
ImGui::EndCombo();
}
ImGui::End();
}
| 34.311295 | 205 | 0.623766 | [
"vector",
"transform"
] |
1c4f90a0f53a787ca74d3c634ccc864e951cef32 | 1,214 | hpp | C++ | cpp/include/darabonba/string.hpp | aliyun/darabonba-string | b09372e1ec8a814a56f32e5898992fab3d75b41d | [
"Apache-2.0"
] | 3 | 2020-11-02T02:35:26.000Z | 2020-11-03T03:03:56.000Z | cpp/include/darabonba/string.hpp | aliyun/darabonba-string | b09372e1ec8a814a56f32e5898992fab3d75b41d | [
"Apache-2.0"
] | 4 | 2021-12-13T04:07:49.000Z | 2021-12-16T03:13:33.000Z | cpp/include/darabonba/string.hpp | aliyun/darabonba-string | b09372e1ec8a814a56f32e5898992fab3d75b41d | [
"Apache-2.0"
] | 6 | 2020-11-02T09:35:32.000Z | 2021-12-16T03:03:29.000Z | // This file is auto-generated, don't edit it. Thanks.
#ifndef DARABONBA_STRING_H_
#define DARABONBA_STRING_H_
#include <iostream>
#include <vector>
using namespace std;
namespace Darabonba_String {
class Client {
public:
static vector<string> split(shared_ptr<string> raw, shared_ptr<string> sep,
shared_ptr<int> limit);
static string replace(shared_ptr<string> raw, shared_ptr<string> oldStr,
shared_ptr<string> newStr, shared_ptr<int> count);
static bool contains(shared_ptr<string> s, shared_ptr<string> substr);
static int count(shared_ptr<string> s, shared_ptr<string> substr);
static bool hasPrefix(shared_ptr<string> s, shared_ptr<string> prefix);
static bool hasSuffix(shared_ptr<string> s, shared_ptr<string> substr);
static int index(shared_ptr<string> s, shared_ptr<string> substr);
static string toLower(shared_ptr<string> s);
static string toUpper(shared_ptr<string> s);
static string subString(shared_ptr<string> s, shared_ptr<int> start,
shared_ptr<int> end);
static bool equals(shared_ptr<string> expect, shared_ptr<string> actual);
Client(){};
};
} // namespace Darabonba_String
#endif
| 35.705882 | 77 | 0.719934 | [
"vector"
] |
1c50ed1efba24d1aa87dc2adfb3f44b52f1bab31 | 5,554 | cpp | C++ | vlc_linux/vlc-3.0.16/modules/demux/smooth/SmoothManager.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/smooth/SmoothManager.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/smooth/SmoothManager.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*
* SmoothManager.cpp
*****************************************************************************
* Copyright © 2015 - VideoLAN and VLC authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_fixups.h>
#include <cinttypes>
#include "SmoothManager.hpp"
#include "../adaptive/SharedResources.hpp"
#include "../adaptive/tools/Retrieve.hpp"
#include "playlist/Parser.hpp"
#include "../adaptive/xml/DOMParser.h"
#include <vlc_stream.h>
#include <vlc_demux.h>
#include <vlc_charset.h>
#include <time.h>
using namespace adaptive;
using namespace adaptive::logic;
using namespace smooth;
using namespace smooth::playlist;
SmoothManager::SmoothManager(demux_t *demux_,
SharedResources *res,
Manifest *playlist,
AbstractStreamFactory *factory,
AbstractAdaptationLogic::LogicType type) :
PlaylistManager(demux_, res, playlist, factory, type)
{
}
SmoothManager::~SmoothManager()
{
}
Manifest * SmoothManager::fetchManifest()
{
std::string playlisturl(p_demux->psz_access);
playlisturl.append("://");
playlisturl.append(p_demux->psz_location);
block_t *p_block = Retrieve::HTTP(resources, playlisturl);
if(!p_block)
return NULL;
stream_t *memorystream = vlc_stream_MemoryNew(p_demux, p_block->p_buffer, p_block->i_buffer, true);
if(!memorystream)
{
block_Release(p_block);
return NULL;
}
xml::DOMParser parser(memorystream);
if(!parser.parse(true))
{
vlc_stream_Delete(memorystream);
block_Release(p_block);
return NULL;
}
Manifest *manifest = NULL;
ManifestParser *manifestParser = new (std::nothrow) ManifestParser(parser.getRootNode(), VLC_OBJECT(p_demux),
memorystream, playlisturl);
if(manifestParser)
{
manifest = manifestParser->parse();
delete manifestParser;
}
vlc_stream_Delete(memorystream);
block_Release(p_block);
return manifest;
}
bool SmoothManager::updatePlaylist()
{
bool b_playlist_empty = false;
/* Trigger full playlist update in case we cannot get next
segment from atom */
std::vector<AbstractStream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
const AbstractStream *st = *it;
const mtime_t m = st->getMinAheadTime();
if(!st->isValid() || st->isDisabled() || !st->isSelected())
{
continue;
}
else if(m < 1)
{
b_playlist_empty = true;
break;
}
}
return updatePlaylist(b_playlist_empty);
}
void SmoothManager::scheduleNextUpdate()
{
time_t now = time(NULL);
mtime_t minbuffer = 0;
std::vector<AbstractStream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
const AbstractStream *st = *it;
if(!st->isValid() || st->isDisabled() || !st->isSelected())
continue;
const mtime_t m = st->getMinAheadTime();
if(m > 0 && (m < minbuffer || minbuffer == 0))
minbuffer = m;
}
minbuffer /= 2;
if(playlist->minUpdatePeriod.Get() > minbuffer)
minbuffer = playlist->minUpdatePeriod.Get();
if(minbuffer < 5 * CLOCK_FREQ)
minbuffer = 5 * CLOCK_FREQ;
nextPlaylistupdate = now + minbuffer / CLOCK_FREQ;
msg_Dbg(p_demux, "Updated playlist, next update in %" PRId64 "s", (mtime_t) nextPlaylistupdate - now );
}
bool SmoothManager::needsUpdate() const
{
if(nextPlaylistupdate && time(NULL) < nextPlaylistupdate)
return false;
return PlaylistManager::needsUpdate();
}
bool SmoothManager::updatePlaylist(bool forcemanifest)
{
/* FIXME: do update from manifest after resuming from pause */
/* Timelines updates should be inlined in tfrf atoms.
We'll just care about pruning live timeline then. */
if(forcemanifest && nextPlaylistupdate)
{
Manifest *newManifest = fetchManifest();
if(newManifest)
{
playlist->updateWith(newManifest);
delete newManifest;
#ifdef NDEBUG
playlist->debug();
#endif
}
else return false;
}
return true;
}
bool SmoothManager::reactivateStream(AbstractStream *stream)
{
if(playlist->isLive())
updatePlaylist(true);
return PlaylistManager::reactivateStream(stream);
}
bool SmoothManager::isSmoothStreaming(xml::Node *root)
{
return root->getName() == "SmoothStreamingMedia";
}
bool SmoothManager::mimeMatched(const std::string &mime)
{
return (mime == "application/vnd.ms-sstr+xml");
}
| 28.050505 | 113 | 0.629816 | [
"vector"
] |
1c5daa14bc4149e686663bb5268bd1d2a912b15d | 22,065 | cc | C++ | ns-allinone-3.35/ns-3.35/examples/tcp/dctcp-example.cc | usi-systems/cc | 487aa9e322b2b01b6af3a92e38545c119e4980a3 | [
"Apache-2.0"
] | 1 | 2022-03-22T08:08:35.000Z | 2022-03-22T08:08:35.000Z | ns-3-dev/examples/tcp/dctcp-example.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null | ns-3-dev/examples/tcp/dctcp-example.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2017-20 NITK Surathkal
* Copyright (c) 2020 Tom Henderson (better alignment with experiment)
*
* 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;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Shravya K.S. <shravya.ks0@gmail.com>
* Apoorva Bhargava <apoorvabhargava13@gmail.com>
* Shikha Bakshi <shikhabakshi912@gmail.com>
* Mohit P. Tahiliani <tahiliani@nitk.edu.in>
* Tom Henderson <tomh@tomh.org>
*/
// The network topology used in this example is based on Fig. 17 described in
// Mohammad Alizadeh, Albert Greenberg, David A. Maltz, Jitendra Padhye,
// Parveen Patel, Balaji Prabhakar, Sudipta Sengupta, and Murari Sridharan.
// "Data Center TCP (DCTCP)." In ACM SIGCOMM Computer Communication Review,
// Vol. 40, No. 4, pp. 63-74. ACM, 2010.
// The topology is roughly as follows
//
// S1 S3
// | | (1 Gbps)
// T1 ------- T2 -- R1
// | | (1 Gbps)
// S2 R2
//
// The link between switch T1 and T2 is 10 Gbps. All other
// links are 1 Gbps. In the SIGCOMM paper, there is a Scorpion switch
// between T1 and T2, but it doesn't contribute another bottleneck.
//
// S1 and S3 each have 10 senders sending to receiver R1 (20 total)
// S2 (20 senders) sends traffic to R2 (20 receivers)
//
// This sets up two bottlenecks: 1) T1 -> T2 interface (30 senders
// using the 10 Gbps link) and 2) T2 -> R1 (20 senders using 1 Gbps link)
//
// RED queues configured for ECN marking are used at the bottlenecks.
//
// Figure 17 published results are that each sender in S1 gets 46 Mbps
// and each in S3 gets 54 Mbps, while each S2 sender gets 475 Mbps, and
// that these are within 10% of their fair-share throughputs (Jain index
// of 0.99).
//
// This program runs the program by default for five seconds. The first
// second is devoted to flow startup (all 40 TCP flows are stagger started
// during this period). There is a three second convergence time where
// no measurement data is taken, and then there is a one second measurement
// interval to gather raw throughput for each flow. These time intervals
// can be changed at the command line.
//
// The program outputs six files. The first three:
// * dctcp-example-s1-r1-throughput.dat
// * dctcp-example-s2-r2-throughput.dat
// * dctcp-example-s3-r1-throughput.dat
// provide per-flow throughputs (in Mb/s) for each of the forty flows, summed
// over the measurement window. The fourth file,
// * dctcp-example-fairness.dat
// provides average throughputs for the three flow paths, and computes
// Jain's fairness index for each flow group (i.e. across each group of
// 10, 20, and 10 flows). It also sums the throughputs across each bottleneck.
// The fifth and sixth:
// * dctcp-example-t1-length.dat
// * dctcp-example-t2-length.dat
// report on the bottleneck queue length (in packets and microseconds
// of delay) at 10 ms intervals during the measurement window.
//
// By default, the throughput averages are 23 Mbps for S1 senders, 471 Mbps
// for S2 senders, and 74 Mbps for S3 senders, and the Jain index is greater
// than 0.99 for each group of flows. The average queue delay is about 1ms
// for the T2->R2 bottleneck, and about 200us for the T1->T2 bottleneck.
//
// The RED parameters (min_th and max_th) are set to the same values as
// reported in the paper, but we observed that throughput distributions
// and queue delays are very sensitive to these parameters, as was also
// observed in the paper; it is likely that the paper's throughput results
// could be achieved by further tuning of the RED parameters. However,
// the default results show that DCTCP is able to achieve high link
// utilization and low queueing delay and fairness across competing flows
// sharing the same path.
#include <iostream>
#include <iomanip>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/traffic-control-module.h"
using namespace ns3;
std::stringstream filePlotQueue1;
std::stringstream filePlotQueue2;
std::ofstream rxS1R1Throughput;
std::ofstream rxS2R2Throughput;
std::ofstream rxS3R1Throughput;
std::ofstream fairnessIndex;
std::ofstream t1QueueLength;
std::ofstream t2QueueLength;
std::vector<uint64_t> rxS1R1Bytes;
std::vector<uint64_t> rxS2R2Bytes;
std::vector<uint64_t> rxS3R1Bytes;
void
PrintProgress (Time interval)
{
std::cout << "Progress to " << std::fixed << std::setprecision (1) << Simulator::Now ().GetSeconds () << " seconds simulation time" << std::endl;
Simulator::Schedule (interval, &PrintProgress, interval);
}
void
TraceS1R1Sink (std::size_t index, Ptr<const Packet> p, const Address& a)
{
rxS1R1Bytes[index] += p->GetSize ();
}
void
TraceS2R2Sink (std::size_t index, Ptr<const Packet> p, const Address& a)
{
rxS2R2Bytes[index] += p->GetSize ();
}
void
TraceS3R1Sink (std::size_t index, Ptr<const Packet> p, const Address& a)
{
rxS3R1Bytes[index] += p->GetSize ();
}
void
InitializeCounters (void)
{
for (std::size_t i = 0; i < 10; i++)
{
rxS1R1Bytes[i] = 0;
}
for (std::size_t i = 0; i < 20; i++)
{
rxS2R2Bytes[i] = 0;
}
for (std::size_t i = 0; i < 10; i++)
{
rxS3R1Bytes[i] = 0;
}
}
void
PrintThroughput (Time measurementWindow)
{
for (std::size_t i = 0; i < 10; i++)
{
rxS1R1Throughput << measurementWindow.GetSeconds () << "s " << i << " " << (rxS1R1Bytes[i] * 8) / (measurementWindow.GetSeconds ()) / 1e6 << std::endl;
}
for (std::size_t i = 0; i < 20; i++)
{
rxS2R2Throughput << Simulator::Now ().GetSeconds () << "s " << i << " " << (rxS2R2Bytes[i] * 8) / (measurementWindow.GetSeconds ()) / 1e6 << std::endl;
}
for (std::size_t i = 0; i < 10; i++)
{
rxS3R1Throughput << Simulator::Now ().GetSeconds () << "s " << i << " " << (rxS3R1Bytes[i] * 8) / (measurementWindow.GetSeconds ()) / 1e6 << std::endl;
}
}
// Jain's fairness index: https://en.wikipedia.org/wiki/Fairness_measure
void
PrintFairness (Time measurementWindow)
{
double average = 0;
uint64_t sumSquares = 0;
uint64_t sum = 0;
double fairness = 0;
for (std::size_t i = 0; i < 10; i++)
{
sum += rxS1R1Bytes[i];
sumSquares += (rxS1R1Bytes[i] * rxS1R1Bytes[i]);
}
average = ((sum / 10) * 8 / measurementWindow.GetSeconds ()) / 1e6;
fairness = static_cast<double> (sum * sum) / (10 * sumSquares);
fairnessIndex << "Average throughput for S1-R1 flows: "
<< std::fixed << std::setprecision (2) << average << " Mbps; fairness: "
<< std::fixed << std::setprecision (3) << fairness << std::endl;
average = 0;
sumSquares = 0;
sum = 0;
fairness = 0;
for (std::size_t i = 0; i < 20; i++)
{
sum += rxS2R2Bytes[i];
sumSquares += (rxS2R2Bytes[i] * rxS2R2Bytes[i]);
}
average = ((sum / 20) * 8 / measurementWindow.GetSeconds ()) / 1e6;
fairness = static_cast<double> (sum * sum) / (20 * sumSquares);
fairnessIndex << "Average throughput for S2-R2 flows: "
<< std::fixed << std::setprecision (2) << average << " Mbps; fairness: "
<< std::fixed << std::setprecision (3) << fairness << std::endl;
average = 0;
sumSquares = 0;
sum = 0;
fairness = 0;
for (std::size_t i = 0; i < 10; i++)
{
sum += rxS3R1Bytes[i];
sumSquares += (rxS3R1Bytes[i] * rxS3R1Bytes[i]);
}
average = ((sum / 10) * 8 / measurementWindow.GetSeconds ()) / 1e6;
fairness = static_cast<double> (sum * sum) / (10 * sumSquares);
fairnessIndex << "Average throughput for S3-R1 flows: "
<< std::fixed << std::setprecision (2) << average << " Mbps; fairness: "
<< std::fixed << std::setprecision (3) << fairness << std::endl;
sum = 0;
for (std::size_t i = 0; i < 10; i++)
{
sum += rxS1R1Bytes[i];
}
for (std::size_t i = 0; i < 20; i++)
{
sum += rxS2R2Bytes[i];
}
fairnessIndex << "Aggregate user-level throughput for flows through T1: " << static_cast<double> (sum * 8) / 1e9 << " Gbps" << std::endl;
sum = 0;
for (std::size_t i = 0; i < 10; i++)
{
sum += rxS3R1Bytes[i];
}
for (std::size_t i = 0; i < 10; i++)
{
sum += rxS1R1Bytes[i];
}
fairnessIndex << "Aggregate user-level throughput for flows to R1: " << static_cast<double> (sum * 8) / 1e9 << " Gbps" << std::endl;
}
void
CheckT1QueueSize (Ptr<QueueDisc> queue)
{
// 1500 byte packets
uint32_t qSize = queue->GetNPackets ();
Time backlog = Seconds (static_cast<double> (qSize * 1500 * 8) / 1e10); // 10 Gb/s
// report size in units of packets and ms
t1QueueLength << std::fixed << std::setprecision (2) << Simulator::Now ().GetSeconds () << " " << qSize << " " << backlog.GetMicroSeconds () << std::endl;
// check queue size every 1/100 of a second
Simulator::Schedule (MilliSeconds (10), &CheckT1QueueSize, queue);
}
void
CheckT2QueueSize (Ptr<QueueDisc> queue)
{
uint32_t qSize = queue->GetNPackets ();
Time backlog = Seconds (static_cast<double> (qSize * 1500 * 8) / 1e9); // 1 Gb/s
// report size in units of packets and ms
t2QueueLength << std::fixed << std::setprecision (2) << Simulator::Now ().GetSeconds () << " " << qSize << " " << backlog.GetMicroSeconds () << std::endl;
// check queue size every 1/100 of a second
Simulator::Schedule (MilliSeconds (10), &CheckT2QueueSize, queue);
}
int main (int argc, char *argv[])
{
std::string outputFilePath = ".";
std::string tcpTypeId = "TcpDctcp";
Time flowStartupWindow = Seconds (1);
Time convergenceTime = Seconds (3);
Time measurementWindow = Seconds (1);
bool enableSwitchEcn = true;
Time progressInterval = MilliSeconds (100);
CommandLine cmd (__FILE__);
cmd.AddValue ("tcpTypeId", "ns-3 TCP TypeId", tcpTypeId);
cmd.AddValue ("flowStartupWindow", "startup time window (TCP staggered starts)", flowStartupWindow);
cmd.AddValue ("convergenceTime", "convergence time", convergenceTime);
cmd.AddValue ("measurementWindow", "measurement window", measurementWindow);
cmd.AddValue ("enableSwitchEcn", "enable ECN at switches", enableSwitchEcn);
cmd.Parse (argc, argv);
Config::SetDefault ("ns3::TcpL4Protocol::SocketType", StringValue ("ns3::" + tcpTypeId));
Time startTime = Seconds (0);
Time stopTime = flowStartupWindow + convergenceTime + measurementWindow;
Time clientStartTime = startTime;
rxS1R1Bytes.reserve (10);
rxS2R2Bytes.reserve (20);
rxS3R1Bytes.reserve (10);
NodeContainer S1, S2, S3, R2;
Ptr<Node> T1 = CreateObject<Node> ();
Ptr<Node> T2 = CreateObject<Node> ();
Ptr<Node> R1 = CreateObject<Node> ();
S1.Create (10);
S2.Create (20);
S3.Create (10);
R2.Create (20);
Config::SetDefault ("ns3::TcpSocket::SegmentSize", UintegerValue (1448));
Config::SetDefault ("ns3::TcpSocket::DelAckCount", UintegerValue (2));
GlobalValue::Bind ("ChecksumEnabled", BooleanValue (false));
// Set default parameters for RED queue disc
Config::SetDefault ("ns3::RedQueueDisc::UseEcn", BooleanValue (enableSwitchEcn));
// ARED may be used but the queueing delays will increase; it is disabled
// here because the SIGCOMM paper did not mention it
// Config::SetDefault ("ns3::RedQueueDisc::ARED", BooleanValue (true));
// Config::SetDefault ("ns3::RedQueueDisc::Gentle", BooleanValue (true));
Config::SetDefault ("ns3::RedQueueDisc::UseHardDrop", BooleanValue (false));
Config::SetDefault ("ns3::RedQueueDisc::MeanPktSize", UintegerValue (1500));
// Triumph and Scorpion switches used in DCTCP Paper have 4 MB of buffer
// If every packet is 1500 bytes, 2666 packets can be stored in 4 MB
Config::SetDefault ("ns3::RedQueueDisc::MaxSize", QueueSizeValue (QueueSize ("2666p")));
// DCTCP tracks instantaneous queue length only; so set QW = 1
Config::SetDefault ("ns3::RedQueueDisc::QW", DoubleValue (1));
Config::SetDefault ("ns3::RedQueueDisc::MinTh", DoubleValue (20));
Config::SetDefault ("ns3::RedQueueDisc::MaxTh", DoubleValue (60));
PointToPointHelper pointToPointSR;
pointToPointSR.SetDeviceAttribute ("DataRate", StringValue ("1Gbps"));
pointToPointSR.SetChannelAttribute ("Delay", StringValue ("10us"));
PointToPointHelper pointToPointT;
pointToPointT.SetDeviceAttribute ("DataRate", StringValue ("10Gbps"));
pointToPointT.SetChannelAttribute ("Delay", StringValue ("10us"));
// Create a total of 62 links.
std::vector<NetDeviceContainer> S1T1;
S1T1.reserve (10);
std::vector<NetDeviceContainer> S2T1;
S2T1.reserve (20);
std::vector<NetDeviceContainer> S3T2;
S3T2.reserve (10);
std::vector<NetDeviceContainer> R2T2;
R2T2.reserve (20);
NetDeviceContainer T1T2 = pointToPointT.Install (T1, T2);
NetDeviceContainer R1T2 = pointToPointSR.Install (R1, T2);
for (std::size_t i = 0; i < 10; i++)
{
Ptr<Node> n = S1.Get (i);
S1T1.push_back (pointToPointSR.Install (n, T1));
}
for (std::size_t i = 0; i < 20; i++)
{
Ptr<Node> n = S2.Get (i);
S2T1.push_back (pointToPointSR.Install (n, T1));
}
for (std::size_t i = 0; i < 10; i++)
{
Ptr<Node> n = S3.Get (i);
S3T2.push_back (pointToPointSR.Install (n, T2));
}
for (std::size_t i = 0; i < 20; i++)
{
Ptr<Node> n = R2.Get (i);
R2T2.push_back (pointToPointSR.Install (n, T2));
}
InternetStackHelper stack;
stack.InstallAll ();
TrafficControlHelper tchRed10;
// MinTh = 50, MaxTh = 150 recommended in ACM SIGCOMM 2010 DCTCP Paper
// This yields a target (MinTh) queue depth of 60us at 10 Gb/s
tchRed10.SetRootQueueDisc ("ns3::RedQueueDisc",
"LinkBandwidth", StringValue ("10Gbps"),
"LinkDelay", StringValue ("10us"),
"MinTh", DoubleValue (50),
"MaxTh", DoubleValue (150));
QueueDiscContainer queueDiscs1 = tchRed10.Install (T1T2);
TrafficControlHelper tchRed1;
// MinTh = 20, MaxTh = 60 recommended in ACM SIGCOMM 2010 DCTCP Paper
// This yields a target queue depth of 250us at 1 Gb/s
tchRed1.SetRootQueueDisc ("ns3::RedQueueDisc",
"LinkBandwidth", StringValue ("1Gbps"),
"LinkDelay", StringValue ("10us"),
"MinTh", DoubleValue (20),
"MaxTh", DoubleValue (60));
QueueDiscContainer queueDiscs2 = tchRed1.Install (R1T2.Get (1));
for (std::size_t i = 0; i < 10; i++)
{
tchRed1.Install (S1T1[i].Get (1));
}
for (std::size_t i = 0; i < 20; i++)
{
tchRed1.Install (S2T1[i].Get (1));
}
for (std::size_t i = 0; i < 10; i++)
{
tchRed1.Install (S3T2[i].Get (1));
}
for (std::size_t i = 0; i < 20; i++)
{
tchRed1.Install (R2T2[i].Get (1));
}
Ipv4AddressHelper address;
std::vector<Ipv4InterfaceContainer> ipS1T1;
ipS1T1.reserve (10);
std::vector<Ipv4InterfaceContainer> ipS2T1;
ipS2T1.reserve (20);
std::vector<Ipv4InterfaceContainer> ipS3T2;
ipS3T2.reserve (10);
std::vector<Ipv4InterfaceContainer> ipR2T2;
ipR2T2.reserve (20);
address.SetBase ("172.16.1.0", "255.255.255.0");
Ipv4InterfaceContainer ipT1T2 = address.Assign (T1T2);
address.SetBase ("192.168.0.0", "255.255.255.0");
Ipv4InterfaceContainer ipR1T2 = address.Assign (R1T2);
address.SetBase ("10.1.1.0", "255.255.255.0");
for (std::size_t i = 0; i < 10; i++)
{
ipS1T1.push_back (address.Assign (S1T1[i]));
address.NewNetwork ();
}
address.SetBase ("10.2.1.0", "255.255.255.0");
for (std::size_t i = 0; i < 20; i++)
{
ipS2T1.push_back (address.Assign (S2T1[i]));
address.NewNetwork ();
}
address.SetBase ("10.3.1.0", "255.255.255.0");
for (std::size_t i = 0; i < 10; i++)
{
ipS3T2.push_back (address.Assign (S3T2[i]));
address.NewNetwork ();
}
address.SetBase ("10.4.1.0", "255.255.255.0");
for (std::size_t i = 0; i < 20; i++)
{
ipR2T2.push_back (address.Assign (R2T2[i]));
address.NewNetwork ();
}
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
// Each sender in S2 sends to a receiver in R2
std::vector<Ptr<PacketSink> > r2Sinks;
r2Sinks.reserve (20);
for (std::size_t i = 0; i < 20; i++)
{
uint16_t port = 50000 + i;
Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress);
ApplicationContainer sinkApp = sinkHelper.Install (R2.Get (i));
Ptr<PacketSink> packetSink = sinkApp.Get (0)->GetObject<PacketSink> ();
r2Sinks.push_back (packetSink);
sinkApp.Start (startTime);
sinkApp.Stop (stopTime);
OnOffHelper clientHelper1 ("ns3::TcpSocketFactory", Address ());
clientHelper1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
clientHelper1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));
clientHelper1.SetAttribute ("DataRate", DataRateValue (DataRate ("1Gbps")));
clientHelper1.SetAttribute ("PacketSize", UintegerValue (1000));
ApplicationContainer clientApps1;
AddressValue remoteAddress (InetSocketAddress (ipR2T2[i].GetAddress (0), port));
clientHelper1.SetAttribute ("Remote", remoteAddress);
clientApps1.Add (clientHelper1.Install (S2.Get (i)));
clientApps1.Start (i * flowStartupWindow / 20 + clientStartTime + MilliSeconds (i * 5));
clientApps1.Stop (stopTime);
}
// Each sender in S1 and S3 sends to R1
std::vector<Ptr<PacketSink> > s1r1Sinks;
std::vector<Ptr<PacketSink> > s3r1Sinks;
s1r1Sinks.reserve (10);
s3r1Sinks.reserve (10);
for (std::size_t i = 0; i < 20; i++)
{
uint16_t port = 50000 + i;
Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress);
ApplicationContainer sinkApp = sinkHelper.Install (R1);
Ptr<PacketSink> packetSink = sinkApp.Get (0)->GetObject<PacketSink> ();
if (i < 10)
{
s1r1Sinks.push_back (packetSink);
}
else
{
s3r1Sinks.push_back (packetSink);
}
sinkApp.Start (startTime);
sinkApp.Stop (stopTime);
OnOffHelper clientHelper1 ("ns3::TcpSocketFactory", Address ());
clientHelper1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
clientHelper1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));
clientHelper1.SetAttribute ("DataRate", DataRateValue (DataRate ("1Gbps")));
clientHelper1.SetAttribute ("PacketSize", UintegerValue (1000));
ApplicationContainer clientApps1;
AddressValue remoteAddress (InetSocketAddress (ipR1T2.GetAddress (0), port));
clientHelper1.SetAttribute ("Remote", remoteAddress);
if (i < 10)
{
clientApps1.Add (clientHelper1.Install (S1.Get (i)));
clientApps1.Start (i * flowStartupWindow / 10 + clientStartTime + MilliSeconds (i * 5));
}
else
{
clientApps1.Add (clientHelper1.Install (S3.Get (i - 10)));
clientApps1.Start ((i - 10) * flowStartupWindow / 10 + clientStartTime + MilliSeconds (i * 5));
}
clientApps1.Stop (stopTime);
}
rxS1R1Throughput.open ("dctcp-example-s1-r1-throughput.dat", std::ios::out);
rxS1R1Throughput << "#Time(s) flow thruput(Mb/s)" << std::endl;
rxS2R2Throughput.open ("dctcp-example-s2-r2-throughput.dat", std::ios::out);
rxS2R2Throughput << "#Time(s) flow thruput(Mb/s)" << std::endl;
rxS3R1Throughput.open ("dctcp-example-s3-r1-throughput.dat", std::ios::out);
rxS3R1Throughput << "#Time(s) flow thruput(Mb/s)" << std::endl;
fairnessIndex.open ("dctcp-example-fairness.dat", std::ios::out);
t1QueueLength.open ("dctcp-example-t1-length.dat", std::ios::out);
t1QueueLength << "#Time(s) qlen(pkts) qlen(us)" << std::endl;
t2QueueLength.open ("dctcp-example-t2-length.dat", std::ios::out);
t2QueueLength << "#Time(s) qlen(pkts) qlen(us)" << std::endl;
for (std::size_t i = 0; i < 10; i++)
{
s1r1Sinks[i]->TraceConnectWithoutContext ("Rx", MakeBoundCallback (&TraceS1R1Sink, i));
}
for (std::size_t i = 0; i < 20; i++)
{
r2Sinks[i]->TraceConnectWithoutContext ("Rx", MakeBoundCallback (&TraceS2R2Sink, i));
}
for (std::size_t i = 0; i < 10; i++)
{
s3r1Sinks[i]->TraceConnectWithoutContext ("Rx", MakeBoundCallback (&TraceS3R1Sink, i));
}
Simulator::Schedule (flowStartupWindow + convergenceTime, &InitializeCounters);
Simulator::Schedule (flowStartupWindow + convergenceTime + measurementWindow, &PrintThroughput, measurementWindow);
Simulator::Schedule (flowStartupWindow + convergenceTime + measurementWindow, &PrintFairness, measurementWindow);
Simulator::Schedule (progressInterval, &PrintProgress, progressInterval);
Simulator::Schedule (flowStartupWindow + convergenceTime, &CheckT1QueueSize, queueDiscs1.Get (0));
Simulator::Schedule (flowStartupWindow + convergenceTime, &CheckT2QueueSize, queueDiscs2.Get (0));
Simulator::Stop (stopTime + TimeStep (1));
Simulator::Run ();
rxS1R1Throughput.close ();
rxS2R2Throughput.close ();
rxS3R1Throughput.close ();
fairnessIndex.close ();
t1QueueLength.close ();
t2QueueLength.close ();
Simulator::Destroy ();
return 0;
}
| 39.191829 | 157 | 0.659642 | [
"vector"
] |
1c5fc343482433c2319aa4e0be34d72cace25f61 | 4,846 | cpp | C++ | src/DivingRecorder/debug/moc_welcomewindow.cpp | wukurua/DVR | 8d41a5b16e6e0bf22c69272fdbfad4ac151e3ba1 | [
"Apache-2.0"
] | 10 | 2020-07-12T15:15:39.000Z | 2021-08-17T08:07:15.000Z | src/DivingRecorder/debug/moc_welcomewindow.cpp | wukurua/DVR | 8d41a5b16e6e0bf22c69272fdbfad4ac151e3ba1 | [
"Apache-2.0"
] | null | null | null | src/DivingRecorder/debug/moc_welcomewindow.cpp | wukurua/DVR | 8d41a5b16e6e0bf22c69272fdbfad4ac151e3ba1 | [
"Apache-2.0"
] | 5 | 2020-08-30T01:01:29.000Z | 2022-03-08T02:06:37.000Z | /****************************************************************************
** Meta object code from reading C++ file 'welcomewindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../view/welcomewindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'welcomewindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.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
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_WelcomeWindow_t {
QByteArrayData data[6];
char stringdata0[54];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_WelcomeWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_WelcomeWindow_t qt_meta_stringdata_WelcomeWindow = {
{
QT_MOC_LITERAL(0, 0, 13), // "WelcomeWindow"
QT_MOC_LITERAL(1, 14, 5), // "close"
QT_MOC_LITERAL(2, 20, 0), // ""
QT_MOC_LITERAL(3, 21, 12), // "startFdecode"
QT_MOC_LITERAL(4, 34, 8), // "closeWin"
QT_MOC_LITERAL(5, 43, 10) // "countToEnd"
},
"WelcomeWindow\0close\0\0startFdecode\0"
"closeWin\0countToEnd"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_WelcomeWindow[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 34, 2, 0x06 /* Public */,
3, 0, 35, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 0, 36, 2, 0x0a /* Public */,
5, 0, 37, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void,
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void WelcomeWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<WelcomeWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->close(); break;
case 1: _t->startFdecode(); break;
case 2: _t->closeWin(); break;
case 3: _t->countToEnd(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (WelcomeWindow::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WelcomeWindow::close)) {
*result = 0;
return;
}
}
{
using _t = void (WelcomeWindow::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&WelcomeWindow::startFdecode)) {
*result = 1;
return;
}
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject WelcomeWindow::staticMetaObject = { {
QMetaObject::SuperData::link<QGraphicsView::staticMetaObject>(),
qt_meta_stringdata_WelcomeWindow.data,
qt_meta_data_WelcomeWindow,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *WelcomeWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *WelcomeWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_WelcomeWindow.stringdata0))
return static_cast<void*>(this);
return QGraphicsView::qt_metacast(_clname);
}
int WelcomeWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGraphicsView::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
// SIGNAL 0
void WelcomeWindow::close()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
// SIGNAL 1
void WelcomeWindow::startFdecode()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 29.369697 | 98 | 0.60194 | [
"object"
] |
1c615e3828adde7d26c0c0cf85a288d88da5cd0c | 911 | hpp | C++ | src/Externals/spire/es-render/comp/FBO.hpp | Nahusa/SCIRun | c54e714d4c7e956d053597cf194e07616e28a498 | [
"MIT"
] | 1 | 2019-05-30T06:00:15.000Z | 2019-05-30T06:00:15.000Z | src/Externals/spire/es-render/comp/FBO.hpp | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | src/Externals/spire/es-render/comp/FBO.hpp | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | #ifndef SPIRE_RENDER_COMPONENT_FBO_HPP
#define SPIRE_RENDER_COMPONENT_FBO_HPP
#include <es-log/trace-log.h>
#include <glm/glm.hpp>
#include <gl-platform/GLPlatform.hpp>
#include <es-cereal/ComponentSerialize.hpp>
#include <es-render/comp/Texture.hpp>
#include <spire/scishare.h>
namespace ren {
struct FBO
{
// -- Data --
GLuint glid;
GLenum textureType;
bool initialized;
// -- Functions --
FBO()
{
glid = 0;
textureType = GL_TEXTURE_2D;
initialized = false;
}
static const char* getName() { return "ren:FBO"; }
struct TextureData
{
GLenum att;
std::string texName;
};
std::vector<TextureData> textures;
bool serialize(spire::ComponentSerialize& /* s */, uint64_t /* entityID */)
{
/// Nothing needs to be serialized. This is context specific.
return true;
}
};
} // namespace ren
#endif
| 18.979167 | 79 | 0.636663 | [
"render",
"vector"
] |
1c6620bb9e4489fe8e4a41b9a3d08d9f2ca09f8c | 12,557 | cxx | C++ | private/windows/opengl/scrsave/pipes/xc.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/windows/opengl/scrsave/pipes/xc.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/windows/opengl/scrsave/pipes/xc.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | /******************************Module*Header*******************************\
* Module Name: xc.cxx
*
* Cross-section (xc) object stuff
*
* Copyright (c) 1995 Microsoft Corporation
*
\**************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <time.h>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glaux.h>
#include <float.h>
#include "sscommon.h"
#include "sspipes.h"
#include "eval.h"
#include "xc.h"
/**************************************************************************\
* XC::CalcArcACValues90
*
* Calculate arc control points for a 90 degree rotation of an xc
*
* Arc is a quarter-circle
* - 90 degree is much easier, so we special case it
* - radius is distance from xc-origin to hinge of turn
*
* History
* July 28, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
void
XC::CalcArcACValues90( int dir, float radius, float *acPts )
{
int i;
float sign;
int offset;
float *ppts = (float *) pts;
// 1) calc 'r' values for each point (4 turn possibilities/point). From
// this can determine ac, which is extrusion of point from xc face
switch( dir ) {
case PLUS_X:
offset = 0;
sign = -1.0f;
break;
case MINUS_X:
offset = 0;
sign = 1.0f;
break;
case PLUS_Y:
offset = 1;
sign = -1.0f;
break;
case MINUS_Y:
offset = 1;
sign = 1.0f;
break;
}
for( i = 0; i < numPts; i++, ppts+=2, acPts++ ) {
*acPts = EVAL_CIRC_ARC_CONTROL * (radius + (sign * ppts[offset]));
}
// replicate !
*acPts = *(acPts - numPts);
}
/**************************************************************************\
* XC::CalcArcACValuesByDistance
*
* Use the distance of each xc point from the xc origin, as the radius for
* an arc control value.
*
* History
* July 29, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
void
XC::CalcArcACValuesByDistance( float *acPts )
{
int i;
float r;
POINT2D *ppts = pts;
for( i = 0; i < numPts; i++, ppts++ ) {
r = (float) sqrt( ppts->x*ppts->x + ppts->y*ppts->y );
*acPts++ = EVAL_CIRC_ARC_CONTROL * r;
}
// replicate !
*acPts = *(acPts - numPts);
}
/**************************************************************************\
* ELLIPTICAL_XC::SetControlPoints
*
* Set the 12 control points for a circle at origin in z=0 plane
*
* Points go CCW from +x
*
* History
* July 24, 95 : [marcfo]
* - Wrote it
* - 10/18/95 [marcfo] : Convert to C++
*
\**************************************************************************/
void
ELLIPTICAL_XC::SetControlPoints( GLfloat r1, GLfloat r2 )
{
GLfloat ac1, ac2;
ac1 = EVAL_CIRC_ARC_CONTROL * r2;
ac2 = EVAL_CIRC_ARC_CONTROL * r1;
// create 12-pt. set CCW from +x
// last 2 points of right triplet
pts[0].x = r1;
pts[0].y = 0.0f;
pts[1].x = r1;
pts[1].y = ac1;
// top triplet
pts[2].x = ac2;
pts[2].y = r2;
pts[3].x = 0.0f;
pts[3].y = r2;
pts[4].x = -ac2;
pts[4].y = r2;
// left triplet
pts[5].x = -r1;
pts[5].y = ac1;
pts[6].x = -r1;
pts[6].y = 0.0f;
pts[7].x = -r1;
pts[7].y = -ac1;
// bottom triplet
pts[8].x = -ac2;
pts[8].y = -r2;
pts[9].x = 0.0f;
pts[9].y = -r2;
pts[10].x = ac2;
pts[10].y = -r2;
// first point of first triplet
pts[11].x = r1;
pts[11].y = -ac1;
}
/**************************************************************************\
* RANDOM4ARC_XC::SetControlPoints
*
* Set random control points for xc
* Points go CCW from +x
*
* History
* July 30, 95 : [marcfo]
* - Wrote it
* - 10/18/95 [marcfo] : Convert to C++
*
\**************************************************************************/
void
RANDOM4ARC_XC::SetControlPoints( float radius )
{
int i;
GLfloat r[4];
float rMin = 0.5f * radius;
float distx, disty;
// figure the radius of each side first
for( i = 0; i < 4; i ++ )
r[i] = ss_fRand( rMin, radius );
// The 4 r's now describe a box around the origin - this restricts stuff
// Now need to select a point along each edge of the box as the joining
// points for each arc (join points are at indices 0,3,6,9)
pts[0].x = r[RIGHT];
pts[3].y = r[TOP];
pts[6].x = -r[LEFT];
pts[9].y = -r[BOTTOM];
// quarter of distance between edges
disty = (r[TOP] - -r[BOTTOM]) / 4.0f;
distx = (r[RIGHT] - -r[LEFT]) / 4.0f;
// uh, put'em somwhere in the middle half of each side
pts[0].y = ss_fRand( -r[BOTTOM] + disty, r[TOP] - disty );
pts[6].y = ss_fRand( -r[BOTTOM] + disty, r[TOP] - disty );
pts[3].x = ss_fRand( -r[LEFT] + distx, r[RIGHT] - distx );
pts[9].x = ss_fRand( -r[LEFT] + distx, r[RIGHT] - distx );
// now can calc ac's
// easy part first:
pts[1].x = pts[11].x = pts[0].x;
pts[2].y = pts[4].y = pts[3].y;
pts[5].x = pts[7].x = pts[6].x;
pts[8].y = pts[10].y = pts[9].y;
// right side ac's
disty = (r[TOP] - pts[0].y) / 4.0f;
pts[1].y = ss_fRand( pts[0].y + disty, r[TOP] );
disty = (pts[0].y - -r[BOTTOM]) / 4.0f;
pts[11].y = ss_fRand( -r[BOTTOM], pts[0].y - disty );
// left side ac's
disty = (r[TOP] - pts[6].y) / 4.0f;
pts[5].y = ss_fRand( pts[6].y + disty, r[TOP]);
disty = (pts[6].y - -r[BOTTOM]) / 4.0f;
pts[7].y = ss_fRand( -r[BOTTOM], pts[6].y - disty );
// top ac's
distx = (r[RIGHT] - pts[3].x) / 4.0f;
pts[2].x = ss_fRand( pts[3].x + distx, r[RIGHT] );
distx = (pts[3].x - -r[LEFT]) / 4.0f;
pts[4].x = ss_fRand( -r[LEFT], pts[3].x - distx );
// bottom ac's
distx = (r[RIGHT] - pts[9].x) / 4.0f;
pts[10].x = ss_fRand( pts[9].x + distx, r[RIGHT] );
distx = (pts[9].x - -r[LEFT]) / 4.0f;
pts[8].x = ss_fRand( -r[LEFT], pts[9].x - distx );
}
/**************************************************************************\
* ConvertPtsZ
*
* Convert the 2D pts in an xc, to 3D pts in point buffer, with z.
*
* Also replicate the last point.
*
* July 28, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
void
XC::ConvertPtsZ( POINT3D *newpts, float z )
{
int i;
POINT2D *xcPts = pts;
for( i = 0; i < numPts; i++, newpts++ ) {
*( (POINT2D *) newpts ) = *xcPts++;
newpts->z = z;
}
*newpts = *(newpts - numPts);
}
/**************************************************************************\
* XC::CalcBoundingBox
*
* Calculate bounding box in x/y plane for xc
*
* July 28, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
void
XC::CalcBoundingBox( )
{
POINT2D *ppts = pts;
int i;
float xMin, xMax, yMax, yMin;
// initialize to really insane numbers
xMax = yMax = -FLT_MAX;
xMin = yMin = FLT_MAX;
// compare with rest of points
for( i = 0; i < numPts; i ++, ppts++ ) {
if( ppts->x < xMin )
xMin = ppts->x;
else if( ppts->x > xMax )
xMax = ppts->x;
if( ppts->y < yMin )
yMin = ppts->y;
else if( ppts->y > yMax )
yMax = ppts->y;
}
xLeft = xMin;
xRight = xMax;
yBottom = yMin;
yTop = yMax;
}
/**************************************************************************\
*
* MinTurnRadius
*
* Get minimum radius for the xc to turn in given direction.
*
* If the turn radius is less than this minimum, then primitive will 'fold'
* over itself at the inside of the turn, creating ugliness.
*
* History
* July 27, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
float
XC::MinTurnRadius( int relDir )
{
//mf: for now, assume xRight, yTop positive, xLeft, yBottom negative
// otherwise, might want to consider 'negative'radius
switch( relDir ) {
case PLUS_X:
return( xRight );
case MINUS_X:
return( - xLeft );
case PLUS_Y:
return( yTop );
case MINUS_Y:
return( - yBottom );
default:
return(0.0f);
}
}
/**************************************************************************\
*
* XC::MaxExtent
*
* Get maximum extent of the xc in x and y
*
* History
* Aug. 1, 95 : [marcfo]
* - Wrote it
*
\**************************************************************************/
float
XC::MaxExtent( )
{
float max;
max = xRight;
if( yTop > max )
max = yTop;
if( -xLeft > max )
max = -xLeft;
if( -yBottom > max )
max = -yBottom;
return max;
}
/**************************************************************************\
*
* XC::Scale
*
* Scale an XC's points and extents by supplied scale value
*
\**************************************************************************/
void
XC::Scale( float scale )
{
int i;
POINT2D *ppts = pts;
for( i = 0; i < numPts; i ++, ppts++ ) {
ppts->x *= scale;
ppts->y *= scale;
}
xLeft *= scale;
xRight *= scale;
yBottom *= scale;
yTop *= scale;
}
/**************************************************************************\
* ~XC::XC
*
* Destructor
*
\**************************************************************************/
XC::~XC()
{
if( pts )
LocalFree( pts );
}
/**************************************************************************\
* XC::XC
*
* Constructor
*
* - Allocates point buffer for the xc
*
\**************************************************************************/
XC::XC( int nPts )
{
numPts = nPts;
pts = (POINT2D *) LocalAlloc( LMEM_FIXED, numPts * sizeof(POINT2D) );
SS_ASSERT( pts != 0, "XC constructor\n" );
}
#if 0
/**************************************************************************\
* XC::XC
*
* Constructor
*
* - Copies data from another XC
*
\**************************************************************************/
//mf: couldn't get calling this to work (compile time)
XC::XC( const XC& xc )
{
numPts = xc.numPts;
pts = (POINT2D *) LocalAlloc( LMEM_FIXED, numPts * sizeof(POINT2D) );
SS_ASSERT( pts != 0, "XC constructor\n" );
RtlCopyMemory( pts, xc.pts, numPts * sizeof(POINT2D) );
xLeft = xc.xLeft;
xRight = xc.xRight;
yBottom = xc.yBottom;
yTop = xc.yTop;
}
#endif
XC::XC( XC *xc )
{
numPts = xc->numPts;
pts = (POINT2D *) LocalAlloc( LMEM_FIXED, numPts * sizeof(POINT2D) );
SS_ASSERT( pts != 0, "XC constructor\n" );
RtlCopyMemory( pts, xc->pts, numPts * sizeof(POINT2D) );
xLeft = xc->xLeft;
xRight = xc->xRight;
yBottom = xc->yBottom;
yTop = xc->yTop;
}
/**************************************************************************\
*
* ELLIPTICAL_XC::ELLIPTICALXC
*
* Elliptical XC constructor
* These have 4 sections of 4 pts each, with pts shared between sections.
*
\**************************************************************************/
ELLIPTICAL_XC::ELLIPTICAL_XC( float r1, float r2 )
// initialize base XC with numPts
: XC( (int) EVAL_XC_CIRC_SECTION_COUNT * (EVAL_ARC_ORDER - 1))
{
SetControlPoints( r1, r2 );
CalcBoundingBox( );
}
/**************************************************************************\
*
* RANDOM4ARC_XC::RANDOM4ARC_XC
*
* Random 4-arc XC constructor
* The bounding box is 2*r each side
* These have 4 sections of 4 pts each, with pts shared between sections.
*
\**************************************************************************/
RANDOM4ARC_XC::RANDOM4ARC_XC( float r )
// initialize base XC with numPts
: XC( (int) EVAL_XC_CIRC_SECTION_COUNT * (EVAL_ARC_ORDER - 1))
{
SetControlPoints( r );
CalcBoundingBox( );
}
| 25.214859 | 77 | 0.43418 | [
"object",
"3d"
] |
1c71a6f20253d395dbac895be4f4072c8a1a67bb | 9,721 | hpp | C++ | include/Nyengine/shader/Shader.hpp | NyantasticUwU/nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | 2 | 2021-12-26T05:10:41.000Z | 2022-01-30T19:51:23.000Z | include/Nyengine/shader/Shader.hpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | include/Nyengine/shader/Shader.hpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | #ifndef NYENGINE_SHADER_SHADER_HPP_INCLUDED
#define NYENGINE_SHADER_SHADER_HPP_INCLUDED
#include "../texture/Texture2D.hpp"
#include "../type/types.hpp"
#include <vector>
/// Contains different shader class types all capable of different things.
namespace nyengine::shader
{
/// Represents an OpenGL shader program.
class Shader
{
using int32_dynamic_t = type::int32_dynamic_t;
using uint32_dynamic_t = type::uint32_dynamic_t;
using float32_dynamic_t = type::float32_dynamic_t;
uint32_dynamic_t m_shaderprogram;
std::vector<uint32_dynamic_t> m_textures;
std::vector<uint32_dynamic_t> m_textureIndexes;
public:
/// Creates a new default shader program.
/// Throws GLException on error.
Shader();
/// Move constructor.
Shader(Shader &&other) noexcept;
/// Creates a new shader program with the specified vert and frag shader sources.
/// Throws GLException on error.
Shader(const char *vertsrc, const char *fragsrc);
// Deleting copy constructor.
Shader(const Shader &) = delete;
/// Cleans up shader resources.
~Shader() noexcept;
// Deleting operator=.
void operator=(const Shader &) = delete;
/// Begin use of the shader.
/// Throws GLException on error.
void use() const;
/// Begin use of the shader for drawing.
/// Throws GLException on error.
void useForDrawing() const;
/// Sets the current camera uniforms for the shader.
/// Throws a GLException on error.
void setCameraUniforms() const;
/// Returns the ID of the shader.
uint32_dynamic_t id() const noexcept;
/// Add a texture to the shader.
/// Throws GLException on error.
void addTexture(const texture::Texture2D &texture, const char *uniform);
/// Removing r-value version of addTexture.
void addTexture(const texture::Texture2D &&, const char *) = delete;
/// Specify the value of a uniform float for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, float32_dynamic_t v0);
/// Specify the value of a uniform vec2 for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, float32_dynamic_t v0, float32_dynamic_t v1);
/// Specify the value of a uniform vec3 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
float32_dynamic_t v0,
float32_dynamic_t v1,
float32_dynamic_t v2);
/// Specify the value of a uniform vec4 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
float32_dynamic_t v0,
float32_dynamic_t v1,
float32_dynamic_t v2,
float32_dynamic_t v3);
/// Specify the value of a uniform int for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, int32_dynamic_t v0);
/// Specify the value of a uniform ivec2 for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, int32_dynamic_t v0, int32_dynamic_t v1);
/// Specify the value of a uniform ivec3 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
int32_dynamic_t v0,
int32_dynamic_t v1,
int32_dynamic_t v2);
/// Specify the value of a uniform ivec4 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
int32_dynamic_t v0,
int32_dynamic_t v1,
int32_dynamic_t v2,
int32_dynamic_t v3);
/// Specify the value of a uniform uint for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, uint32_dynamic_t v0);
/// Specify the value of a uniform uvec2 for the shader.
/// Throws GLException on error.
void setUniform(const char *uniform, uint32_dynamic_t v0, uint32_dynamic_t v1);
/// Specify the value of a uniform uvec3 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
uint32_dynamic_t v0,
uint32_dynamic_t v1,
uint32_dynamic_t v2);
/// Specify the value of a uniform uvec4 for the shader.
/// Throws GLException on error.
void setUniform(
const char *uniform,
uint32_dynamic_t v0,
uint32_dynamic_t v1,
uint32_dynamic_t v2,
uint32_dynamic_t v3);
/// Specify the value of a uniform float[] for the shader.
/// Throws GLException on error.
void setUniformArray(const char *uniform, int32_dynamic_t size, float32_dynamic_t *v);
/// Specify the value of a uniform int[] for the shader.
/// Throws GLException on error.
void setUniformArray(const char *uniform, int32_dynamic_t size, int32_dynamic_t *v);
/// Specify the value of a uniform uint[] for the shader.
/// Throws GLException on error.
void setUniformArray(const char *uniform, int32_dynamic_t size, uint32_dynamic_t *v);
/// Specify the value of a uniform vec2[] for the shader.
/// Throws GLException on error.
void setUniformVec2Array(const char *uniform, int32_dynamic_t size, float32_dynamic_t *v);
/// Specify the value of a uniform vec3[] for the shader.
/// Throws GLException on error.
void setUniformVec3Array(const char *uniform, int32_dynamic_t size, float32_dynamic_t *v);
/// Specify the value of a uniform vec4[] for the shader.
/// Throws GLException on error.
void setUniformVec4Array(const char *uniform, int32_dynamic_t size, float32_dynamic_t *v);
/// Specify the value of a uniform ivec2[] for the shader.
/// Throws GLException on error.
void setUniformIVec2Array(const char *uniform, int32_dynamic_t size, int32_dynamic_t *v);
/// Specify the value of a uniform ivec3[] for the shader.
/// Throws GLException on error.
void setUniformIVec3Array(const char *uniform, int32_dynamic_t size, int32_dynamic_t *v);
/// Specify the value of a uniform ivec4[] for the shader.
/// Throws GLException on error.
void setUniformIVec4Array(const char *uniform, int32_dynamic_t size, int32_dynamic_t *v);
/// Specify the value of a uniform uvec2[] for the shader.
/// Throws GLException on error.
void setUniformUVec2Array(const char *uniform, int32_dynamic_t size, uint32_dynamic_t *v);
/// Specify the value of a uniform uvec3[] for the shader.
/// Throws GLException on error.
void setUniformUVec3Array(const char *uniform, int32_dynamic_t size, uint32_dynamic_t *v);
/// Specify the value of a uniform uvec4[] for the shader.
/// Throws GLException on error.
void setUniformUVec4Array(const char *uniform, int32_dynamic_t size, uint32_dynamic_t *v);
/// Specify the value of a uniform mat2 for the shader.
/// Throws GLException on error.
void setUniformMat2(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat3 for the shader.
/// Throws GLException on error.
void setUniformMat3(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat4 for the shader.
/// Throws GLException on error.
void setUniformMat4(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat2x3 for the shader.
/// Throws GLException on error.
void setUniformMat2x3(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat3x2 for the shader.
/// Throws GLException on error.
void setUniformMat3x2(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat2x4 for the shader.
/// Throws GLException on error.
void setUniformMat2x4(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat4x2 for the shader.
/// Throws GLException on error.
void setUniformMat4x2(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat3x4 for the shader.
/// Throws GLException on error.
void setUniformMat3x4(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
/// Specify the value of a uniform mat4x3 for the shader.
/// Throws GLException on error.
void setUniformMat4x3(
const char *uniform,
int32_dynamic_t size,
bool transpose,
float32_dynamic_t *v);
};
}
#endif
| 37.824903 | 98 | 0.622775 | [
"vector"
] |
1c720834c5066f1e4edd23851b90fda9f7cd4340 | 8,618 | cpp | C++ | Raytracer/Raytracer/RaytracerRenderer.cpp | Krien/RaytracerSDL | fd64c34f2584abc6a1933f332ac3da78907420ae | [
"Apache-2.0"
] | null | null | null | Raytracer/Raytracer/RaytracerRenderer.cpp | Krien/RaytracerSDL | fd64c34f2584abc6a1933f332ac3da78907420ae | [
"Apache-2.0"
] | null | null | null | Raytracer/Raytracer/RaytracerRenderer.cpp | Krien/RaytracerSDL | fd64c34f2584abc6a1933f332ac3da78907420ae | [
"Apache-2.0"
] | null | null | null | #include "precomp.h"
RaytracerRenderer::RaytracerRenderer(Screen* screen) : Renderer(screen)
{
width = screen->getWidth();
height = screen->getHeight();
}
RaytracerRenderer::~RaytracerRenderer()
{
}
void RaytracerRenderer::draw(int iteration)
{
assert(currentScene != NULL && camera != NULL);
shapes = currentScene->objects;
shapeSize = shapes.size();
lights = currentScene->lights;
lightSize = lights.size();
Vec3Df rayStartDir = camera->getTopLeft();
Vec3Df xOffset = Vec3Df( (camera->getTopRight() - camera->getTopLeft()) / (width - 1));
Vec3Df yOffset = Vec3Df((camera->getBottomLeft() - camera->getTopLeft()) / (height - 1));
#pragma unroll
for (unsigned int y = 0; y < height; y++)
{
for (unsigned int x = 0; x < width; x+=2)
{
// Pixel 1.....
// Make ray
Vec3Df direction = rayStartDir + Vec3Df(x)* xOffset + Vec3Df(y)*yOffset;
direction -= camera->position;
direction = normalize_vector(direction);
lastId = -1;
Ray r = { camera->position, direction, 100,1.000293f, 1.000586f };
// Check for hits
Vec3Df argb = trace(r,0) * Vec3Df(255);
// Convert color
unsigned int xy = x*4 + (y * width)*4;
*(pixelBuffer + xy) = std::min((int)argb.extract(0), 255);
*(pixelBuffer + xy+1) = std::min((int)argb.extract(1), 255);
*(pixelBuffer + xy+2) = std::min((int)argb.extract(2), 255);
*(pixelBuffer + xy+3) = 0;
// Pixel 2....
// Make ray
direction = rayStartDir + Vec3Df(x+1) * xOffset + Vec3Df(y) * yOffset;
direction -= camera->position;
direction = normalize_vector(direction);
lastId = -1;
r = { camera->position, direction, 100,1.000293f, 1.000586f };
// Check for hits
argb = trace(r, 0) * Vec3Df(255);
// Pixel 1
// Convert color
xy = x * 4 + (y * width) * 4;
*(pixelBuffer + xy+4) = std::min((int)argb.extract(0),255);
*(pixelBuffer + xy + 5) = std::min((int)argb.extract(1),255);
*(pixelBuffer + xy + 6) = std::min((int)argb.extract(2), 255);
*(pixelBuffer + xy + 7) = 0;
}
}
}
Vec3Df RaytracerRenderer::trace(Ray ray, int depth)
{
if (depth > RAYTRACER_RECURSION_DEPTH)
return Vec3Df(0);
HitInfo hitInfo = { Vec3Df(0),Vec3Df(0),1000 };
for (size_t i = 0; i < shapeSize; i++)
{
shapes[i]->hit(ray, &hitInfo);
}
// Not a hit, so return
if (hitInfo.distance > RAYTRACER_MAX_RENDERDISTANCE)
{
return Vec3Df(0);
}
if (hitInfo.material.mirror == 0 && hitInfo.material.refracIndex <= 1)
{
return calculateLight(hitInfo, ray.direction)*hitInfo.material.diffuseColor;
}
else if(hitInfo.material.refracIndex <= 1)
{
Vec3Df normalCol = calculateLight(hitInfo, ray.direction) * hitInfo.material.diffuseColor;
Vec3Df mirrCol = hitInfo.material.diffuseColor*trace(mirrorRay(ray.direction, hitInfo), depth + 1);
Vec3Df finalCol = mirrCol * Vec3Df(hitInfo.material.mirror) + normalCol * (Vec3Df(1 - hitInfo.material.mirror));
return finalCol;
}
else
{
// Init beers law
Vec3Df k = Vec3Df(1);
float c = 0;
lastId = hitInfo.id;
// Obtuse angle
if (dot_product(ray.direction, hitInfo.normal) < 0)
{
float cosTheta = rayCosTheta(ray, hitInfo.normal, hitInfo.material.refracIndex);
bool refracted = cosTheta >= 0;
Vec3Df refractDir = refracted ? refractRay(ray, hitInfo.normal, hitInfo.material.refracIndex, cosTheta) : Vec3Df(0);
Ray refractedRay = { hitInfo.hitPos + refractDir * Vec3Df(RAY_MIGRAINE), refractDir, 1000 };
c = dot_product(-ray.direction, hitInfo.normal);
// Calculate the reflectance at normal incidence.
float R0 = ((hitInfo.material.refracIndex - 1) * (hitInfo.material.refracIndex - 1)) / ((hitInfo.material.refracIndex + 1) * (hitInfo.material.refracIndex + 1));
// Calculate schlick's approximation (amount of % the refraction contributes to the total).
float R = R0 + (1 - R0) * pow((1 - c), 5);
// The ray has now hit something refractive, if two spheres border each other we want them to refract off each other's indices and not the indice of air, and thus we set the last hit refract indice for the ray.
if (lastId == hitInfo.id)
{
ray.refracIndex = 1.000293f;
ray.refracIndex2 = 1.000586f;
}
else
{
ray.refracIndex = hitInfo.material.refracIndex;
ray.refracIndex2 = hitInfo.material.refracIndex * hitInfo.material.refracIndex;
}
// Return percentage of mirror and refraction that results from the above calculations, where R is the amount reflected and 1-R the amount refracted.
return k * (R * trace(mirrorRay(ray.direction, hitInfo), depth + 1)) + (1 - R) * trace(refractedRay, depth + 1);
}
else
{
float cosTheta = rayCosTheta(ray, -hitInfo.normal, 1/hitInfo.material.refracIndex);
bool refracted = cosTheta >= 0;
Vec3Df refractDir = refracted ? refractRay(ray, -hitInfo.normal, 1/hitInfo.material.refracIndex, cosTheta) : Vec3Df(0);
Vec3Df power = -hitInfo.material.absorbtion * refractDir;
k = Vec3Df(pow(E, power[0]), pow(E, power[1]), pow(E, power[2]));
if (!refracted)
{
return k * trace(mirrorRay(ray.direction, hitInfo), depth + 1);
}
Ray refractedRay = { hitInfo.hitPos + refractDir * Vec3Df(RAY_MIGRAINE), refractDir, 1000 };
c = dot_product(ray.direction, hitInfo.normal);
// Calculate the reflectance at normal incidence.
float R0 = ((hitInfo.material.refracIndex - 1) * (hitInfo.material.refracIndex - 1)) / ((hitInfo.material.refracIndex + 1) * (hitInfo.material.refracIndex + 1));
// Calculate schlick's approximation (amount of % the refraction contributes to the total).
float R = R0 + (1 - R0) * pow((1 - c), 5);
// The ray has now hit something refractive, if two spheres border each other we want them to refract off each other's indices and not the indice of air, and thus we set the last hit refract indice for the ray.
if (lastId == hitInfo.id)
{
ray.refracIndex = 1.000293f;
ray.refracIndex2 = 1.000586f;
}
else
{
ray.refracIndex = hitInfo.material.refracIndex;
ray.refracIndex2 = hitInfo.material.refracIndex* hitInfo.material.refracIndex;
}
// Return percentage of mirror and refraction that results from the above calculations, where R is the amount reflected and 1-R the amount refracted.
return k * (R * trace(mirrorRay(ray.direction, hitInfo), depth + 1)) + (1 - R) * trace(refractedRay, depth + 1);
}
}
}
Vec3Df RaytracerRenderer::calculateLight(HitInfo hitI, Vec3Df direction)
{
Vec3Df argb = hitI.material.ambientColor;
for (Light* l : lights)
{
Vec3Df lightDist = l->position - hitI.hitPos;
Vec3Df lightV = normalize_vector(lightDist);
//If we cannot reach this light from the intersection point we go on to the next light.
if (dot_product(hitI.normal, lightDist) < 0)
continue;
// blocked
Vec3Df shadowOrigin = hitI.hitPos + lightV * Vec3Df(RAY_MIGRAINE);
float shadowLength = (float)(vector_length(lightDist) - 2 * RAY_MIGRAINE);
Ray shadowR = { shadowOrigin, lightV, shadowLength };
for (size_t i = 0; i < shapeSize; i++)
{
if (shapes[i]->fastHit(shadowR))
continue;
}
// Diffuse
Vec3Df halfVector = normalize_vector(lightV - direction);
Vec3Df diffuse = l->intensity / vector_length(lightDist);
// Blinn phong
Vec3Df blinnphong = hitI.material.diffuseColor * l->intensity * Vec3Df(std::max(0.0f, dot_product(hitI.normal, lightV)));
Vec3Df specular = hitI.material.diffuseColor * hitI.material.specularColor * l->intensity;
specular *= Vec3Df( (float)pow(std::max(0.0f, dot_product(hitI.normal, halfVector)), BLINN_PHONG_POWER) );
blinnphong += specular;
Vec3Df lightColor = diffuse * blinnphong;
argb += lightColor;
}
return argb;
}
Ray RaytracerRenderer::mirrorRay(Vec3Df originalDir, HitInfo hitSurface)
{
Vec3Df mirrDir = originalDir - (hitSurface.normal * Vec3Df((2.0f * dot_product(originalDir, hitSurface.normal))));
mirrDir = normalize_vector(mirrDir);
Ray mirrorRay = Ray{ hitSurface.hitPos + Vec3Df(RAY_MIGRAINE) * mirrDir, mirrDir, 1000,1.000293f, 1.000586f };
return mirrorRay;
}
float RaytracerRenderer::rayCosTheta(Ray r, Vec3Df normal, float rIndex)
{
float dotDirNor = dot_product(r.direction, normal);
float cosVal = (1.0f - (r.refracIndex2 * (1.0f - (dotDirNor* dotDirNor))) / (rIndex * rIndex));
return cosVal;
}
Vec3Df RaytracerRenderer::refractRay(Ray r, Vec3Df normal, float rIndex, float rayCosTheta)
{
// Calculate the sine of the phi angle of the transmission vector t.
Vec3Df sinPhi = (r.refracIndex * (r.direction - normal * dot_product(r.direction, normal))) / rIndex;
// Calculate the finale refraction direction
Vec3Df refractDir = normalize_vector(sinPhi - normal * Vec3Df(sqrtf(rayCosTheta)));
return refractDir;
}
| 39.53211 | 213 | 0.691692 | [
"vector"
] |
1c782b4304e5db03beb30707083f416cc7906e91 | 1,002 | cpp | C++ | vol3/max-points-on-a-line/max-points-on-a-line.cpp | zeyuanxy/LeetCode | fab1b6ea07249d7024f37a8f4bbef9d397edc3ec | [
"MIT"
] | 3 | 2015-12-07T05:40:08.000Z | 2018-12-17T18:39:15.000Z | vol3/max-points-on-a-line/max-points-on-a-line.cpp | zeyuanxy/leet-code | fab1b6ea07249d7024f37a8f4bbef9d397edc3ec | [
"MIT"
] | null | null | null | vol3/max-points-on-a-line/max-points-on-a-line.cpp | zeyuanxy/leet-code | fab1b6ea07249d7024f37a8f4bbef9d397edc3ec | [
"MIT"
] | null | null | null | /**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point> &points) {
if(points.size() == 0)
return 0;
map<double, int> mp;
int ans = 1;
for(int i = 0; i < points.size(); ++ i) {
mp.clear();
int maxValue = 0;
int duplicate = 1;
for(int j = i + 1; j < points.size(); ++ j)
if(points[i].x == points[j].x && points[i].y == points[j].y)
duplicate ++;
else {
double k = (points[i].x == points[j].x) ? INT_MAX : (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
mp[k] ++;
maxValue = max(maxValue, mp[k]);
}
ans = max(ans, maxValue + duplicate);
}
return ans;
}
}; | 29.470588 | 138 | 0.4002 | [
"vector"
] |
cc663d64d30b96413ac8660869d31dfa5c8118bd | 527 | cpp | C++ | 2021/day_01/day_01.cpp | andrewparr/advent-of-code | f2b476ac837e1d42d180418e81abf900e9c3a1b6 | [
"Unlicense"
] | null | null | null | 2021/day_01/day_01.cpp | andrewparr/advent-of-code | f2b476ac837e1d42d180418e81abf900e9c3a1b6 | [
"Unlicense"
] | null | null | null | 2021/day_01/day_01.cpp | andrewparr/advent-of-code | f2b476ac837e1d42d180418e81abf900e9c3a1b6 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
int main(int argc, char** argv) {
std::vector<int> input;
while (!std::cin.eof()) {
int value;
std::cin >> value;
input.push_back(value);
}
int part_1 = 0;
int part_2 = 0;
for (size_t i = 1; i < input.size(); ++i) {
if (input[i] > input[i-1])
part_1++;
if (i > 2 && input[i] > input[i-3])
part_2++;
}
std::cout << part_1 << std::endl;
std::cout << part_2 << std::endl;
return 0;
} | 20.269231 | 47 | 0.478178 | [
"vector"
] |
cc676ef86dbc926266f5b9cd5fedd11efeed1eaf | 2,351 | hxx | C++ | OcctQtWidget/OcctQtLib/libscetcher/Sketcher_CommandCircleCenterRadius.hxx | grotius-cnc/occt-samples-qopenglwidget | d88871c6435ebabe29ccc7ea922edd9d64bb2df8 | [
"MIT"
] | 1 | 2022-02-04T11:56:59.000Z | 2022-02-04T11:56:59.000Z | OcctQtWidget/OcctQtLib/libscetcher/Sketcher_CommandCircleCenterRadius.hxx | grotius-cnc/occt-samples-qopenglwidget | d88871c6435ebabe29ccc7ea922edd9d64bb2df8 | [
"MIT"
] | null | null | null | OcctQtWidget/OcctQtLib/libscetcher/Sketcher_CommandCircleCenterRadius.hxx | grotius-cnc/occt-samples-qopenglwidget | d88871c6435ebabe29ccc7ea922edd9d64bb2df8 | [
"MIT"
] | null | null | null | /**
* \file Sketcher_CommandCircleCenterRadius.hxx
* \brief Header file for the class Sketcher_CommandCircleCenterRadius
* \author <a href="mailto:sergmaslov@istel.ru?subject=Sketcher_CommandCircleCenterRadius.hxx">Sergei Maslov</a>
*/
#ifndef Sketcher_CommandCIRCLECENTERRADIUS_H
#define Sketcher_CommandCIRCLECENTERRADIUS_H
#include "Sketcher_Command.hxx"
#include <Geom2d_CartesianPoint.hxx>
#include <Geom2d_Circle.hxx>
#include <Geom_CartesianPoint.hxx>
#include <Geom_Circle.hxx>
#include <AIS_Circle.hxx>
#include <gp_Ax2d.hxx>
class Geom_Circle;
class AIS_Circle;
class AIS_Line;
DEFINE_STANDARD_HANDLE(Sketcher_CommandCircleCenterRadius,Sketcher_Command)
//Command entering Circle by Center point and other point
class Sketcher_CommandCircleCenterRadius : public Sketcher_Command
{
public:
// Type management
DEFINE_STANDARD_RTTIEXT(Sketcher_CommandCircleCenterRadius, Sketcher_Command)
enum CircleCenterRadiusAction { Nothing,Input_CenterPoint,Input_RadiusPoint };
/**
* \fn Sketcher_CommandCircleCenterRadius()
* \brief Constructs a Sketcher_CommandCircleCenterRadius
*/
Standard_EXPORT Sketcher_CommandCircleCenterRadius();
/**
* \fn ~Sketcher_CommandCircleCenterRadius()
* \brief destructor
*/
Standard_EXPORT ~Sketcher_CommandCircleCenterRadius();
/**
* \fn Action()
* \brief turn command to active state
*/
Standard_EXPORT void Action();
/**
* \fn MouseInputEvent(const gp_Pnt2d& thePnt2d )
* \brief input event handler
* \return Standard_Boolean
* \param thePnt2d const gp_Pnt2d&
*/
Standard_EXPORT Standard_Boolean MouseInputEvent(const gp_Pnt2d& thePnt2d, bool ortho);
/**
* \fn MouseMoveEvent(const gp_Pnt2d& thePnt2d )
* \brief mouse move handler
* \return void
* \param thePnt2d const gp_Pnt2d&
*/
Standard_EXPORT void MouseMoveEvent(const gp_Pnt2d& thePnt2d, bool ortho);
/**
* \fn CancelEvent()
* \brief cancel event handler, stop entering object
* \return void
*/
Standard_EXPORT void CancelEvent();
/**
* \fn GetTypeOfMethod()
* \brief get command Method
* \return Sketcher_ObjectTypeOfMethod
*/
Standard_EXPORT Sketcher_ObjectTypeOfMethod GetTypeOfMethod();
private:
//members
CircleCenterRadiusAction myCircleCenterRadiusAction;
Standard_Real radius;
Handle(Geom_Circle) tempGeom_Circle;
Handle(AIS_Circle) myRubberCircle;
gp_Ax2d myCircleAx2d;
};
#endif
| 25.27957 | 111 | 0.790302 | [
"object"
] |
cc6ca3209f7b44ab246d913e785743316ccf4744 | 5,155 | cxx | C++ | src/AcdUtilFuncs.cxx | fermi-lat/AcdUtil | 0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09 | [
"BSD-3-Clause"
] | null | null | null | src/AcdUtilFuncs.cxx | fermi-lat/AcdUtil | 0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09 | [
"BSD-3-Clause"
] | null | null | null | src/AcdUtilFuncs.cxx | fermi-lat/AcdUtil | 0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09 | [
"BSD-3-Clause"
] | null | null | null | #include "../AcdUtil/AcdUtilFuncs.h"
#include <set>
namespace AcdUtil {
/**
* @brief Fill an AcdEventToplogy object from a list of AcdHits
* @param acdHits the hit
* @param topology the topology object
**/
bool UtilFunctions::fillAcdEventTopology(const std::vector<Event::AcdHit*>& acdHits,
Event::AcdEventTopology& evtTopo){
unsigned tileCount(0),ribbonCount(0),vetoCount(0),tileVeto(0);
float totalTileEnergy(0),totalRibbonEnergy(0);
float tileEnergy(0),ribbonEnergy(0);
float ghostTileEnergy(0),ghostRibbonEnergy(0);
float triggerTileEnergy(0),triggerRibbonEnergy(0);
unsigned nTilesTop(0);
unsigned nTilesSideRow[4] = {0,0,0,0};
unsigned nTilesSideFace[4] = {0,0,0,0};
unsigned nVetoTop(0);
unsigned nVetoSideRow[4] = {0,0,0,0};
unsigned nVetoSideFace[4] = {0,0,0,0};
float tileEnergyTop(0);
float tileEnergySideRow[4] = {0.,0.,0.,0.};
float tileEnergySideFace[4] = {0.,0.,0.,0.};
unsigned nSidesHit(0),nSidesVeto(0);
std::set<int> sidesHit;
std::set<int> sidesVeto;
for ( Event::AcdHitCol::const_iterator itr = acdHits.begin(); itr != acdHits.end(); itr++ ) {
Event::AcdHit* theHit = *itr;
const idents::AcdId& id = theHit->getAcdId();
bool hasGhost = theHit->getGhost();
bool hasTrigger = theHit->getTriggerVeto();
if ( hasTrigger) vetoCount++;
if ( id.tile() ) {
tileCount++;
sidesHit.insert( id.face() );
if ( hasTrigger ) {
sidesVeto.insert( id.face() );
tileVeto++;
switch ( id.face() ) {
case 0:
nVetoTop++;
break;
case 1: case 2: case 3: case 4:
nVetoSideFace[id.face()-1]++;
nVetoSideRow[id.row()]++;
}
}
float energy = theHit->tileEnergy();
totalTileEnergy += energy;
tileEnergy += energy*!hasGhost;
ghostTileEnergy += energy*hasGhost;
triggerTileEnergy += energy*hasTrigger;
switch ( id.face() ) {
case 0:
nTilesTop++;
tileEnergyTop += energy;
break;
case 1:
case 2:
case 3:
case 4:
nTilesSideFace[id.face() - 1]++;
tileEnergySideFace[id.face() - 1] += energy;
nTilesSideRow[id.row()]++;
tileEnergySideRow[id.row()] += energy;
break;
}
} else if ( id.ribbon() ) {
ribbonCount++;
float energy = theHit->ribbonEnergy( Event::AcdHit::A ) + theHit->ribbonEnergy( Event::AcdHit::B );
energy /= 2.;
totalRibbonEnergy += energy;
ribbonEnergy += energy*!hasGhost;
ghostRibbonEnergy += energy*hasGhost;
triggerRibbonEnergy += energy*hasTrigger;
}
}
nSidesHit = sidesHit.size();
nSidesVeto = sidesVeto.size();
evtTopo.set( tileCount, ribbonCount, vetoCount, tileVeto,
totalTileEnergy, totalRibbonEnergy, tileEnergy, ribbonEnergy,
ghostTileEnergy, ghostRibbonEnergy, triggerTileEnergy, triggerRibbonEnergy,
nTilesTop, nTilesSideRow, nTilesSideFace,
nVetoTop, nVetoSideRow, nVetoSideFace,
tileEnergyTop, tileEnergySideRow, tileEnergySideFace,
nSidesHit, nSidesVeto);
return true;
}
/**
* @brief fill cone energies from a set of AcdTkrHitPoca
*
* @param hitPocae the AcdTkrHitPoca
* @param energy15 (energy in tiles within 15 degrees of the track)
* @param energy30 (energy in tiles within 30 degrees of the track)
* @param energy45 (energy in tiles within 45 degrees of the track)
* @param triggerEnergy15 (energy within 15 degrees of the track for tiles with veto asserted)
* @param triggerEnergy30 (energy within 30 degrees of the track for tiles with veto asserted)
* @param triggerEnergy45 (energy within 45 degrees of the track for tiles with veto asserted)
**/
bool UtilFunctions::getConeEnergies(const std::vector<Event::AcdTkrHitPoca*>& hitPocae,
float& energy15, float& energy30, float& energy45,
float& triggerEnergy15, float& triggerEnergy30, float& triggerEnergy45) {
energy15 = energy30 = energy45 = 0.;
triggerEnergy15 = triggerEnergy30 = triggerEnergy45 = 0.;
static const double tan45 = 1.;
static const double tan30 = 5.77350288616910401e-01;
static const double tan15 = 2.67949200239410490e-01;
for ( std::vector<Event::AcdTkrHitPoca*>::const_iterator itr = hitPocae.begin(); itr != hitPocae.end(); itr++ ) {
const Event::AcdTkrHitPoca* hitPoca = *itr;
// Don't include ribbons
if ( hitPoca->getId().ribbon() ) continue;
// Don't include stuff without hits
if ( ! hitPoca->hasHit() ) continue;
float tanAngle = ( -1 * hitPoca->getDoca() )/ hitPoca->getArcLength();
float energy = hitPoca->tileEnergy();
if (tanAngle < tan45) {
if ( ! hitPoca->getGhost() ) {
energy45 += energy;
}
if ( hitPoca->getTriggerVeto() ) {
triggerEnergy45 += energy;
}
if (tanAngle < tan30) {
if ( ! hitPoca->getGhost() ) {
energy30 += energy;
}
if ( hitPoca->getTriggerVeto() ) {
triggerEnergy30 += energy;
}
if (tanAngle < tan15) {
if ( ! hitPoca->getGhost() ) {
energy15 += energy;
}
if ( hitPoca->getTriggerVeto() ) {
triggerEnergy15 += energy;
}
}
}
}
}
}
}
| 31.625767 | 117 | 0.644229 | [
"object",
"vector"
] |
cc784708fd53917ddf69231c864bc8d8063422bb | 9,364 | cc | C++ | RecoVertex/KinematicFit/src/LagrangeParentParticleFitter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoVertex/KinematicFit/src/LagrangeParentParticleFitter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoVertex/KinematicFit/src/LagrangeParentParticleFitter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "RecoVertex/KinematicFit/interface/LagrangeParentParticleFitter.h"
#include "RecoVertex/KinematicFitPrimitives/interface/KinematicVertexFactory.h"
#include "RecoVertex/KinematicFit/interface/InputSort.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
LagrangeParentParticleFitter::LagrangeParentParticleFitter()
{defaultParameters();}
/*
RefCountedKinematicTree LagrangeParentParticleFitter::fit(RefCountedKinematicTree tree, KinematicConstraint * cs) const
{
//fitting top paticle only
tree->movePointerToTheTop();
RefCountedKinematicParticle particle = tree->currentParticle();
RefCountedKinematicVertex inVertex = tree->currentDecayVertex();
//parameters and covariance matrix of the particle to fit
AlgebraicVector par = particle->currentState().kinematicParameters().vector();
AlgebraicSymMatrix cov = particle->currentState().kinematicParametersError().matrix();
//chi2 and ndf
float chi = 0.;
float ndf = 0.;
//constraint
//here it is defined at 7-point
//taken just at current state parameters
AlgebraicVector vl;
AlgebraicMatrix dr;
AlgebraicVector dev;
//initial expansion point
AlgebraicVector exPoint = particle->currentState().kinematicParameters().vector();
//refitted parameters and covariance matrix:
//simple and symmetric
AlgebraicVector refPar;
AlgebraicSymMatrix refCovS;
int nstep = 0;
double df = 0.;
do{
chi = particle->chiSquared();
ndf = particle->degreesOfFreedom();
df = 0.;
//derivative and value at expansion point
vl = cs->value(exPoint).first;
dr = cs->derivative(exPoint).first;
dev = cs->deviations();
//residual between expansion and current parameters
//0 at the first step
AlgebraicVector delta_alpha = par - exPoint;
//parameters needed for refit
// v_d = (D * V_alpha & * D.T)^(-1)
AlgebraicMatrix drt = dr.T();
AlgebraicMatrix v_d = dr * cov * drt;
int ifail = 0;
v_d.invert(ifail);
if(ifail != 0) throw VertexException("ParentParticleFitter::error inverting covariance matrix");
//lagrangian multipliers
//lambda = V_d * (D * delta_alpha + d)
AlgebraicVector lambda = v_d * (dr*delta_alpha + vl);
//refitted parameters
refPar = par - (cov * drt * lambda);
//refitted covariance: simple and SymMatrix
refCovS = cov;
AlgebraicMatrix sPart = drt * v_d * dr;
AlgebraicMatrix covF = cov * sPart * cov;
AlgebraicSymMatrix sCovF(7,0);
for(int i = 1; i<8; i++)
{
for(int j = 1; j<8; j++)
{if(i<=j) sCovF(i,j) = covF(i,j);}
}
refCovS -= sCovF;
for(int i = 1; i < 8; i++)
{refCovS(i,i) += dev(i);}
//chiSquared
chi += (lambda.T() * (dr*delta_alpha + vl))(1);
ndf += cs->numberOfEquations();
//new expansionPoint
exPoint = refPar;
AlgebraicVector vlp = cs->value(exPoint).first;
for(int i = 1; i< vl.num_row();i++)
{df += std::abs(vlp(i));}
nstep++;
}while(df>theMaxDiff && nstep<theMaxStep);
//!!!!!!!!!!!!!!!here the math part is finished!!!!!!!!!!!!!!!!!!!!!!
//creating an output KinematicParticle
//and putting it on its place in the tree
KinematicParameters param(refPar);
KinematicParametersError er(refCovS);
KinematicState kState(param,er,particle->initialState().particleCharge());
RefCountedKinematicParticle refParticle = particle->refittedParticle(kState,chi,ndf,cs->clone());
tree->replaceCurrentParticle(refParticle);
//replacing the vertex with its refitted version
GlobalPoint nvPos(param.vector()(1), param.vector()(2), param.vector()(3));
AlgebraicSymMatrix nvMatrix = er.matrix().sub(1,3);
GlobalError nvError(asSMatrix<3>(nvMatrix));
VertexState vState(nvPos, nvError, 1.0);
KinematicVertexFactory vFactory;
RefCountedKinematicVertex nVertex = vFactory.vertex(vState, inVertex,chi,ndf);
tree->replaceCurrentVertex(nVertex);
return tree;
}
*/
std::vector<RefCountedKinematicTree> LagrangeParentParticleFitter::fit(const std::vector<RefCountedKinematicTree> &trees,
KinematicConstraint * cs)const
{
InputSort iSort;
std::vector<RefCountedKinematicParticle> prt = iSort.sort(trees);
int nStates = prt.size();
//making full initial parameters and covariance
AlgebraicVector part(7*nStates,0);
AlgebraicSymMatrix cov(7*nStates,0);
AlgebraicVector chi_in(nStates,0);
AlgebraicVector ndf_in(nStates,0);
int l_c=0;
for(std::vector<RefCountedKinematicParticle>::const_iterator i = prt.begin(); i != prt.end(); i++)
{
AlgebraicVector7 lp = (*i)->currentState().kinematicParameters().vector();
for(int j = 1; j != 8; j++){part(7*l_c + j) = lp(j-1);}
AlgebraicSymMatrix lc= asHepMatrix<7>((*i)->currentState().kinematicParametersError().matrix());
cov.sub(7*l_c+1,lc);
chi_in(l_c+1) = (*i)->chiSquared();
ndf_in(l_c+1) = (*i)->degreesOfFreedom();
l_c++;
}
//refitted parameters and covariance matrix:
//simple and symmetric
AlgebraicVector refPar;
AlgebraicSymMatrix refCovS;
//constraint values, derivatives and deviations:
AlgebraicVector vl;
AlgebraicMatrix dr;
AlgebraicVector dev;
int nstep = 0;
double df = 0.;
AlgebraicVector exPoint = part;
//this piece of code should later be refactored:
// The algorithm is the same as above, but the
// number of refitted particles is >1. Smart way of
// refactoring should be chosen for it.
AlgebraicVector chi;
AlgebraicVector ndf;
// cout<<"Starting the main loop"<<endl;
do{
df = 0.;
chi = chi_in;
ndf = ndf_in;
// cout<<"Iterational linearization point: "<<exPoint<<endl;
vl = cs->value(exPoint).first;
dr = cs->derivative(exPoint).first;
dev = cs->deviations(nStates);
// cout<<"The value : "<<vl<<endl;
// cout<<"The derivative: "<<dr<<endl;
// cout<<"deviations: "<<dev<<endl;
// cout<<"covariance "<<cov<<endl;
//residual between expansion and current parameters
//0 at the first step
AlgebraicVector delta_alpha = part - exPoint;
//parameters needed for refit
// v_d = (D * V_alpha & * D.T)^(-1)
AlgebraicMatrix drt = dr.T();
AlgebraicMatrix v_d = dr * cov * drt;
int ifail = 0;
v_d.invert(ifail);
if(ifail != 0) {
LogDebug("KinematicConstrainedVertexFitter")
<< "Fit failed: unable to invert covariance matrix\n";
return std::vector<RefCountedKinematicTree>();
}
//lagrangian multipliers
//lambda = V_d * (D * delta_alpha + d)
AlgebraicVector lambda = v_d * (dr*delta_alpha + vl);
//refitted parameters
refPar = part - (cov * drt * lambda);
//refitted covariance: simple and SymMatrix
refCovS = cov;
AlgebraicMatrix sPart = drt * v_d * dr;
AlgebraicMatrix covF = cov * sPart * cov;
//total covariance symmatrix
AlgebraicSymMatrix sCovF(nStates*7,0);
for(int i = 1; i< nStates*7 +1; ++i)
{
for(int j = 1; j< nStates*7 +1; j++)
{if(i<=j) sCovF(i,j) = covF(i,j);}
}
refCovS -= sCovF;
// cout<<"Fitter: refitted covariance "<<refCovS<<endl;
for(int i = 1; i < nStates+1; i++)
{for(int j = 1; j<8; j++){refCovS((i-1)+j,(i-1)+j) += dev(j);}}
//chiSquared
for(int k =1; k<nStates+1; k++)
{
chi(k) += (lambda.T() * (dr*delta_alpha + vl))(1);
ndf(k) += cs->numberOfEquations();
}
//new expansionPoint
exPoint = refPar;
AlgebraicVector vlp = cs->value(exPoint).first;
for(int i = 1; i< vl.num_row();i++)
{df += std::abs(vlp(i));}
nstep++;
}while(df>theMaxDiff && nstep<theMaxStep);
//here math and iterative part is finished, starting an output production
//creating an output KinematicParticle and putting it on its place in the tree
//vector of refitted particles and trees
std::vector<RefCountedKinematicParticle> refPart;
std::vector<RefCountedKinematicTree> refTrees = trees;
int j=1;
std::vector<RefCountedKinematicTree>::const_iterator tr = refTrees.begin();
for(std::vector<RefCountedKinematicParticle>::const_iterator i = prt.begin(); i!= prt.end(); i++)
{
AlgebraicVector7 lRefPar;
for(int k = 1; k<8 ; k++)
{lRefPar(k-1) = refPar((j-1)*7+k);}
AlgebraicSymMatrix77 lRefCovS = asSMatrix<7>(refCovS.sub((j-1)*7 +1,(j-1)*7+7));
//new refitted parameters and covariance
KinematicParameters param(lRefPar);
KinematicParametersError er(lRefCovS);
KinematicState kState(param,er,(*i)->initialState().particleCharge(), (**i).magneticField());
RefCountedKinematicParticle refParticle = (*i)->refittedParticle(kState,chi(j),ndf(j),cs->clone());
//replacing particle itself
(*tr)->findParticle(*i);
RefCountedKinematicVertex inVertex = (*tr)->currentDecayVertex();
(*tr)->replaceCurrentParticle(refParticle);
//replacing the vertex with its refitted version
GlobalPoint nvPos(param.position());
AlgebraicSymMatrix nvMatrix = asHepMatrix<7>(er.matrix()).sub(1,3);
GlobalError nvError(asSMatrix<3>(nvMatrix));
VertexState vState(nvPos, nvError, 1.0);
KinematicVertexFactory vFactory;
RefCountedKinematicVertex nVertex = vFactory.vertex(vState,inVertex,chi(j),ndf(j));
(*tr)->replaceCurrentVertex(nVertex);
tr++;
j++;
}
return refTrees;
}
void LagrangeParentParticleFitter::setParameters(const edm::ParameterSet& pSet)
{
theMaxDiff = pSet.getParameter<double>("maxDistance");
theMaxStep = pSet.getParameter<int>("maxNbrOfIterations");;
}
void LagrangeParentParticleFitter::defaultParameters()
{
theMaxDiff = 0.001;
theMaxStep = 100;
}
| 32.627178 | 123 | 0.688167 | [
"vector"
] |
cc7eb8da40ff83f0b7fcac02d5328486cd1785e7 | 1,253 | inl | C++ | include/Nazara/Core/CallOnExit.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Core/CallOnExit.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Core/CallOnExit.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::CallOnExit
* \brief Core class that represents a function to call at the end of the scope
*/
/*!
* \brief Constructs a CallOnExit object with a functor
*
* \param func Function to call on exit
*/
template<typename F>
CallOnExit<F>::CallOnExit(F&& functor) :
m_functor(std::move(functor))
{
}
/*!
* \brief Destructs the object and calls the function
*/
template<typename F>
CallOnExit<F>::~CallOnExit()
{
if (m_functor)
(*m_functor)();
}
/*!
* \brief Calls the function and sets the new callback
*
* \param func Function to call on exit
*/
template<typename F>
void CallOnExit<F>::CallAndReset()
{
if (m_functor)
(*m_functor)();
m_functor.reset();
}
/*!
* \brief Resets the function
*
* \param func Function to call on exit
*/
template<typename F>
void CallOnExit<F>::Reset()
{
m_functor.reset();
}
}
#include <Nazara/Core/DebugOff.hpp>
| 19.276923 | 79 | 0.680766 | [
"object"
] |
cc85ff5f6a9a8ea74dfa7ac765cdc54eef627752 | 1,046 | cc | C++ | blurt_cpp_80211/qam.cc | saydulk/blurt | 0ce647c8260fac55ddafd994fdef1bfed05553fa | [
"MIT"
] | 5 | 2015-02-20T14:18:28.000Z | 2022-03-18T13:35:20.000Z | blurt_cpp_80211/qam.cc | saydulk/blurt | 0ce647c8260fac55ddafd994fdef1bfed05553fa | [
"MIT"
] | null | null | null | blurt_cpp_80211/qam.cc | saydulk/blurt | 0ce647c8260fac55ddafd994fdef1bfed05553fa | [
"MIT"
] | 9 | 2017-04-27T07:55:11.000Z | 2019-04-19T10:16:03.000Z | #include "qam.h"
#include <cmath>
#include <stdint.h>
uint32_t grayRevToBinary(uint32_t x, uint32_t n) {
uint32_t y = 0;
for (size_t i=0; i<n; i++) {
y <<= 1;
y |= x&1;
x >>= 1;
}
for (size_t shift=1; shift<n; shift<<=1)
y ^= y >> shift;
return y;
}
QAM::QAM(size_t Nbpsc) : Constellation(Nbpsc) {
float scale = 1.f;
size_t n = 1;
if (Nbpsc != 1) {
// want variance = .5 per channel
// in fact, var{ 2 range(2^{Nbpsc/2}) - const } = (2^Nbpsc - 1) / 3
scale = sqrtf( 1.5f / ((1<<Nbpsc) - 1) );
n = Nbpsc >> 1;
}
std::vector<float> syms(1<<n);
for (size_t i=0; i<1<<n; i++)
syms[i] = (2*(int)grayRevToBinary((uint32_t)i, (uint32_t)n) + 1 - (1<<n)) * scale;
if (Nbpsc != 1) {
size_t k=0;
for (size_t i=0; i<1<<n; i++)
for (size_t j=0; j<1<<n; j++)
symbols[k++] = complex(syms[j], syms[i]);
} else {
for (size_t i=0; i<1<<n; i++)
symbols[i] = syms[i];
}
}
| 26.820513 | 90 | 0.464627 | [
"vector"
] |
cc8bc71b6fc4aea9a5dc55b266173eb53e686bdf | 3,902 | cpp | C++ | test/std/algorithm.cpp | wordring/wordring | e2c9c2ed66010537efd78694521312c5b63f0510 | [
"Unlicense"
] | 2 | 2020-03-07T05:23:20.000Z | 2021-01-23T15:19:18.000Z | test/std/algorithm.cpp | wordring/libwordring | b71d990ea9288e9d9fe85521c8adac5d50471fa6 | [
"Unlicense"
] | null | null | null | test/std/algorithm.cpp | wordring/libwordring | b71d990ea9288e9d9fe85521c8adac5d50471fa6 | [
"Unlicense"
] | null | null | null | // test/std/algorithm.cpp
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <random>
#include <string>
#include <vector>
#define STRING(str) #str
#define TO_STRING(str) STRING(str)
std::string const current_source_path{ TO_STRING(CURRENT_SOURCE_PATH) };
std::string const current_binary_path{ TO_STRING(CURRENT_BINARY_PATH) };
BOOST_AUTO_TEST_SUITE(std__algorithm__test)
BOOST_AUTO_TEST_CASE(std_algorithm__adjacent_find_1)
{
#ifdef NDEBUG
std::uint32_t n = 100 * 1024 * 1024;
#else
std::uint32_t n = 1024;
#endif
std::vector<std::uint32_t> v1;
v1.reserve(n);
std::uint32_t i = 0;
std::generate_n(std::back_inserter(v1), n, [&i]()->std::uint32_t { return ++i; });
std::cout.imbue(std::locale(""));
std::cout << "---------- std_algorithm__adjacent_find_1 ----------" << std::endl;
std::cout << "std::vector<std::uint32_t>" << std::endl;
std::cout << "\tsize():\t" << v1.size() << std::endl;
auto start = std::chrono::system_clock::now();
(void)std::adjacent_find(v1.begin(), v1.end());
auto duration = std::chrono::system_clock::now() - start;
std::cout << "\tstd::adjacent_find:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms" << std::endl;
std::cout << std::endl;
}
BOOST_AUTO_TEST_CASE(std_algorithm__is_sorted_1)
{
#ifdef NDEBUG
std::uint32_t n = 100 * 1024 * 1024;
#else
std::uint32_t n = 1024;
#endif
std::vector<std::uint32_t> v1;
v1.reserve(n);
std::uint32_t i = 0;
std::generate_n(std::back_inserter(v1), n, [&i]()->std::uint32_t { return ++i; });
std::cout.imbue(std::locale(""));
std::cout << "---------- std_algorithm__is_sorted_1 ----------" << std::endl;
std::cout << "std::vector<std::uint32_t>" << std::endl;
std::cout << "\tsize():\t" << v1.size() << std::endl;
auto start = std::chrono::system_clock::now();
(void)std::is_sorted(v1.begin(), v1.end());
auto duration = std::chrono::system_clock::now() - start;
std::cout << "\tstd::is_sorted:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms" << std::endl;
std::cout << std::endl;
}
BOOST_AUTO_TEST_CASE(std_algorithm__sort_1)
{
#ifdef NDEBUG
std::uint32_t n = 1 * 1024 * 1024;
#else
std::uint32_t n = 1024;
#endif
std::vector<std::uint32_t> v1;
v1.reserve(n);
std::random_device rd;
std::mt19937 mt(rd());
std::generate_n(std::back_inserter(v1), n, std::ref(mt));
std::cout.imbue(std::locale(""));
std::cout << "---------- std_algorithm__sort_1 ----------" << std::endl;
std::cout << "std::vector<std::uint32_t>" << std::endl;
std::cout << "\tsize():\t" << v1.size() << std::endl;
auto start = std::chrono::system_clock::now();
std::sort(v1.begin(), v1.end());
auto duration = std::chrono::system_clock::now() - start;
std::cout << "\tstd::sort:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms" << std::endl;
std::cout << std::endl;
}
BOOST_AUTO_TEST_CASE(std_algorithm__unique_1)
{
#ifdef NDEBUG
std::uint32_t n = 5 * 1024 * 1024;
#else
std::uint32_t n = 1024;
#endif
std::vector<std::uint32_t> v1;
v1.reserve(n);
std::random_device rd;
std::mt19937 mt(rd());
std::generate_n(std::back_inserter(v1), n, std::ref(mt));
std::sort(v1.begin(), v1.end());
std::cout.imbue(std::locale(""));
std::cout << "---------- std_algorithm__unique_1 ----------" << std::endl;
std::cout << "std::vector<std::uint32_t>" << std::endl;
std::cout << "\tsize():\t" << v1.size() << std::endl;
auto start = std::chrono::system_clock::now();
(void)std::unique(v1.begin(), v1.end());
auto duration = std::chrono::system_clock::now() - start;
std::cout << "\tstd::unique:\t" << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms" << std::endl;
std::cout << std::endl;
}
BOOST_AUTO_TEST_SUITE_END()
| 29.338346 | 136 | 0.648129 | [
"vector"
] |
cc8d1a9be5c16429d901cdfc45c1a5d285c537b0 | 42,672 | cpp | C++ | Source/ECS/CollisionSystem.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 121 | 2019-05-02T01:22:17.000Z | 2022-03-19T00:16:14.000Z | Source/ECS/CollisionSystem.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 42 | 2019-08-17T20:33:43.000Z | 2019-09-25T14:28:50.000Z | Source/ECS/CollisionSystem.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 20 | 2019-05-02T01:22:20.000Z | 2022-01-30T04:04:57.000Z | #include "ECS/ComponentSystems.h"
#include "ECS/CollisionSystem.h"
#include "ECS/Transform3DSystem.h"
#include "ECS/AttributeSystem.h"
#include "ECS/InventorySystem.h"
#include "ECS/AIControllerSystem.h"
#include "ECS/PlayerControllerSystem.h"
#include "ECS/Renderer2DSystem.h"
#include "ECS/EffectSystem.h"
#include "ECS/Effects.h"
#include "ECS/EntityFactory.h"
#include "Level.h"
#include <Graphics/Camera2D.h>
#include <Graphics/ParticleEngine2D.h>
#include <Graphics/SpriteSheetManager.h>
#include <Graphics/FontManager.h>
#include <Graphics/Color.h>
#include <Defines.h>
#include <System/Types.h>
#include <Math/Random.h>
#include <IO/ResourceManager.h>
#include <SDL2/SDL.h>
#include <time.h>
#include <unordered_set>
#include <limits.h>
#define MAX_COLLISION_INDICIES
namespace ECS{ namespace Systems { namespace Collision {
// Collision BitMasks
Enjon::uint32 COLLISION_NONE = 0x00000000;
Enjon::uint32 COLLISION_PLAYER = 0x00000001;
Enjon::uint32 COLLISION_ENEMY = 0x00000002;
Enjon::uint32 COLLISION_ITEM = 0x00000004;
Enjon::uint32 COLLISION_PROJECTILE = 0x00000008;
Enjon::uint32 COLLISION_WEAPON = 0x00000010;
Enjon::uint32 COLLISION_EXPLOSIVE = 0x00000020;
Enjon::uint32 COLLISION_PROP = 0x00000040;
Enjon::uint32 COLLISION_VORTEX = 0x00000080;
auto NumberOfCollisionLoops = 0;
std::unordered_map<std::string, Enjon::uint32> CollisionPairsWithLastFrameUpdate;
std::unordered_set<const char*> CollisionPairs;
/*-- Function Declarations --*/
void DrawBlood(ECS::Systems::EntityManager* Manager, Enjon::Math::Vec2 Pos);
void DrawBody(ECS::Systems::EntityManager* Manager, Enjon::Math::Vec2 Pos);
// Creates new CollisionSystem
struct CollisionSystem* NewCollisionSystem(struct EntityManager* Manager)
{
struct CollisionSystem* System = new CollisionSystem;
if (System == nullptr) Enjon::Utils::FatalError("COMPOPNENT_SYSTEMS::NEW_COLLISION_SYSTEM::System is null");
System->Manager = Manager;
return System;
}
// Updates all possible collisions
void Update(struct EntityManager* Manager)
{
static Enjon::uint32 StartTime = 0;
static Enjon::uint32 GetCellsTime = 0;
static Enjon::uint32 CollisionCheckTime = 0;
auto NumberOfChecks = 0;
// TODO(John): This is way too slow to be creating and destroying a set each frame / creating something once and update its values each frame instead,
// preferably something that has an O(1) lookup time
// This could really be unecessary writing...
eid32 size = Manager->CollisionSystem->Entities.empty() ? 0 : Manager->CollisionSystem->Entities.size();
for (eid32 n = 0; n < size; n++)
{
// Get entity
eid32 e = Manager->CollisionSystem->Entities[n];
// Get entities
std::vector<eid32> Entities;
// if (Manager->AttributeSystem->Masks[e] & Masks::Type::WEAPON) Entities = SpatialHash::FindCell(Manager->Grid, e, &Manager->TransformSystem->Transforms[e].AABB);
Entities = SpatialHash::FindCell(Manager->Grid, e, &Manager->TransformSystem->Transforms[e].AABB);
// else Entities = SpatialHash::GetEntitiesFromCells(Manager->Grid, Manager->CollisionSystem->CollisionComponents[e].Cells);
// Collide with entities
for (eid32 collider : Entities)
{
bool FoundCollisionPair = false;
bool NeedToUpdateCollisionPairFrame = false;
std::string HashString;
if (e == collider) continue;
if (e > collider) HashString = std::to_string(e) + std::to_string(collider);
else HashString = std::to_string(collider) + std::to_string(e);
// This will cause unnecessary branching. Figure out a way to take it out of the loop.
// if (CollisionPairs.find(HashString.c_str()) == CollisionPairs.end())
// Search for key
auto CollisionPairIterator = CollisionPairsWithLastFrameUpdate.find(HashString);
// Set whether or not found the pair
FoundCollisionPair = CollisionPairIterator != CollisionPairsWithLastFrameUpdate.end();
// If found, determine whether or not this frame matches the one needing to be checked
if (FoundCollisionPair) NeedToUpdateCollisionPairFrame = CollisionPairIterator->second != NumberOfCollisionLoops;
if (!FoundCollisionPair || NeedToUpdateCollisionPairFrame)
{
// Increment number of checks
NumberOfChecks++;
// Hash and put back into pair
// CollisionPairs.insert(HashString.c_str());
// Update or insert new pair into map with current collision loop as its value
CollisionPairsWithLastFrameUpdate[HashString] = NumberOfCollisionLoops;
// Get EntityType of collider and entity
Component::EntityType AType = Manager->Types[collider];
Component::EntityType BType = Manager->Types[e];
// Get collision mask for A and B
Enjon::uint32 Mask = GetCollisionType(Manager, e, collider);
// NOTE(John): I can only imagine how much branching this causes... Ugh.
if (Mask == (COLLISION_ITEM | COLLISION_ITEM)) {
// CollideWithDebris(Manager, collider, e); continue;
continue;
}
if (Mask == (COLLISION_ENEMY | COLLISION_ENEMY)) {
CollideWithEnemy(Manager, e, collider); continue;
// continue;
}
if (Mask == (COLLISION_WEAPON | COLLISION_ENEMY)) {
if (AType == Component::EntityType::ENEMY) CollideWithEnemy(Manager, e, collider);
else CollideWithEnemy(Manager, collider, e);
continue;
}
if (Mask == (COLLISION_PROJECTILE | COLLISION_ENEMY)) {
if (AType == Component::EntityType::PROJECTILE) CollideWithProjectile(Manager, collider, e);
else CollideWithProjectile(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_ITEM | COLLISION_PLAYER)) {
if (AType == Component::EntityType::ITEM) CollideWithDebris(Manager, collider, e);
else CollideWithDebris(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_ITEM | COLLISION_ENEMY)) {
if (AType == Component::EntityType::ITEM) CollideWithDebris(Manager, collider, e);
else CollideWithDebris(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_ITEM | COLLISION_EXPLOSIVE)) {
if (AType == Component::EntityType::ITEM) CollideWithDebris(Manager, collider, e);
else CollideWithDebris(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_ITEM | COLLISION_VORTEX)) {
if (AType == Component::EntityType::ITEM) CollideWithVortex(Manager, collider, e);
else CollideWithVortex(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_PROJECTILE | COLLISION_VORTEX)) {
if (AType == Component::EntityType::PROJECTILE) CollideWithVortex(Manager, collider, e);
else CollideWithVortex(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_PROJECTILE | COLLISION_EXPLOSIVE)){
if (AType == Component::EntityType::PROJECTILE) CollideWithDebris(Manager, collider, e);
else CollideWithDebris(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_PROJECTILE | COLLISION_WEAPON)) {
if (AType == Component::EntityType::PROJECTILE) CollideWithDebris(Manager, collider, e);
else CollideWithDebris(Manager, e, collider);
continue;
}
if (Mask == (COLLISION_ENEMY | COLLISION_PLAYER)) {
if (AType == Component::EntityType::PLAYER) CollideWithEnemy(Manager, e, collider);
else CollideWithEnemy(Manager, collider, e);
continue;
}
if (Mask == (COLLISION_EXPLOSIVE | COLLISION_ENEMY)) {
if (AType == Component::EntityType::ENEMY) CollideWithExplosive(Manager, e, collider);
else CollideWithExplosive(Manager, collider, e);
continue;
}
}
}
}
static auto t = 0.0f;
t += 0.1f;
if (t > 10.0f)
{
std::cout << "Number Of Collision pairs: " << CollisionPairsWithLastFrameUpdate.size() << std::endl;
// std::cout << "Number Of Collision pairs: " << CollisionPairs.size() << std::endl;
t = 0.0f;
}
if (CollisionPairsWithLastFrameUpdate.size() > 100000)
{
CollisionPairsWithLastFrameUpdate.clear();
}
// CollisionPairs.clear();
// Increment number of collision loops
NumberOfCollisionLoops = (NumberOfCollisionLoops + 1) % UINT_MAX;
} // Collision Update
Enjon::uint32 GetCollisionType(Systems::EntityManager* Manager, ECS::eid32 A, ECS::eid32 B)
{
// Init collision mask
Enjon::uint32 Mask = COLLISION_NONE;
// Make sure that manager is not null
if (Manager == nullptr) Enjon::Utils::FatalError("COLLISION_SYSTEM::GET_COLLISION_TYPE::Manager is null");
// Get types of A and B
const Component::EntityType* TypeA = &Manager->Types[A];
const Component::EntityType* TypeB = &Manager->Types[B];
// Or the mask with TypeA collision
switch(*TypeA)
{
case Component::EntityType::ITEM: Mask |= COLLISION_ITEM; break;
case Component::EntityType::WEAPON: Mask |= COLLISION_WEAPON; break;
case Component::EntityType::PLAYER: Mask |= COLLISION_PLAYER; break;
case Component::EntityType::ENEMY: Mask |= COLLISION_ENEMY; break;
case Component::EntityType::PROJECTILE: Mask |= COLLISION_PROJECTILE; break;
case Component::EntityType::EXPLOSIVE: Mask |= COLLISION_EXPLOSIVE; break;
case Component::EntityType::PROP: Mask |= COLLISION_PROP; break;
case Component::EntityType::VORTEX: Mask |= COLLISION_VORTEX; break;
default: Mask |= COLLISION_NONE; break;
}
// // Or the mask with TypeB collision
switch(*TypeB)
{
case Component::EntityType::ITEM: Mask |= COLLISION_ITEM; break;
case Component::EntityType::WEAPON: Mask |= COLLISION_WEAPON; break;
case Component::EntityType::PLAYER: Mask |= COLLISION_PLAYER; break;
case Component::EntityType::ENEMY: Mask |= COLLISION_ENEMY; break;
case Component::EntityType::PROJECTILE: Mask |= COLLISION_PROJECTILE; break;
case Component::EntityType::EXPLOSIVE: Mask |= COLLISION_EXPLOSIVE; break;
case Component::EntityType::PROP: Mask |= COLLISION_PROP; break;
case Component::EntityType::VORTEX: Mask |= COLLISION_VORTEX; break;
default: Mask |= COLLISION_NONE; break;
}
return Mask;
}
// Collide Explosive with Enemy
void CollideWithExplosive(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec3* ColliderVelocity = &Manager->TransformSystem->Transforms[B_ID].Velocity;
Enjon::Math::Vec3* EntityVelocity = &Manager->TransformSystem->Transforms[A_ID].Velocity;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) return;
else
{
// Shake the camera for effect
Manager->Camera->ShakeScreen(Enjon::Random::Roll(30, 40));
// Get minimum translation distance
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_A, AABB_B);
*EntityVelocity = EM::Vec3(EM::CartesianToIso(mtd), EntityVelocity->z);
Enjon::Math::Vec2 Difference = Enjon::Math::Vec2::Normalize(EntityPosition->XY() - ColliderPosition->XY());
// if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
// *ColliderPosition -= Enjon::Math::Vec3(Difference * 30.0f, 0.0f);
*ColliderVelocity = -2.0f * Enjon::Math::Vec3(Difference, 0.0f);
// Update velocities based on "bounce" factor
// float bf = 1.0f; // Bounce factor
// ColliderVelocity->x = -ColliderVelocity->x * bf;
// ColliderVelocity->y = -ColliderVelocity->y * bf;
// Hurt Collider
// Get health and color of entity
Component::HealthComponent* HealthComponent = &Manager->AttributeSystem->HealthComponents[B_ID];
Enjon::Graphics::ColorRGBA16* Color = &Manager->Renderer2DSystem->Renderers[B_ID].Color;
// Set option to damaged
Manager->AttributeSystem->Masks[B_ID] |= Masks::GeneralOptions::DAMAGED;
if (HealthComponent == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Collider health component is null");
if (Color == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Color component is null");
// Add blood particle effect (totally a test)...
const EM::Vec3* PP = &Manager->TransformSystem->Transforms[B_ID].Position;
static GLuint PTex = EI::ResourceManager::GetTexture("../IsoARPG/assets/textures/orb.png").id;
EG::ColorRGBA16 R = EG::RGBA16(1.0f, 0.01f, 0.01f, 1.0f);
// Add 100 at a time
// for (Enjon::uint32 i = 0; i < 2; i++)
// {
float XPos = Enjon::Random::Roll(-50, 100), YPos = Enjon::Random::Roll(-50, 100), ZVel = Enjon::Random::Roll(-10, 10), XVel = Enjon::Random::Roll(-10, 10),
YSize = Enjon::Random::Roll(2, 7), XSize = Enjon::Random::Roll(1, 5);
EG::Particle2D::AddParticle(EM::Vec3(PP->x + 50.0f + XVel, PP->y + 50.0f + ZVel, 0.0f), EM::Vec3(XVel, XVel, ZVel),
EM::Vec2(XSize, YSize), R, PTex, 0.05f, Manager->ParticleEngine->ParticleBatches[0]);
// Add blood overlay to level
DrawBlood(Manager, ColliderPosition->XY());
// }
// Get min and max damage of weapon
const Loot::Weapon::WeaponProfile* WP = Manager->AttributeSystem->WeaponProfiles[A_ID];
Enjon::uint32 MiD, MaD;
if (WP)
{
MiD = WP->Damage.Min;
MaD = WP->Damage.Max;
}
else
{
MiD = 5;
MaD = 10;
}
auto Damage = Enjon::Random::Roll(MiD, MaD);
// Decrement by damage
HealthComponent->Health -= Damage;
// printf("Hit for %d damage\n", Damage);
if (HealthComponent->Health <= 0.0f)
{
// DrawBody(Manager, ColliderPosition->XY());
// Remove entity if no health
EntitySystem::RemoveEntity(Manager, B_ID);
// Drop some loot!
// Loot::DropLootBasedOnProfile(Manager, B_ID);
// auto* LP = Manager->AttributeSystem->LootProfiles[B_ID];
}
// Remove projectile
// EntitySystem::RemoveEntity(Manager, A_ID);
// Continue with next entity
return;
}
}
void CollideWithProjectile(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec3* EntityVelocity = &Manager->TransformSystem->Transforms[A_ID].Velocity;
Enjon::Math::Vec3* ColliderVelocity = &Manager->TransformSystem->Transforms[B_ID].Velocity;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
// If parent, then return
if (Manager->AttributeSystem->Groups[A_ID].Parent == B_ID) return;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) return;
else
{
// If is a grenade, then spawn an explosion
if (Manager->AttributeSystem->Masks[A_ID] & Masks::WeaponSubOptions::GRENADE)
{
// TODO(John): Make a "spawn" function that gets called for any entity that has a factory component
ECS::eid32 Explosion = Factory::CreateWeapon(Manager, Enjon::Math::Vec3(Manager->TransformSystem->Transforms[A_ID].Position.XY(), 0.0f), Enjon::Math::Vec2(16.0f, 16.0f),
Enjon::Graphics::SpriteSheetManager::GetSpriteSheet("Orb"),
Masks::Type::WEAPON | Masks::WeaponOptions::EXPLOSIVE, Component::EntityType::EXPLOSIVE, "Explosion");
Manager->AttributeSystem->Masks[Explosion] |= Masks::GeneralOptions::COLLIDABLE;
Manager->TransformSystem->Transforms[Explosion].Velocity = Enjon::Math::Vec3(0.0f, 0.0f, 0.0f);
Manager->TransformSystem->Transforms[Explosion].VelocityGoal = Enjon::Math::Vec3(0.0f, 0.0f, 0.0f);
Manager->TransformSystem->Transforms[Explosion].BaseHeight = 0.0f;
Manager->TransformSystem->Transforms[Explosion].MaxHeight = 0.0f;
Manager->TransformSystem->Transforms[Explosion].AABBPadding = Enjon::Math::Vec2(200, 200);
Enjon::Graphics::Particle2D::DrawFire(Manager->ParticleEngine->ParticleBatches[0], Manager->TransformSystem->Transforms[A_ID].Position);
auto I = Enjon::Random::Roll(0, 2);
Enjon::Graphics::GLTexture S;
switch(I)
{
case 0: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/explody.png"); break;
case 1: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/explody_2.png"); break;
case 2: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/explody_3.png"); break;
default: break;
}
auto Position = &Manager->TransformSystem->Transforms[A_ID].Position;
auto alpha = Enjon::Random::Roll(50, 255) / 255.0f;
auto X = (float)Enjon::Random::Roll(-50, 100);
auto Y = (float)Enjon::Random::Roll(-100, 50);
auto C = Enjon::Graphics::RGBA16_White();
auto DC = Enjon::Random::Roll(80, 100) / 255.0f;
C = Enjon::Graphics::RGBA16(C.r - DC, C.g - DC, C.b - DC, alpha);
Manager->Lvl->AddTileOverlay(S, Enjon::Math::Vec4(Position->x + X, Position->y + Y, (float)Enjon::Random::Roll(50, 100), (float)Enjon::Random::Roll(50, 100)), C);
}
// Shake the camera for effect
if (Manager->AttributeSystem->Masks[A_ID] & Masks::WeaponOptions::EXPLOSIVE) Manager->Camera->ShakeScreen(Enjon::Random::Roll(30, 40));
else Manager->Camera->ShakeScreen(Enjon::Random::Roll(10, 15));
// Get minimum translation distance
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_A, AABB_B);
*EntityVelocity = EM::Vec3(EM::CartesianToIso(mtd), EntityVelocity->z);
// *EntityPosition -= Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), EntityPosition->z);
// Manager->TransformSystem->Transforms[A_ID].GroundPosition -= Enjon::Math::CartesianToIso(mtd);
// if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
// *ColliderPosition += Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd) * 1.0f, 0.0f);
Enjon::Math::Vec2 Difference = Enjon::Math::Vec2::Normalize(EntityPosition->XY() - ColliderPosition->XY());
// if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
// *ColliderPosition -= Enjon::Math::Vec3(Difference * 30.0f, 0.0f);
if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
*ColliderVelocity = -2.0f * Enjon::Math::Vec3(Difference, 0.0f);
// Update velocities based on "bounce" factor
// float bf = 1.0f; // Bounce factor
// ColliderVelocity->x = -ColliderVelocity->x * bf;
// ColliderVelocity->y = -ColliderVelocity->y * bf;
// Hurt Collider
// Get health and color of entity
Component::HealthComponent* HealthComponent = &Manager->AttributeSystem->HealthComponents[B_ID];
Enjon::Graphics::ColorRGBA16* Color = &Manager->Renderer2DSystem->Renderers[B_ID].Color;
// Set option to damaged
Manager->AttributeSystem->Masks[B_ID] |= Masks::GeneralOptions::DAMAGED;
if (HealthComponent == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Collider health component is null");
if (Color == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Color component is null");
// Add blood particle effect (totally a test)...
const EM::Vec3* PP = &Manager->TransformSystem->Transforms[B_ID].Position;
static GLuint PTex = EI::ResourceManager::GetTexture("../IsoARPG/assets/textures/orb.png").id;
EG::ColorRGBA16 R = EG::RGBA16(1.0f, 0.01f, 0.01f, 1.0f);
// Add 100 at a time
// for (Enjon::uint32 i = 0; i < 2; i++)
// {
float XPos = Enjon::Random::Roll(-50, 100), YPos = Enjon::Random::Roll(-50, 100), ZVel = Enjon::Random::Roll(-10, 10), XVel = Enjon::Random::Roll(-10, 10),
YSize = Enjon::Random::Roll(2, 7), XSize = Enjon::Random::Roll(1, 5);
EG::Particle2D::AddParticle(EM::Vec3(PP->x + 50.0f + XVel, PP->y + 50.0f + ZVel, 0.0f), EM::Vec3(XVel, XVel, ZVel),
EM::Vec2(XSize, YSize), R, PTex, 0.05f, Manager->ParticleEngine->ParticleBatches[0]);
// Add blood overlay to level
DrawBlood(Manager, ColliderPosition->XY());
// }
// Get min and max damage of weapon
const Loot::Weapon::WeaponProfile* WP = Manager->AttributeSystem->WeaponProfiles[A_ID];
Enjon::uint32 MiD, MaD;
if (WP)
{
MiD = WP->Damage.Min;
MaD = WP->Damage.Max;
}
else
{
MiD = 5;
MaD = 10;
}
auto Damage = Enjon::Random::Roll(MiD, MaD);
// Decrement by damage
HealthComponent->Health -= Damage;
// printf("Hit for %d damage\n", Damage);
if (HealthComponent->Health <= 0.0f)
{
//DrawBody(Manager, ColliderPosition->XY());
// Remove entity if no health
EntitySystem::RemoveEntity(Manager, B_ID);
// Drop some loot!
// Loot::DropLootBasedOnProfile(Manager, B_ID);
// auto* LP = Manager->AttributeSystem->LootProfiles[B_ID];
}
else
{
if ((Manager->Masks[B_ID] & COMPONENT_NONE) != COMPONENT_NONE)
{
// Apply an effect just to see if this shit works at all...
auto* T = &Manager->EffectSystem->TransferredEffects[B_ID]["Poison"];
T->Type = EffectType::TEMPORARY;
T->Apply = &Effects::Cold;
T->Timer = Component::TimerComponent{5.0f, 0.05f, B_ID};
T->Entity = B_ID;
}
}
// Remove projectile
EntitySystem::RemoveEntity(Manager, A_ID);
// Continue with next entity
return;
}
}
void CollideWithItem(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
Component::EntityType AType = Manager->Types[A_ID];
Component::EntityType BType = Manager->Types[B_ID];
auto AM = Manager->AttributeSystem->Masks[A_ID];
auto BM = Manager->AttributeSystem->Masks[B_ID];
// Leave if debris
if (AM & Masks::GeneralOptions::DEBRIS || BM & Masks::GeneralOptions::DEBRIS) return;
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) return;
// Picking up an item
else
{
eid32 Item = AType == Component::EntityType::ITEM ? A_ID : B_ID;
eid32 Player = Item == A_ID ? B_ID : A_ID;
if (Manager->InventorySystem->Inventories[Player].Items.size() < MAX_ITEMS)
{
printf("Picked up item!\n");
// Place in player inventory
Manager->InventorySystem->Inventories[Player].Items.push_back(Item);
printf("Inventory Size: %d\n", Manager->InventorySystem->Inventories[Player].Items.size());
// Turn off render and transform components of item
EntitySystem::RemoveComponents(Manager, Item, COMPONENT_RENDERER2D | COMPONENT_TRANSFORM3D);
// Set item to picked up
Manager->AttributeSystem->Masks[Item] |= Masks::GeneralOptions::PICKED_UP;
// Particle effects for shiggles...
// Add blood particle effect (totally a test)...
const EM::Vec3* PP = &Manager->TransformSystem->Transforms[Player].Position;
static GLuint PTex = EI::ResourceManager::GetTexture("../IsoARPG/assets/textures/orb.png").id;
EG::ColorRGBA16 C1 = EG::RGBA16(1.0f, 0, 0, 1.0f);
// Add 100 at a time
for (Enjon::uint32 i = 0; i < 2; i++)
{
float XPos = Enjon::Random::Roll(-50, 100), YPos = Enjon::Random::Roll(-50, 100), ZVel = Enjon::Random::Roll(-10, 10), XVel = Enjon::Random::Roll(-10, 10),
YVel = Enjon::Random::Roll(-10, 10), YSize = Enjon::Random::Roll(1, 3), XSize = Enjon::Random::Roll(1, 3);
EG::Particle2D::AddParticle(EM::Vec3(PP->x + 50.0f, PP->y + 50.0f, 100.0f), EM::Vec3(XVel, YVel, ZVel),
EM::Vec2(XSize, YSize), C1, PTex, 0.05f, Manager->ParticleEngine->ParticleBatches[0]);
}
}
// Continue to next entity
return;
}
}
void CollideWithDebris(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec3* EntityVelocity = &Manager->TransformSystem->Transforms[A_ID].Velocity;
Enjon::Math::Vec3* ColliderVelocity = &Manager->TransformSystem->Transforms[B_ID].Velocity;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
float AMass = Manager->TransformSystem->Transforms[A_ID].Mass;
float BMass = Manager->TransformSystem->Transforms[B_ID].Mass;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) { return; }
else
{
if (Manager->AttributeSystem->Masks[B_ID] & Masks::WeaponOptions::EXPLOSIVE)
{
V2 Direction = EM::Vec2::Normalize(*A - *B);
if (Direction.x == 0) Direction.x = (float)ER::Roll(-100, 100) / 100.0f;
if (Direction.y == 0) Direction.y = (float)ER::Roll(-100, 100) / 100.0f;
float Length = Direction.Length();
float Impulse = 55.0f / (Length + 0.001f);
*EntityVelocity = (1.0f / AMass) * -Impulse * EM::Vec3(EM::CartesianToIso(Direction), EntityVelocity->z);
if (Manager->AttributeSystem->Masks[A_ID] & Masks::WeaponOptions::PROJECTILE)
{
*EntityVelocity = *EntityVelocity * 2.0f;
Manager->TransformSystem->Transforms[A_ID].VelocityGoal = *EntityVelocity;
EM::Vec2 R(1,0);
float a = acos(Direction.DotProduct(R)) * 180.0f / M_PI;
if (Direction.y < 0) a *= -1;
Manager->TransformSystem->Transforms[A_ID].Angle = EM::ToRadians(a);
}
}
else if (Manager->AttributeSystem->Masks[B_ID] & Masks::WeaponOptions::MELEE)
{
V2 Direction = *A - *B;
Direction.x += ER::Roll(-10, 10);
Direction.y += ER::Roll(-10, 10);
Direction = EM::Vec2::Normalize(Direction);
if (Direction.x == 0) Direction.x = (float)ER::Roll(-100, 100) / 100.0f;
if (Direction.y == 0) Direction.y = (float)ER::Roll(-100, 100) / 100.0f;
float Length = Direction.Length();
float Impulse = 25.0f / (Length + 0.001f);
*EntityVelocity = (1.0f / AMass) * -Impulse * EM::Vec3(EM::CartesianToIso(Direction), EntityVelocity->z);
if (Manager->AttributeSystem->Masks[A_ID] & Masks::WeaponOptions::PROJECTILE)
{
*EntityVelocity = *EntityVelocity * 2.0f;
Manager->TransformSystem->Transforms[A_ID].VelocityGoal = *EntityVelocity;
EM::Vec2 R(1,0);
float a = acos(Direction.DotProduct(R)) * 180.0f / M_PI;
if (Direction.y < 0) a *= -1;
Manager->TransformSystem->Transforms[A_ID].Angle = EM::ToRadians(a);
}
}
else if (Manager->AttributeSystem->Masks[B_ID] & Masks::GeneralOptions::DEBRIS &&
Manager->AttributeSystem->Masks[A_ID] & Masks::GeneralOptions::DEBRIS)
{
{
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_B, AABB_A);
// *EntityVelocity = 0.98f * *EntityVelocity + -0.05f * EM::Vec3(EM::CartesianToIso(mtd), 0.0f);
*EntityPosition -= Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), EntityPosition->z);
// *ColliderVelocity = 0.98f * *ColliderVelocity + 0.05f * EM::Vec3(EM::CartesianToIso(mtd), 0.0f);
// *ColliderPosition += Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), ColliderPosition->z);
}
}
else
{
// Get minimum translation distance
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_B, AABB_A);
*EntityVelocity = 0.85f * *EntityVelocity + -0.05f * EM::Vec3(EM::CartesianToIso(mtd), 0.0f);
// V2 Direction = *A - *B;
// Direction.x += ER::Roll(-10, 10);
// Direction.y += ER::Roll(-10, 10);
// Direction = EM::Vec2::Normalize(Direction);
// if (Direction.x == 0) Direction.x = (float)ER::Roll(-100, 100) / 100.0f;
// if (Direction.y == 0) Direction.y = (float)ER::Roll(-100, 100) / 100.0f;
// float Length = Direction.Length();
// float Impulse = 25.0f / (Length + 0.001f);
// *ColliderPosition += Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), EntityPosition->z);
// *EntityVelocity = (1.0f / AMass) * 0.05f * -Impulse * EM::Vec3(EM::CartesianToIso(Direction), EntityVelocity->z);
// *ColliderVelocity = (1.0f / BMass) * 0.05f * Impulse * EM::Vec3(EM::CartesianToIso(Direction), EntityVelocity->z);
// *ColliderVelocity = 1.0f * *ColliderVelocity + 0.05f * EM::Vec3(EM::CartesianToIso(mtd), 0.0f);
}
}
return;
}
void CollideWithVortex(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
static float t = 0.0f;
t += 0.001f;
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec3* EntityVelocity = &Manager->TransformSystem->Transforms[A_ID].Velocity;
Enjon::Math::Vec3* ColliderVelocity = &Manager->TransformSystem->Transforms[B_ID].Velocity;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
float AMass = Manager->TransformSystem->Transforms[A_ID].Mass;
float BMass = Manager->TransformSystem->Transforms[B_ID].Mass;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) { return; }
else
{
if (Manager->AttributeSystem->Masks[A_ID] & Masks::WeaponOptions::PROJECTILE)
{
auto Center = (AABB_B->Max + AABB_B->Min) / 2.0f;
float DistFromCenter = B->DistanceTo(Center);
if (DistFromCenter > 100.0f)
{
V2 Direction = EM::Vec2::Normalize(Center - *B);
float Length = Direction.Length();
float Impulse = 2.0f * 15 - Length;
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_B, AABB_A);
*EntityVelocity = 0.2f * *EntityVelocity + (1.0f / 1000.0f) * Impulse * EM::Vec3(EM::CartesianToIso(Direction), sin(t) * ER::Roll(1, 10));
*EntityPosition += EM::Vec3(ER::Roll(-1, 1), ER::Roll(-1, 1), 0.0f);
EM::Vec2 R(1,0);
float a = acos(Direction.DotProduct(R)) * 180.0f / M_PI;
if (Direction.y < 0) a *= -1;
Manager->TransformSystem->Transforms[A_ID].Angle = EM::ToRadians(a);
}
}
else
{
auto Center = (AABB_B->Max + AABB_B->Min) / 2.0f;
float DistFromCenter = A->DistanceTo(Center);
if (DistFromCenter > 13.0f)
{
V2 Direction = EM::Vec2::Normalize(*A - *B);
float Length = Direction.Length();
float Impulse = 2.0f;
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_B, AABB_A);
*EntityVelocity = 0.85f * *EntityVelocity + (1.0f / AMass) * Impulse * EM::Vec3(EM::CartesianToIso(Direction) +
EM::CartesianToIso(0.25f * EM::Vec2(2.0f * cos(t), sin(t))), sin(t) * 1.0f);
Manager->TransformSystem->Transforms[A_ID].VelocityGoal = EM::Vec3(0.0f, 0.0f, 0.0f);
// *EntityPosition += EM::Vec3(ER::Roll(-1, 1), ER::Roll(-1, 1), 0.0f);
EM::Vec2 R(1,0);
float a = acos(Direction.DotProduct(R)) * 180.0f / M_PI;
if (Direction.y < 0) a *= -1;
*EntityPosition = *EntityPosition + (2.0f / AMass) * EM::Vec3(EM::CartesianToIso(EM::Vec2(cos(EM::ToRadians(a + 180)), sin(EM::ToRadians(a + 180)))), 0.0f);
}
}
Manager->AttributeSystem->Groups[A_ID].Parent = Manager->AttributeSystem->Groups[B_ID].Parent;
}
return;
}
// Collide Player with Enemy
void CollideWithEnemy(Systems::EntityManager* Manager, ECS::eid32 A_ID, ECS::eid32 B_ID)
{
Enjon::Math::Vec3* EntityPosition = &Manager->TransformSystem->Transforms[A_ID].Position;
Enjon::Math::Vec3* ColliderPosition = &Manager->TransformSystem->Transforms[B_ID].Position;
Enjon::Math::Vec2* A = &Manager->TransformSystem->Transforms[B_ID].CartesianPosition;
Enjon::Math::Vec2* B = &Manager->TransformSystem->Transforms[A_ID].CartesianPosition;
Enjon::Math::Vec3* EntityVelocity = &Manager->TransformSystem->Transforms[A_ID].Velocity;
Enjon::Math::Vec3* ColliderVelocity = &Manager->TransformSystem->Transforms[B_ID].Velocity;
Enjon::Physics::AABB* AABB_A = &Manager->TransformSystem->Transforms[A_ID].AABB;
Enjon::Physics::AABB* AABB_B = &Manager->TransformSystem->Transforms[B_ID].AABB;
Enjon::Math::Vec2 Difference = Enjon::Math::Vec2::Normalize(EntityPosition->XY() - ColliderPosition->XY());
// Height not the same... Testing
if (abs(EntityPosition->z - ColliderPosition->z) > 100.0f) return;
// Collision didn't happen
if (!Enjon::Physics::AABBvsAABB(AABB_A, AABB_B)) { return; }
else
{
// Get minimum translation distance
V2 mtd = Enjon::Physics::MinimumTranslation(AABB_B, AABB_A);
// if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::ITEM) *EntityVelocity = 0.25f * EM::Vec3(EM::CartesianToIso(mtd), 20.0f);
// else
{
*EntityPosition -= Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), EntityPosition->z);
}
Manager->TransformSystem->Transforms[A_ID].GroundPosition -= Enjon::Math::CartesianToIso(mtd);
if (!Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
*ColliderPosition += Enjon::Math::Vec3(Enjon::Math::CartesianToIso(mtd), 0.0f);
// if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
// *ColliderPosition -= Enjon::Math::Vec3(Difference * 30.0f, 0.0f);
if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
*ColliderVelocity += -2.0f * Enjon::Math::Vec3(Difference, 0.0f);
// Update velocities based on "bounce" factor
float bf; // Bounce factor
if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
{
// Shake the camera for effect
Manager->Camera->ShakeScreen(Enjon::Random::Roll(10, 15));
bf = 1.2f;
}
else bf = 1.0f;
// ColliderVelocity->x = -ColliderVelocity->x * bf;
// ColliderVelocity->y = -ColliderVelocity->y * bf;
if (Manager->AttributeSystem->Masks[A_ID] & Masks::Type::WEAPON)
{
// NOTE(John): This could cause some trouble eventually
if (Manager->AttributeSystem->Masks[B_ID] & Masks::GeneralOptions::DAMAGED) return;
// Get min and max damage of weapon
auto DC = Manager->AttributeSystem->WeaponProfiles[A_ID]->Damage;
float MiD = DC.Min;
float MaD = DC.Max;
float Damage = static_cast<float>(Enjon::Random::Roll(MiD, MaD));
// Get health and color of entity
Component::HealthComponent* HealthComponent = &Manager->AttributeSystem->HealthComponents[B_ID];
Enjon::Graphics::ColorRGBA16* Color = &Manager->Renderer2DSystem->Renderers[B_ID].Color;
// Set option to damaged
Manager->AttributeSystem->Masks[B_ID] |= Masks::GeneralOptions::DAMAGED;
if (HealthComponent == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Collider health component is null");
if (Color == nullptr) Enjon::Utils::FatalError("COMPONENT_SYSTEMS::COLLISION_SYSTEM::Color component is null");
// Decrement by some arbitrary amount for now
HealthComponent->Health -= Damage;
// Add blood particle effect (totally a test)...
// EM::Vec3* PP = &Manager->TransformSystem->Transforms[B_ID].Position;
static GLuint PTex = EI::ResourceManager::GetTexture("../IsoARPG/assets/textures/blood_1.png").id;
EG::ColorRGBA16 R = EG::RGBA16(1.0f, 0.01f, 0.01f, 1.0f);
for (auto p = 0; p < 100; p++)
{
float XPos = Enjon::Random::Roll(-50, 100), YPos = Enjon::Random::Roll(-50, 100), ZVel = Enjon::Random::Roll(-10, 10), XVel = Enjon::Random::Roll(-10, 10),
YSize = Enjon::Random::Roll(10, 20), XSize = Enjon::Random::Roll(10, 20);
// EG::Particle2D::AddParticle(EM::Vec3(ColliderPosition->x + 50.0f + XVel, ColliderPosition->y + 50.0f + ZVel, 0.0f), EM::Vec3(XVel, XVel, ZVel),
// EM::Vec2(XSize * 1.5f, YSize * 1.5f), R, PTex, 0.005f, Manager->ParticleEngine->ParticleBatches.at(0));
EG::Particle2D::AddParticle(
EM::Vec3(ColliderPosition->x + 50.0f + XVel, ColliderPosition->y + 50.0f + ZVel, 50.0f),
15.0f * EM::Vec3(
-Difference.x + static_cast<float>(ER::Roll(-2, 2)) / 10.0f,
-Difference.y + static_cast<float>(ER::Roll(-2, 2)) / 10.0f,
static_cast<float>(ER::Roll(-2, 2)) / 10.0f
),
EM::Vec2(XSize * 1.5f, YSize * 1.5f), R, PTex, 0.005f, Manager->ParticleEngine->ParticleBatches.at(0));
}
// Print out that damage, son!
auto DamageString = std::to_string(static_cast<Enjon::uint32>(Damage));
auto x_pos_advance = -5.0f;
auto DamageColor = EG::RGBA16_White();
if (Damage >= 0.8f * ((MaD - MiD) + MiD)) DamageColor = EG::RGBA16_Red();
else if (Damage >= 0.4f * ((MaD - MiD) + MiD)) DamageColor = EG::RGBA16_Orange();
else DamageColor = EG::RGBA16_ZombieGreen();
for (auto c : DamageString)
{
auto x_advance = 0.0f;
auto F = EG::FontManager::GetFont("8Bit_32");
auto CS = EG::Fonts::GetCharacterAttributes(EM::Vec2(ColliderPosition->x, ColliderPosition->y + 50.0f), 1.0f, F, c, &x_advance);
EG::Particle2D::AddParticle(
EM::Vec3(ColliderPosition->x + x_pos_advance, ColliderPosition->y + 200.0f, 0.0f),
EM::Vec3(0.0f, 0.0f, 2.0f),
EM::Vec2(
EG::Fonts::GetAdvance(c, F, 1.0f),
EG::Fonts::GetHeight(c, F, 1.0f)
),
DamageColor,
CS.TextureID,
0.005f,
Manager->ParticleEngine->ParticleBatches.at(2)
);
x_pos_advance += 30.0f;
}
x_pos_advance = 0.0f;
// Blood!
DrawBlood(Manager, ColliderPosition->XY());
// }
// Apply an effect just to see if this shit work at all...
// 20% chance to apply
float Percent = 0.2f;
float Chance = (float)Enjon::Random::Roll(0, 100) / 100.0f;
if (Chance < Percent)
{
auto* T = &Manager->EffectSystem->TransferredEffects[B_ID]["Poison"];
T->Type = EffectType::TEMPORARY;
T->Apply = &Effects::Poison;
T->Timer = Component::TimerComponent{3.0f, 0.05f, B_ID};
T->Entity = B_ID;
}
// If dead, then kill it
// TODO(John): This doesn't belong here. Need to have this be a dispatched message to the attribute system or the entity manager itself.
if (HealthComponent->Health <= 0.0f)
{
// Drop some loot!
// Loot::DropLootBasedOnProfile(Manager, B_ID);
// auto* LP = Manager->AttributeSystem->LootProfiles[B_ID];
// Put body overlay onto the world
// DrawBody(Manager, ColliderPosition->XY());
// Let's try and make an explosion of debris
// auto max_debris = ER::Roll(15, 20);
// for (auto e = 0; e < max_debris; e++)
// {
// auto id = ECS::Factory::CreateGib(
// Manager,
// *ColliderPosition,
// 20.0f * EM::Vec3(
// -Difference.x + static_cast<float>(ER::Roll(-2, 2)) / 10.0f,
// -Difference.y + static_cast<float>(ER::Roll(-2, 2)) / 10.0f,
// 0.0f
// )
// );
// }
// Remove collider
EntitySystem::RemoveEntity(Manager, B_ID);
}
}
// Continue with next entity
return;
}
}
void DrawBody(ECS::Systems::EntityManager* Manager, Enjon::Math::Vec2 PP)
{
auto S = 200.0f;
auto C = Enjon::Graphics::RGBA16_White();
auto DC = 0.75f;
C = Enjon::Graphics::RGBA16(C.r - DC, C.g - DC, C.b - DC, C.a);
Manager->Lvl->AddTileOverlay(Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/body.png"), Enjon::Math::Vec4(PP, S, S * 0.26f), C);
}
void DrawBlood(ECS::Systems::EntityManager* Manager, Enjon::Math::Vec2 PP)
{
for (auto i = 0; i < 5; i++)
{
auto I = Enjon::Random::Roll(0, 2);
Enjon::Graphics::GLTexture S;
switch(I)
{
case 0: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/blood_1.png"); break;
case 1: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/blood_2.png"); break;
case 2: S = Enjon::Input::ResourceManager::GetTexture("../IsoARPG/Assets/Textures/blood_3.png"); break;
default: break;
}
auto alpha = Enjon::Random::Roll(50, 255) / 255.0f;
auto X = (float)Enjon::Random::Roll(-50, 100);
auto Y = (float)Enjon::Random::Roll(-100, 50);
auto C = Enjon::Graphics::RGBA16_White();
auto DC = Enjon::Random::Roll(80, 100) / 255.0f;
C = Enjon::Graphics::RGBA16(C.r - DC, C.g - DC, C.b - DC, alpha);
Manager->Lvl->AddTileOverlay(S, Enjon::Math::Vec4(PP.x + X, PP.y + Y, (float)Enjon::Random::Roll(50, 100), (float)Enjon::Random::Roll(50, 100)), C);
}
}
}}}
| 41.509728 | 174 | 0.651434 | [
"render",
"vector",
"transform"
] |
cc9670095c375c46301ffd23882e740640025cf8 | 4,514 | cpp | C++ | CISC/SubgraphComparing/matching/SelectEdge.cpp | Holly-Jiang/QCTSA | b90136b9df18fc21ae53b431f1e5e0c6ef786fae | [
"MIT"
] | 75 | 2020-02-19T15:03:18.000Z | 2022-03-25T08:24:33.000Z | CISC/SubgraphComparing/matching/SelectEdge.cpp | Holly-Jiang/QCTSA | b90136b9df18fc21ae53b431f1e5e0c6ef786fae | [
"MIT"
] | 9 | 2020-09-22T11:02:14.000Z | 2022-03-16T11:19:24.000Z | CISC/SubgraphComparing/matching/SelectEdge.cpp | Holly-Jiang/QCTSA | b90136b9df18fc21ae53b431f1e5e0c6ef786fae | [
"MIT"
] | 18 | 2020-06-02T13:35:21.000Z | 2021-11-26T11:43:00.000Z | //
// Created by ssunah on 10/31/19.
//
//
// Created by ssunah on 10/31/19.
//
#include <cassert>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
#include <chrono>
#include <tuple>
#include <random>
using namespace std;
void write_csr(string& deg_output_file, string &adj_output_file, vector<pair<int, int>> &lines, unsigned int vertex_num) {
auto edge_num = lines.size();
vector<int> degree_arr(vertex_num, 0);
vector<vector<int>> matrix(vertex_num);
ofstream deg_ofs(deg_output_file, ios::binary);
for (const auto &line : lines) {
int src, dst;
std::tie(src, dst) = line;
degree_arr[src]++;
degree_arr[dst]++;
matrix[src].emplace_back(dst);
matrix[dst].emplace_back(src);
}
cout << "begin write" << endl;
cout << "Input |V| = " << vertex_num << ", |E| = " << edge_num << endl;
int int_size = sizeof(int);
deg_ofs.write(reinterpret_cast<const char *>(&int_size), 4);
deg_ofs.write(reinterpret_cast<const char *>(&vertex_num), 4);
deg_ofs.write(reinterpret_cast<const char *>(&edge_num), 4);
deg_ofs.write(reinterpret_cast<const char *>(°ree_arr.front()), degree_arr.size() * 4);
cout << "finish degree write..." << endl;
ofstream adj_ofs(adj_output_file, ios::binary);
for (auto &adj_arr: matrix) {
adj_ofs.write(reinterpret_cast<const char *>(&adj_arr.front()), adj_arr.size() * 4);
}
cout << "finish edge write..." << endl;
}
void read_csr(string& degree_bin_path, string& adj_bin_path, vector<unsigned int>& offsets, vector<unsigned int>& neighbors) {
std::ifstream deg_file(degree_bin_path, std::ios::binary);
if (deg_file.is_open()) {
std::cout << "Open degree file " << degree_bin_path << " successfully." << std::endl;
}
else {
std::cerr << "Cannot open degree file " << degree_bin_path << " ." << std::endl;
exit(-1);
}
int int_size;
unsigned int vertex_count;
unsigned int edge_count;
deg_file.read(reinterpret_cast<char *>(&int_size), 4);
deg_file.read(reinterpret_cast<char *>(&vertex_count), 4);
deg_file.read(reinterpret_cast<char *>(&edge_count), 4);
cout << "Input |V| = " << vertex_count << ", |E| = " << edge_count << endl;
offsets.resize(vertex_count + 1);
vector<unsigned int> degrees(vertex_count);
deg_file.read(reinterpret_cast<char *>(°rees.front()), sizeof(int) * vertex_count);
deg_file.close();
deg_file.clear();
std::ifstream adj_file(adj_bin_path, std::ios::binary);
if (adj_file.is_open()) {
std::cout << "Open edge file " << adj_bin_path << " successfully." << std::endl;
}
else {
std::cerr << "Cannot open edge file " << adj_bin_path << " ." << std::endl;
exit(-1);
}
size_t neighbors_count = (size_t)edge_count * 2;
neighbors.resize(neighbors_count);
offsets[0] = 0;
for (unsigned int i = 1; i <= vertex_count; ++i) {
offsets[i] = offsets[i - 1] + degrees[i - 1];
}
for (unsigned int i = 0; i < vertex_count; ++i) {
if (degrees[i] > 0) {
adj_file.read(reinterpret_cast<char *>(&neighbors.data()[offsets[i]]), degrees[i] * sizeof(int));
}
}
adj_file.close();
adj_file.clear();
}
int main(int argc, char *argv[]) {
string input_edge_prob(argv[1]);
string input_degree_bin_path(argv[2]);
string input_adj_bin_path(argv[3]);
string output_degree_bin_path(argv[4]);
string output_adj_bin_path(argv[5]);
double prob_threshold = std::stod(input_edge_prob);
cout << "start read..." << endl;
vector<unsigned int> offset;
vector<unsigned int> adj_bin;
read_csr(input_degree_bin_path, input_adj_bin_path, offset, adj_bin);
vector<pair<int, int>> edge_list;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
for (unsigned int i = 0; i < offset.size() - 1; ++i) {
int src = i;
for (unsigned int j = offset[i]; j < offset[i + 1]; ++j) {
int dst = adj_bin[j];
if (src < dst) {
double prob = dis(gen);
if (prob < prob_threshold)
edge_list.emplace_back(make_pair(src, dst));
}
}
}
cout << "start write..." << endl;
write_csr(output_degree_bin_path, output_adj_bin_path, edge_list, offset.size() - 1);
cout << "finish..." << endl;
return 0;
}
| 30.295302 | 126 | 0.610323 | [
"vector"
] |
cc99211efc951fbdac3d0bf8b36c232663b1f6f1 | 1,218 | cpp | C++ | Project II Game/Motor2D/j1Scene2.cpp | Sanmopre/Sea_Conquest | 52c46c218b38eeaa8f7f224e7bff74ef2cc5d934 | [
"Zlib"
] | null | null | null | Project II Game/Motor2D/j1Scene2.cpp | Sanmopre/Sea_Conquest | 52c46c218b38eeaa8f7f224e7bff74ef2cc5d934 | [
"Zlib"
] | 1 | 2020-03-03T09:56:15.000Z | 2020-05-24T22:29:01.000Z | Project II Game/Motor2D/j1Scene2.cpp | Sanmopre/Sea_Conquest | 52c46c218b38eeaa8f7f224e7bff74ef2cc5d934 | [
"Zlib"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1PathFinding.h"
#include "j1Scene.h"
#include "j1Scene2.h"
#include "j1LogoScene.h"
#include "j1GUI.h"
#include "j1Transitions.h"
#include "j1TransitionManager.h"
j1Scene2::j1Scene2() : j1Module()
{
name.create("scene2");
}
// Destructor
j1Scene2::~j1Scene2()
{}
// Called before render is available
bool j1Scene2::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1Scene2::Start()
{
return true;
}
// Called each loop iteration
bool j1Scene2::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1Scene2::Update(float dt)
{
App->render->AddBlitEvent(1, main_texture, 0, 0, { 0,0,1280,720 }, false, true, 0u, 0u, 0u, 255, true);
return true;
}
bool j1Scene2::PostUpdate()
{
return true;
}
bool j1Scene2::CleanUp()
{
LOG("Freeing scene");
return true;
}
void j1Scene2::ChangeScene() {
this->active = true;
if (App->scene->active)
{
App->scene->CleanUp();
App->scene->active = false;
}
App->scene3->active = false;
App->scene2->Start();
} | 15.037037 | 104 | 0.678982 | [
"render"
] |
cca6f781078d83ddfa2f0edce48523c6a385efb1 | 377 | cpp | C++ | src/test/tutorial_render_simple.cpp | vadi2/nanobench | 954a82064141537330ab1a6ab27f01b21878bfa8 | [
"MIT"
] | 706 | 2019-10-08T05:29:49.000Z | 2022-03-31T06:49:24.000Z | src/test/tutorial_render_simple.cpp | vadi2/nanobench | 954a82064141537330ab1a6ab27f01b21878bfa8 | [
"MIT"
] | 55 | 2019-10-08T05:30:36.000Z | 2022-03-30T16:06:41.000Z | src/test/tutorial_render_simple.cpp | vadi2/nanobench | 954a82064141537330ab1a6ab27f01b21878bfa8 | [
"MIT"
] | 34 | 2019-10-12T13:50:08.000Z | 2022-03-29T15:01:21.000Z | #include <nanobench.h>
#include <thirdparty/doctest/doctest.h>
#include <atomic>
#include <iostream>
TEST_CASE("tutorial_render_simple") {
std::atomic<int> x(0);
ankerl::nanobench::Bench()
.output(nullptr)
.run("std::vector",
[&] {
++x;
})
.render(ankerl::nanobench::templates::csv(), std::cout);
}
| 20.944444 | 64 | 0.551724 | [
"render",
"vector"
] |
cca7d724de53f43aac0276f4e77ea5af0d1649f7 | 3,081 | cpp | C++ | src/module_peer/partner_table.cpp | umichan0621/P2P-File-Share-System | 3025dcde37c9fe4988f993ec2fa5bfe2804eaedb | [
"MIT"
] | null | null | null | src/module_peer/partner_table.cpp | umichan0621/P2P-File-Share-System | 3025dcde37c9fe4988f993ec2fa5bfe2804eaedb | [
"MIT"
] | null | null | null | src/module_peer/partner_table.cpp | umichan0621/P2P-File-Share-System | 3025dcde37c9fe4988f993ec2fa5bfe2804eaedb | [
"MIT"
] | null | null | null | #include "partner_table.h"
#include <base/logger/logger.h>
namespace peer
{
void PartnerTable::set_partner_max_num(uint16_t PartnerMaxNum)
{
m_PartnerMaxNum = PartnerMaxNum;
}
void PartnerTable::add_cid(const base::SHA1& CID)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
//已经记录
if (0 == m_PartnerMap.count(CID))
{
m_PartnerMap[CID].clear();
m_CIDList.push_front(CID);
}
}
void PartnerTable::add_partner(const base::SHA1& CID, uint16_t SessionId)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
//已经记录
if (0 != m_PartnerMap.count(CID))
{
if (0 == m_PartnerMap[CID].count(SessionId))
{
m_PartnerMap[CID].insert(SessionId);
m_PartnerContent[SessionId].push_back(CID);
}
}
else
{
m_PartnerMap[CID].insert(SessionId);
m_PartnerContent[SessionId].push_back(CID);
m_CIDList.push_front(CID);
}
}
void PartnerTable::delete_partner(uint16_t SessionId)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
if (0 != m_PartnerContent.count(SessionId))
{
//删除与SessionId有关的CID中的SessionId
for (auto& CID : m_PartnerContent[SessionId])
{
m_PartnerMap[CID].erase(SessionId);
//如果为空
if (true == m_PartnerMap[CID].empty())
{
m_PartnerMap.erase(CID);
}
}
m_PartnerContent.erase(SessionId);
}
}
bool PartnerTable::search_partner(const base::SHA1& CID, uint16_t SessionId)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
if (0 == m_PartnerMap.count(CID))
{
return false;
}
if (0 == m_PartnerMap[CID].count(SessionId))
{
return false;
}
return true;
}
void PartnerTable::delete_cid(const base::SHA1& CID)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
if (0 != m_PartnerMap.count(CID))
{
//与CID有关的所有SessionId
for (auto& SessionId : m_PartnerMap[CID])
{
for (auto It = m_PartnerContent[SessionId].begin(); It != m_PartnerContent[SessionId].end(); ++It)
{
//删除SessionId中的CID记录
if ((*It) == CID)
{
m_PartnerContent[SessionId].erase(It);
//如果为空
if (true == m_PartnerContent[SessionId].empty())
{
m_PartnerContent.erase(SessionId);
}
break;
}
}
}
}
}
bool PartnerTable::search_cid(const base::SHA1& CID)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
return 0 != m_PartnerMap.count(CID);
}
bool PartnerTable::search_cid(const base::SHA1& CID, std::vector<uint16_t>& PartnerList)
{
std::unique_lock<std::mutex> Lock(m_PartnerMutex);
if (0 == m_PartnerMap.count(CID))
{
return false;
}
for (auto& Partner : m_PartnerMap[CID])
{
PartnerList.push_back(Partner);
}
return true;
}
bool PartnerTable::get_cid(base::SHA1& CID)
{
if (true == m_CIDList.empty())
{
return false;
}
while (true != m_CIDList.empty())
{
//当前CID有效
if (0 != m_PartnerMap.count(m_CIDList.front()))
{
base::SHA1 Temp= m_CIDList.front();
CID = Temp;
m_CIDList.pop_front();
m_CIDList.push_back(Temp);
return true;
}
else
{
m_CIDList.pop_front();
}
}
return false;
}
} | 21.248276 | 102 | 0.653359 | [
"vector"
] |
ccaf44ca691a454d393d670a7d5000b85c90abc2 | 3,978 | cpp | C++ | contracts/game1/game1.cpp | trumae/dapp1 | 05a7c6d896e79f2056a6a57f716dfefc57d8f0e9 | [
"MIT"
] | null | null | null | contracts/game1/game1.cpp | trumae/dapp1 | 05a7c6d896e79f2056a6a57f716dfefc57d8f0e9 | [
"MIT"
] | null | null | null | contracts/game1/game1.cpp | trumae/dapp1 | 05a7c6d896e79f2056a6a57f716dfefc57d8f0e9 | [
"MIT"
] | null | null | null | /**
* @file
*
* 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
* 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
* 1188888881111888888811118888888111188888811111881111111111888881111118888811111888888811
* 1188111111111881118811118811111111188111881111881111111118811188131188111881111881111111
* 1188111111111881118811118111111111188111881111881111111118811188111188111111111881111111
* 1188888811111881118811118888888111188888811111881111111118888888111188111111111888888111
* 1188111111111881118811111111188111188111111111881111111118811188111188111111111881111111
* 1188111111111881118811111111188111188111111111881111111118811188111188111881111881111111
* 1188888881111888888811118888888111188111111111888888811118811188111118888811111888888811
* 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
* 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
*/
#include <utility>
#include <vector>
#include <string>
#include <eosiolib/eosio.hpp>
#include <eosiolib/asset.hpp>
#include <eosiolib/contract.hpp>
#include <eosiolib/singleton.hpp>
#include <eosiolib/crypto.h>
#include <eosiolib/print.hpp>
#include <ctime>
#include <sstream>
#include "cppjsindex.hpp"
using namespace eosio;
class game1 : public eosio::contract {
enum GameStatus { waiting, open, deadline, closed };
public:
using contract::contract;
game1(account_name self) :
contract(self){}
//@abi action
void newgame(const uint64_t o) {
}
//@abi action
void newplayer(const std::string login, const std::string pass) {
eosio_assert(login.size() > 6, "Login name too small");
eosio_assert(pass.size() > 9, "Password too small");
player_index players(_self, _self);
auto p = players.find(cppjsindex::index(login.c_str()));
eosio_assert(p == players.end(), "This name is already used");
players.emplace( _self, [&]( auto& s ) {
//s.id = players.available_primary_key();
s.id = cppjsindex::index(login.c_str());
s.login = login;
s.passhash = hashloginpass(login, pass);
s.balance = 1000;
});
}
private:
static checksum256 hashloginpass(const std::string &login, const std::string &pass) {
const std::string saltpass = "salt@!#@@";
checksum256 ret;
std::string ss = login + "_" + pass + saltpass;
sha256((char *) ss.c_str(), ss.size(), &ret);
return ret;
}
static bool is_equal(const checksum256& a, const checksum256& b) {
return memcmp((const void *)&a, (const void *)&b, sizeof(checksum256)) == 0;
}
//@abi table game i64
struct game {
uint64_t id;
uint64_t owner;
std::string name;
uint64_t primary_key()const { return id; }
EOSLIB_SERIALIZE( game,
(id)
(owner)
(name))
};
typedef eosio::multi_index< N(game), game> game_index;
//@abi table bet i64
struct bet {
uint64_t id;
uint64_t idgame;
uint64_t iduser;
uint32_t team1;
uint32_t team2;
uint64_t primary_key()const { return id; }
EOSLIB_SERIALIZE( bet,
(id)
(idgame)
(iduser)
(team1)
(team1))
};
typedef eosio::multi_index< N(bet), bet> bet_index;
//@abi table player i64
struct player {
uint64_t id;
std::string login;
checksum256 passhash;
uint64_t balance;
uint64_t primary_key()const { return id; }
EOSLIB_SERIALIZE( player,
(id)
(login)
(passhash)
(balance))
};
typedef eosio::multi_index< N(player), player> player_index;
struct tconfig {
account_name application;
EOSLIB_SERIALIZE( tconfig, (application) )
};
typedef singleton<N(tconfigs), tconfig> state_config;
};
EOSIO_ABI( game1, (newgame) (newplayer))
| 28.618705 | 91 | 0.696581 | [
"vector"
] |
ccb0db4b2056c4930c1100db85e12697b3a46b45 | 1,451 | cpp | C++ | Binary Search/Allocate Books.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | Binary Search/Allocate Books.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | Binary Search/Allocate Books.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | bool satisfy(vector<int> &books, int students,long mid) // mid is the maximum we want to acheive
{
int booksInd = 0;
int st = 0;
long totPages = 0;
while(st < students && booksInd < books.size())
{
if(totPages+books[booksInd] > mid)
{
totPages = 0;
st++;
}
else
{
totPages += books[booksInd];
booksInd++;
if(booksInd == books.size())
st++;
}
}
if(booksInd < books.size()) // increase the maximum, with such less maximum we can't allocate all the books.
return false;
/* please note i am not checking whether all students are served or not because if all students are not served,that means maximum value
is too high. Therefore we need to decrease the maximum. Hence we are returing true because even if we allocated successfully,
we would have decreased our hi and we also know we have a solution within this. */
return true;
}
int Solution::books(vector<int> &books, int students) {
if(students > books.size())
return -1;
long hi = 0;
for(int i=0;i<books.size();i++)
hi += books[i];
long lo = *(max_element(books.begin(),books.end()));
while(lo <= hi)
{
long mid = lo + (hi-lo)/2;
if(satisfy(books,students,mid))
hi = mid - 1;
else
lo = mid + 1;
}
return hi + 1;
}
| 31.543478 | 139 | 0.559614 | [
"vector"
] |
ccb3a3ba5bf25d5ed1ecc38739bc6560e04603a2 | 32,991 | cc | C++ | tensorpipe/transport/ibv/connection.cc | gunandrose4u/tensorpipe | d86777dbcefa3dd3133e866dbe6f075f2ac6a5e3 | [
"BSD-3-Clause"
] | null | null | null | tensorpipe/transport/ibv/connection.cc | gunandrose4u/tensorpipe | d86777dbcefa3dd3133e866dbe6f075f2ac6a5e3 | [
"BSD-3-Clause"
] | null | null | null | tensorpipe/transport/ibv/connection.cc | gunandrose4u/tensorpipe | d86777dbcefa3dd3133e866dbe6f075f2ac6a5e3 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <tensorpipe/transport/ibv/connection.h>
#include <string.h>
#include <deque>
#include <vector>
#include <tensorpipe/common/callback.h>
#include <tensorpipe/common/defs.h>
#include <tensorpipe/common/epoll_loop.h>
#include <tensorpipe/common/error_macros.h>
#include <tensorpipe/common/ibv.h>
#include <tensorpipe/common/memory.h>
#include <tensorpipe/common/ringbuffer_read_write_ops.h>
#include <tensorpipe/common/socket.h>
#include <tensorpipe/transport/error.h>
#include <tensorpipe/transport/ibv/context_impl.h>
#include <tensorpipe/transport/ibv/error.h>
#include <tensorpipe/transport/ibv/reactor.h>
#include <tensorpipe/transport/ibv/sockaddr.h>
#include <tensorpipe/util/ringbuffer/consumer.h>
#include <tensorpipe/util/ringbuffer/producer.h>
namespace tensorpipe {
namespace transport {
namespace ibv {
namespace {
constexpr auto kBufferSize = 2 * 1024 * 1024;
// When the connection gets closed, to avoid leaks, it needs to "reclaim" all
// the work requests that it had posted, by waiting for their completion. They
// may however complete with error, which makes it harder to identify and
// distinguish them from failing incoming requests because, in principle, we
// cannot access the opcode field of a failed work completion. Therefore, we
// assign a special ID to those types of requests, to match them later on.
constexpr uint64_t kWriteRequestId = 1;
constexpr uint64_t kAckRequestId = 2;
// The data that each queue pair endpoint needs to send to the other endpoint in
// order to set up the queue pair itself. This data is transferred over a TCP
// connection.
struct Exchange {
IbvSetupInformation setupInfo;
uint64_t memoryRegionPtr;
uint32_t memoryRegionKey;
};
} // namespace
class Connection::Impl : public std::enable_shared_from_this<Connection::Impl>,
public EpollLoop::EventHandler,
public IbvEventHandler {
enum State {
INITIALIZING = 1,
SEND_ADDR,
RECV_ADDR,
ESTABLISHED,
};
public:
// Create a connection that is already connected (e.g. from a listener).
Impl(
std::shared_ptr<Context::PrivateIface> context,
Socket socket,
std::string id);
// Create a connection that connects to the specified address.
Impl(
std::shared_ptr<Context::PrivateIface> context,
std::string addr,
std::string id);
// Initialize member fields that need `shared_from_this`.
void init();
// Queue a read operation.
void read(read_callback_fn fn);
void read(AbstractNopHolder& object, read_nop_callback_fn fn);
void read(void* ptr, size_t length, read_callback_fn fn);
// Perform a write operation.
void write(const void* ptr, size_t length, write_callback_fn fn);
void write(const AbstractNopHolder& object, write_callback_fn fn);
// Tell the connection what its identifier is.
void setId(std::string id);
// Shut down the connection and its resources.
void close();
// Implementation of EventHandler.
void handleEventsFromLoop(int events) override;
// Implementation of IbvEventHandler.
void onRemoteProducedData(uint32_t length) override;
void onRemoteConsumedData(uint32_t length) override;
void onWriteCompleted() override;
void onAckCompleted() override;
void onError(IbvLib::wc_status status, uint64_t wr_id) override;
private:
// Initialize member fields that need `shared_from_this`.
void initFromLoop();
// Queue a read operation.
void readFromLoop(read_callback_fn fn);
void readFromLoop(AbstractNopHolder& object, read_nop_callback_fn fn);
void readFromLoop(void* ptr, size_t length, read_callback_fn fn);
// Perform a write operation.
void writeFromLoop(const void* ptr, size_t length, write_callback_fn fn);
void writeFromLoop(const AbstractNopHolder& object, write_callback_fn fn);
void setIdFromLoop_(std::string id);
// Shut down the connection and its resources.
void closeFromLoop();
// Handle events of type EPOLLIN on the UNIX domain socket.
//
// The only data that is expected on that socket is the address and other
// setup information for the other side's queue pair and inbox.
void handleEventInFromLoop();
// Handle events of type EPOLLOUT on the UNIX domain socket.
//
// Once the socket is writable we send the address and other setup information
// for this side's queue pair and inbox.
void handleEventOutFromLoop();
State state_{INITIALIZING};
Error error_{Error::kSuccess};
std::shared_ptr<Context::PrivateIface> context_;
Socket socket_;
optional<Sockaddr> sockaddr_;
ClosingReceiver closingReceiver_;
IbvQueuePair qp_;
IbvSetupInformation ibvSelfInfo_;
// Inbox.
// Initialize header during construction because it isn't assignable.
util::ringbuffer::RingBufferHeader inboxHeader_{kBufferSize};
// Use mmapped memory so it's page-aligned (and, one day, to use huge pages).
MmappedPtr inboxBuf_;
util::ringbuffer::RingBuffer inboxRb_;
IbvMemoryRegion inboxMr_;
// Outbox.
// Initialize header during construction because it isn't assignable.
util::ringbuffer::RingBufferHeader outboxHeader_{kBufferSize};
// Use mmapped memory so it's page-aligned (and, one day, to use huge pages).
MmappedPtr outboxBuf_;
util::ringbuffer::RingBuffer outboxRb_;
IbvMemoryRegion outboxMr_;
// Peer inbox key, pointer and head.
uint32_t peerInboxKey_{0};
uint64_t peerInboxPtr_{0};
uint64_t peerInboxHead_{0};
// The ringbuffer API is synchronous (it expects data to be consumed/produced
// immediately "inline" when the buffer is accessed) but InfiniBand is
// asynchronous, thus we need to abuse the ringbuffer API a bit. When new data
// is appended to the outbox, we must access it, to send it over IB, but we
// must first skip over the data that we have already started sending which is
// still in flight (we can only "commit" that data, by increasing the tail,
// once the remote acknowledges it, or else it could be overwritten). We keep
// track of how much data to skip with this field.
uint32_t numBytesInFlight_{0};
// The connection performs two types of send requests: writing to the remote
// inbox, or acknowledging a write into its own inbox. These send operations
// could be delayed and stalled by the reactor as only a limited number of
// work requests can be outstanding at the same time globally. Thus we keep
// count of how many we have pending to make sure they have all completed or
// flushed when we close, and that none is stuck in the pipeline.
uint32_t numWritesInFlight_{0};
uint32_t numAcksInFlight_{0};
// Pending read operations.
std::deque<RingbufferReadOperation> readOperations_;
// Pending write operations.
std::deque<RingbufferWriteOperation> writeOperations_;
// A sequence number for the calls to read.
uint64_t nextBufferBeingRead_{0};
// A sequence number for the calls to write.
uint64_t nextBufferBeingWritten_{0};
// A sequence number for the invocations of the callbacks of read.
uint64_t nextReadCallbackToCall_{0};
// A sequence number for the invocations of the callbacks of write.
uint64_t nextWriteCallbackToCall_{0};
// An identifier for the connection, composed of the identifier for the
// context or listener, combined with an increasing sequence number. It will
// only be used for logging and debugging purposes.
std::string id_;
// Process pending read operations if in an operational state.
//
// This may be triggered by the other side of the connection (by pushing this
// side's inbox token to the reactor) when it has written some new data to its
// outbox (which is this side's inbox). It is also called by this connection
// when it moves into an established state or when a new read operation is
// queued, in case data was already available before this connection was ready
// to consume it.
void processReadOperationsFromLoop();
// Process pending write operations if in an operational state.
//
// This may be triggered by the other side of the connection (by pushing this
// side's outbox token to the reactor) when it has read some data from its
// inbox (which is this side's outbox). This is important when some of this
// side's writes couldn't complete because the outbox was full, and thus they
// needed to wait for some of its data to be read. This method is also called
// by this connection when it moves into an established state, in case some
// writes were queued before the connection was ready to process them, or when
// a new write operation is queued.
void processWriteOperationsFromLoop();
void setError_(Error error);
// Deal with an error.
void handleError();
void tryCleanup_();
void cleanup_();
};
Connection::Connection(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
Socket socket,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(socket),
std::move(id))) {
impl_->init();
}
Connection::Connection(
ConstructorToken /* unused */,
std::shared_ptr<Context::PrivateIface> context,
std::string addr,
std::string id)
: impl_(std::make_shared<Impl>(
std::move(context),
std::move(addr),
std::move(id))) {
impl_->init();
}
void Connection::Impl::init() {
context_->deferToLoop([impl{shared_from_this()}]() { impl->initFromLoop(); });
}
void Connection::close() {
impl_->close();
}
void Connection::Impl::close() {
context_->deferToLoop(
[impl{shared_from_this()}]() { impl->closeFromLoop(); });
}
Connection::~Connection() {
close();
}
Connection::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
Socket socket,
std::string id)
: context_(std::move(context)),
socket_(std::move(socket)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
Connection::Impl::Impl(
std::shared_ptr<Context::PrivateIface> context,
std::string addr,
std::string id)
: context_(std::move(context)),
sockaddr_(Sockaddr::createInetSockAddr(addr)),
closingReceiver_(context_, context_->getClosingEmitter()),
id_(std::move(id)) {}
void Connection::Impl::initFromLoop() {
TP_DCHECK(context_->inLoop());
closingReceiver_.activate(*this);
Error error;
// The connection either got a socket or an address, but not both.
TP_DCHECK(socket_.hasValue() ^ sockaddr_.has_value());
if (!socket_.hasValue()) {
std::tie(error, socket_) =
Socket::createForFamily(sockaddr_->addr()->sa_family);
if (error) {
setError_(std::move(error));
return;
}
error = socket_.reuseAddr(true);
if (error) {
setError_(std::move(error));
return;
}
error = socket_.connect(sockaddr_.value());
if (error) {
setError_(std::move(error));
return;
}
}
// Ensure underlying control socket is non-blocking such that it
// works well with event driven I/O.
error = socket_.block(false);
if (error) {
setError_(std::move(error));
return;
}
// Create ringbuffer for inbox.
inboxBuf_ = MmappedPtr(
kBufferSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1);
inboxRb_ = util::ringbuffer::RingBuffer(&inboxHeader_, inboxBuf_.ptr());
inboxMr_ = createIbvMemoryRegion(
context_->getReactor().getIbvLib(),
context_->getReactor().getIbvPd(),
inboxBuf_.ptr(),
kBufferSize,
IbvLib::ACCESS_LOCAL_WRITE | IbvLib::ACCESS_REMOTE_WRITE);
// Create ringbuffer for outbox.
outboxBuf_ = MmappedPtr(
kBufferSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1);
outboxRb_ = util::ringbuffer::RingBuffer(&outboxHeader_, outboxBuf_.ptr());
outboxMr_ = createIbvMemoryRegion(
context_->getReactor().getIbvLib(),
context_->getReactor().getIbvPd(),
outboxBuf_.ptr(),
kBufferSize,
0);
// Create and init queue pair.
{
IbvLib::qp_init_attr initAttr;
std::memset(&initAttr, 0, sizeof(initAttr));
initAttr.qp_type = IbvLib::QPT_RC;
initAttr.send_cq = context_->getReactor().getIbvCq().get();
initAttr.recv_cq = context_->getReactor().getIbvCq().get();
initAttr.cap.max_send_wr = kNumPendingWriteReqs;
initAttr.cap.max_send_sge = 1;
initAttr.srq = context_->getReactor().getIbvSrq().get();
initAttr.sq_sig_all = 1;
qp_ = createIbvQueuePair(
context_->getReactor().getIbvLib(),
context_->getReactor().getIbvPd(),
initAttr);
}
transitionIbvQueuePairToInit(
context_->getReactor().getIbvLib(),
qp_,
context_->getReactor().getIbvAddress());
// Register methods to be called when our peer writes to our inbox and reads
// from our outbox.
context_->getReactor().registerQp(qp_->qp_num, shared_from_this());
// We're sending address first, so wait for writability.
state_ = SEND_ADDR;
context_->registerDescriptor(socket_.fd(), EPOLLOUT, shared_from_this());
}
void Connection::read(read_callback_fn fn) {
impl_->read(std::move(fn));
}
void Connection::Impl::read(read_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, fn{std::move(fn)}]() mutable {
impl->readFromLoop(std::move(fn));
});
}
void Connection::Impl::readFromLoop(read_callback_fn fn) {
TP_DCHECK(context_->inLoop());
uint64_t sequenceNumber = nextBufferBeingRead_++;
TP_VLOG(7) << "Connection " << id_ << " received an unsized read request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error, const void* ptr, size_t length) {
TP_DCHECK_EQ(sequenceNumber, nextReadCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_
<< " is calling an unsized read callback (#" << sequenceNumber
<< ")";
fn(error, ptr, length);
TP_VLOG(7) << "Connection " << id_
<< " done calling an unsized read callback (#" << sequenceNumber
<< ")";
};
if (error_) {
fn(error_, nullptr, 0);
return;
}
readOperations_.emplace_back(std::move(fn));
// If the inbox already contains some data, we may be able to process this
// operation right away.
processReadOperationsFromLoop();
}
void Connection::read(AbstractNopHolder& object, read_nop_callback_fn fn) {
impl_->read(object, std::move(fn));
}
void Connection::Impl::read(
AbstractNopHolder& object,
read_nop_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, &object, fn{std::move(fn)}]() mutable {
impl->readFromLoop(object, std::move(fn));
});
}
void Connection::Impl::readFromLoop(
AbstractNopHolder& object,
read_nop_callback_fn fn) {
TP_DCHECK(context_->inLoop());
uint64_t sequenceNumber = nextBufferBeingRead_++;
TP_VLOG(7) << "Connection " << id_ << " received a nop object read request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](const Error& error) {
TP_DCHECK_EQ(sequenceNumber, nextReadCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_
<< " is calling a nop object read callback (#" << sequenceNumber
<< ")";
fn(error);
TP_VLOG(7) << "Connection " << id_
<< " done calling a nop object read callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_);
return;
}
readOperations_.emplace_back(
&object,
[fn{std::move(fn)}](
const Error& error, const void* /* unused */, size_t /* unused */) {
fn(error);
});
// If the inbox already contains some data, we may be able to process this
// operation right away.
processReadOperationsFromLoop();
}
void Connection::read(void* ptr, size_t length, read_callback_fn fn) {
impl_->read(ptr, length, std::move(fn));
}
void Connection::Impl::read(void* ptr, size_t length, read_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, ptr, length, fn{std::move(fn)}]() mutable {
impl->readFromLoop(ptr, length, std::move(fn));
});
}
void Connection::Impl::readFromLoop(
void* ptr,
size_t length,
read_callback_fn fn) {
TP_DCHECK(context_->inLoop());
uint64_t sequenceNumber = nextBufferBeingRead_++;
TP_VLOG(7) << "Connection " << id_ << " received a sized read request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](
const Error& error, const void* ptr, size_t length) {
TP_DCHECK_EQ(sequenceNumber, nextReadCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_ << " is calling a sized read callback (#"
<< sequenceNumber << ")";
fn(error, ptr, length);
TP_VLOG(7) << "Connection " << id_
<< " done calling a sized read callback (#" << sequenceNumber
<< ")";
};
if (error_) {
fn(error_, ptr, length);
return;
}
readOperations_.emplace_back(ptr, length, std::move(fn));
// If the inbox already contains some data, we may be able to process this
// operation right away.
processReadOperationsFromLoop();
}
void Connection::write(const void* ptr, size_t length, write_callback_fn fn) {
impl_->write(ptr, length, std::move(fn));
}
void Connection::Impl::write(
const void* ptr,
size_t length,
write_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, ptr, length, fn{std::move(fn)}]() mutable {
impl->writeFromLoop(ptr, length, std::move(fn));
});
}
void Connection::Impl::writeFromLoop(
const void* ptr,
size_t length,
write_callback_fn fn) {
TP_DCHECK(context_->inLoop());
uint64_t sequenceNumber = nextBufferBeingWritten_++;
TP_VLOG(7) << "Connection " << id_ << " received a write request (#"
<< sequenceNumber << ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](const Error& error) {
TP_DCHECK_EQ(sequenceNumber, nextWriteCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_ << " is calling a write callback (#"
<< sequenceNumber << ")";
fn(error);
TP_VLOG(7) << "Connection " << id_ << " done calling a write callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_);
return;
}
writeOperations_.emplace_back(ptr, length, std::move(fn));
// If the outbox has some free space, we may be able to process this operation
// right away.
processWriteOperationsFromLoop();
}
void Connection::write(const AbstractNopHolder& object, write_callback_fn fn) {
impl_->write(object, std::move(fn));
}
void Connection::Impl::write(
const AbstractNopHolder& object,
write_callback_fn fn) {
context_->deferToLoop(
[impl{shared_from_this()}, &object, fn{std::move(fn)}]() mutable {
impl->writeFromLoop(object, std::move(fn));
});
}
void Connection::Impl::writeFromLoop(
const AbstractNopHolder& object,
write_callback_fn fn) {
TP_DCHECK(context_->inLoop());
uint64_t sequenceNumber = nextBufferBeingWritten_++;
TP_VLOG(7) << "Connection " << id_
<< " received a nop object write request (#" << sequenceNumber
<< ")";
fn = [this, sequenceNumber, fn{std::move(fn)}](const Error& error) {
TP_DCHECK_EQ(sequenceNumber, nextWriteCallbackToCall_++);
TP_VLOG(7) << "Connection " << id_
<< " is calling a nop object write callback (#" << sequenceNumber
<< ")";
fn(error);
TP_VLOG(7) << "Connection " << id_
<< " done calling a nop object write callback (#"
<< sequenceNumber << ")";
};
if (error_) {
fn(error_);
return;
}
writeOperations_.emplace_back(&object, std::move(fn));
// If the outbox has some free space, we may be able to process this operation
// right away.
processWriteOperationsFromLoop();
}
void Connection::setId(std::string id) {
impl_->setId(std::move(id));
}
void Connection::Impl::setId(std::string id) {
context_->deferToLoop(
[impl{shared_from_this()}, id{std::move(id)}]() mutable {
impl->setIdFromLoop_(std::move(id));
});
}
void Connection::Impl::setIdFromLoop_(std::string id) {
TP_DCHECK(context_->inLoop());
TP_VLOG(7) << "Connection " << id_ << " was renamed to " << id;
id_ = std::move(id);
}
void Connection::Impl::handleEventsFromLoop(int events) {
TP_DCHECK(context_->inLoop());
TP_VLOG(9) << "Connection " << id_ << " is handling an event on its socket ("
<< EpollLoop::formatEpollEvents(events) << ")";
// Handle only one of the events in the mask. Events on the control
// file descriptor are rare enough for the cost of having epoll call
// into this function multiple times to not matter. The benefit is
// that every handler can close and unregister the control file
// descriptor from the event loop, without worrying about the next
// handler trying to do so as well.
// In some cases the socket could be in a state where it's both in an error
// state and readable/writable. If we checked for EPOLLIN or EPOLLOUT first
// and then returned after handling them, we would keep doing so forever and
// never reach the error handling. So we should keep the error check first.
if (events & EPOLLERR) {
int error;
socklen_t errorlen = sizeof(error);
int rv = getsockopt(
socket_.fd(),
SOL_SOCKET,
SO_ERROR,
reinterpret_cast<void*>(&error),
&errorlen);
if (rv == -1) {
setError_(TP_CREATE_ERROR(SystemError, "getsockopt", rv));
} else {
setError_(TP_CREATE_ERROR(SystemError, "async error on socket", error));
}
return;
}
if (events & EPOLLIN) {
handleEventInFromLoop();
return;
}
if (events & EPOLLOUT) {
handleEventOutFromLoop();
return;
}
// Check for hangup last, as there could be cases where we get EPOLLHUP but
// there's still data to be read from the socket, so we want to deal with that
// before dealing with the hangup.
if (events & EPOLLHUP) {
setError_(TP_CREATE_ERROR(EOFError));
return;
}
}
void Connection::Impl::handleEventInFromLoop() {
TP_DCHECK(context_->inLoop());
if (state_ == RECV_ADDR) {
struct Exchange ex;
auto err = socket_.read(&ex, sizeof(ex));
// Crossing our fingers that the exchange information is small enough that
// it can be read in a single chunk.
if (err != sizeof(ex)) {
setError_(TP_CREATE_ERROR(ShortReadError, sizeof(ex), err));
return;
}
transitionIbvQueuePairToReadyToReceive(
context_->getReactor().getIbvLib(),
qp_,
context_->getReactor().getIbvAddress(),
ex.setupInfo);
transitionIbvQueuePairToReadyToSend(
context_->getReactor().getIbvLib(), qp_, ibvSelfInfo_);
peerInboxKey_ = ex.memoryRegionKey;
peerInboxPtr_ = ex.memoryRegionPtr;
// The connection is usable now.
state_ = ESTABLISHED;
processWriteOperationsFromLoop();
// Trigger read operations in case a pair of local read() and remote
// write() happened before connection is established. Otherwise read()
// callback would lose if it's the only read() request.
processReadOperationsFromLoop();
return;
}
if (state_ == ESTABLISHED) {
// We don't expect to read anything on this socket once the
// connection has been established. If we do, assume it's a
// zero-byte read indicating EOF.
setError_(TP_CREATE_ERROR(EOFError));
return;
}
TP_THROW_ASSERT() << "EPOLLIN event not handled in state " << state_;
}
void Connection::Impl::handleEventOutFromLoop() {
TP_DCHECK(context_->inLoop());
if (state_ == SEND_ADDR) {
Exchange ex;
ibvSelfInfo_ =
makeIbvSetupInformation(context_->getReactor().getIbvAddress(), qp_);
ex.setupInfo = ibvSelfInfo_;
ex.memoryRegionPtr = reinterpret_cast<uint64_t>(inboxBuf_.ptr());
ex.memoryRegionKey = inboxMr_->rkey;
auto err = socket_.write(reinterpret_cast<void*>(&ex), sizeof(ex));
// Crossing our fingers that the exchange information is small enough that
// it can be written in a single chunk.
if (err != sizeof(ex)) {
setError_(TP_CREATE_ERROR(ShortWriteError, sizeof(ex), err));
return;
}
// Sent our address. Wait for address from peer.
state_ = RECV_ADDR;
context_->registerDescriptor(socket_.fd(), EPOLLIN, shared_from_this());
return;
}
TP_THROW_ASSERT() << "EPOLLOUT event not handled in state " << state_;
}
void Connection::Impl::processReadOperationsFromLoop() {
TP_DCHECK(context_->inLoop());
// Process all read read operations that we can immediately serve, only
// when connection is established.
if (state_ != ESTABLISHED) {
return;
}
// Serve read operations
util::ringbuffer::Consumer inboxConsumer(inboxRb_);
while (!readOperations_.empty()) {
RingbufferReadOperation& readOperation = readOperations_.front();
ssize_t len = readOperation.handleRead(inboxConsumer);
if (len > 0) {
IbvLib::send_wr wr;
std::memset(&wr, 0, sizeof(wr));
wr.wr_id = kAckRequestId;
wr.opcode = IbvLib::WR_SEND_WITH_IMM;
wr.imm_data = len;
TP_VLOG(9) << "Connection " << id_
<< " is posting a send request (acknowledging " << wr.imm_data
<< " bytes) on QP " << qp_->qp_num;
context_->getReactor().postAck(qp_, wr);
numAcksInFlight_++;
}
if (readOperation.completed()) {
readOperations_.pop_front();
} else {
break;
}
}
}
void Connection::Impl::processWriteOperationsFromLoop() {
TP_DCHECK(context_->inLoop());
if (state_ != ESTABLISHED) {
return;
}
util::ringbuffer::Producer outboxProducer(outboxRb_);
while (!writeOperations_.empty()) {
RingbufferWriteOperation& writeOperation = writeOperations_.front();
ssize_t len = writeOperation.handleWrite(outboxProducer);
if (len > 0) {
ssize_t ret;
util::ringbuffer::Consumer outboxConsumer(outboxRb_);
// In order to get the pointers and lengths to the data that was just
// written to the ringbuffer we pretend to start a consumer transaction so
// we can use accessContiguous, which we'll however later abort. The data
// will only be really consumed once we receive the ACK from the remote.
ret = outboxConsumer.startTx();
TP_THROW_SYSTEM_IF(ret < 0, -ret);
ssize_t numBuffers;
std::array<util::ringbuffer::Consumer::Buffer, 2> buffers;
// Skip over the data that was already sent but is still in flight.
std::tie(numBuffers, buffers) =
outboxConsumer.accessContiguousInTx</*allowPartial=*/false>(
numBytesInFlight_);
std::tie(numBuffers, buffers) =
outboxConsumer.accessContiguousInTx</*allowPartial=*/false>(len);
TP_THROW_SYSTEM_IF(numBuffers < 0, -numBuffers);
for (int bufferIdx = 0; bufferIdx < numBuffers; bufferIdx++) {
IbvLib::sge list;
list.addr = reinterpret_cast<uint64_t>(buffers[bufferIdx].ptr);
list.length = buffers[bufferIdx].len;
list.lkey = outboxMr_->lkey;
uint64_t peerInboxOffset = peerInboxHead_ & (kBufferSize - 1);
peerInboxHead_ += buffers[bufferIdx].len;
IbvLib::send_wr wr;
std::memset(&wr, 0, sizeof(wr));
wr.wr_id = kWriteRequestId;
wr.sg_list = &list;
wr.num_sge = 1;
wr.opcode = IbvLib::WR_RDMA_WRITE_WITH_IMM;
wr.imm_data = buffers[bufferIdx].len;
wr.wr.rdma.remote_addr = peerInboxPtr_ + peerInboxOffset;
wr.wr.rdma.rkey = peerInboxKey_;
TP_VLOG(9) << "Connection " << id_
<< " is posting a RDMA write request (transmitting "
<< wr.imm_data << " bytes) on QP " << qp_->qp_num;
context_->getReactor().postWrite(qp_, wr);
numWritesInFlight_++;
}
ret = outboxConsumer.cancelTx();
TP_THROW_SYSTEM_IF(ret < 0, -ret);
numBytesInFlight_ += len;
}
if (writeOperation.completed()) {
writeOperations_.pop_front();
} else {
break;
}
}
}
void Connection::Impl::onRemoteProducedData(uint32_t length) {
TP_DCHECK(context_->inLoop());
TP_VLOG(9) << "Connection " << id_ << " was signalled that " << length
<< " bytes were written to its inbox on QP " << qp_->qp_num;
// We could start a transaction and use the proper methods for this, but as
// this method is the only producer for the inbox ringbuffer we can cut it
// short and directly increase the head.
inboxHeader_.incHead(length);
processReadOperationsFromLoop();
}
void Connection::Impl::onRemoteConsumedData(uint32_t length) {
TP_DCHECK(context_->inLoop());
TP_VLOG(9) << "Connection " << id_ << " was signalled that " << length
<< " bytes were read from its outbox on QP " << qp_->qp_num;
// We could start a transaction and use the proper methods for this, but as
// this method is the only consumer for the outbox ringbuffer we can cut it
// short and directly increase the tail.
outboxHeader_.incTail(length);
numBytesInFlight_ -= length;
processWriteOperationsFromLoop();
}
void Connection::Impl::onWriteCompleted() {
TP_DCHECK(context_->inLoop());
TP_VLOG(9) << "Connection " << id_
<< " done posting a RDMA write request on QP " << qp_->qp_num;
numWritesInFlight_--;
tryCleanup_();
}
void Connection::Impl::onAckCompleted() {
TP_DCHECK(context_->inLoop());
TP_VLOG(9) << "Connection " << id_ << " done posting a send request on QP "
<< qp_->qp_num;
numAcksInFlight_--;
tryCleanup_();
}
void Connection::Impl::onError(IbvLib::wc_status status, uint64_t wr_id) {
TP_DCHECK(context_->inLoop());
setError_(TP_CREATE_ERROR(
IbvError, context_->getReactor().getIbvLib().wc_status_str(status)));
if (wr_id == kWriteRequestId) {
onWriteCompleted();
} else if (wr_id == kAckRequestId) {
onAckCompleted();
}
}
void Connection::Impl::setError_(Error error) {
// Don't overwrite an error that's already set.
if (error_ || !error) {
return;
}
error_ = std::move(error);
handleError();
}
void Connection::Impl::handleError() {
TP_DCHECK(context_->inLoop());
TP_VLOG(8) << "Connection " << id_ << " is handling error " << error_.what();
for (auto& readOperation : readOperations_) {
readOperation.handleError(error_);
}
readOperations_.clear();
for (auto& writeOperation : writeOperations_) {
writeOperation.handleError(error_);
}
writeOperations_.clear();
transitionIbvQueuePairToError(context_->getReactor().getIbvLib(), qp_);
tryCleanup_();
if (socket_.hasValue()) {
if (state_ > INITIALIZING) {
context_->unregisterDescriptor(socket_.fd());
}
socket_.reset();
}
}
void Connection::Impl::tryCleanup_() {
TP_DCHECK(context_->inLoop());
// Setting the queue pair to an error state will cause all its work requests
// (both those that had started being served, and those that hadn't; including
// those from a shared receive queue) to be flushed. We need to wait for the
// completion events of all those requests to be retrieved from the completion
// queue before we can destroy the queue pair. We can do so by deferring the
// destruction to the loop, since the reactor will only proceed to invoke
// deferred functions once it doesn't have any completion events to handle.
// However the RDMA writes and the sends may be queued up inside the reactor
// and thus may not have even been scheduled yet, so we explicitly wait for
// them to complete.
if (error_) {
if (numWritesInFlight_ == 0 && numAcksInFlight_ == 0) {
TP_VLOG(8) << "Connection " << id_ << " is ready to clean up";
context_->deferToLoop([impl{shared_from_this()}]() { impl->cleanup_(); });
} else {
TP_VLOG(9) << "Connection " << id_
<< " cannot proceed to cleanup because it has "
<< numWritesInFlight_ << " pending RDMA write requests and "
<< numAcksInFlight_ << " pending send requests on QP "
<< qp_->qp_num;
}
}
}
void Connection::Impl::cleanup_() {
TP_DCHECK(context_->inLoop());
TP_VLOG(8) << "Connection " << id_ << " is cleaning up";
context_->getReactor().unregisterQp(qp_->qp_num);
qp_.reset();
inboxMr_.reset();
inboxBuf_.reset();
outboxMr_.reset();
outboxBuf_.reset();
}
void Connection::Impl::closeFromLoop() {
TP_DCHECK(context_->inLoop());
TP_VLOG(7) << "Connection " << id_ << " is closing";
setError_(TP_CREATE_ERROR(ConnectionClosedError));
}
} // namespace ibv
} // namespace transport
} // namespace tensorpipe
| 33.123494 | 80 | 0.675093 | [
"object",
"vector"
] |
ccc0ac566330537b8460d4d663374d95b51255f2 | 309 | cc | C++ | src/addon.cc | nick-thompson/jetpack | aca463c8a762dc1821a7a7e8ca32f857a011cb63 | [
"MIT"
] | 5 | 2015-09-02T19:54:11.000Z | 2021-01-21T06:12:54.000Z | src/addon.cc | nick-thompson/jetpack | aca463c8a762dc1821a7a7e8ca32f857a011cb63 | [
"MIT"
] | null | null | null | src/addon.cc | nick-thompson/jetpack | aca463c8a762dc1821a7a7e8ca32f857a011cb63 | [
"MIT"
] | 1 | 2016-04-22T10:09:50.000Z | 2016-04-22T10:09:50.000Z | #include <nan.h>
#include "hive.h"
using namespace v8;
void Init(Handle<Object> exports) {
exports->Set(NanNew<String>("eval"),
NanNew<FunctionTemplate>(Eval)->GetFunction());
exports->Set(NanNew<String>("init"),
NanNew<FunctionTemplate>(Initialize)->GetFunction());
}
NODE_MODULE(addon, Init)
| 22.071429 | 57 | 0.705502 | [
"object"
] |
ccc652ea1dd64d6730c5775653ce01344cc6cb2d | 3,489 | cpp | C++ | HotDir/hd60/hditer.cpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | 1 | 2015-03-26T02:35:13.000Z | 2015-03-26T02:35:13.000Z | HotDir/hd60/hditer.cpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | HotDir/hd60/hditer.cpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | /* hditer.cpp - iterates through the options of hotdir
see 'hditer.h' for details
http://vividos.home.pages.de - vividos@asamnet.de
(c) 1999 Michael Fink
*/
#include "hditer.h"
#include "hdstring.h"
#include "formatul.h"
#include "console.h"
#include "hdcont.h"
#include "hdviewer.h"
#include "hdtree.h"
#include <string.h>
#include <dir.h>
#include <dos.h>
extern console *con;
hditerator::hditerator(hdprefs *_hdp){
hdp=_hdp;
drives=new bool[26];
for(int n=0;n<26;drives[n++]=false);
pathcount=0;
filecount=0;
all_needed_size=0;
all_true_size=0;
};
hditerator::~hditerator(){
if (!hdp->treemode){
if (pathcount==0)
con->printf("^7sorry, no output.\n");
if (pathcount>1)
show_allpath_infos();
};
for(int n=0;n<26;n++)
if (drives[n])
show_drive_infos( n+'A' );
delete drives;
};
void hditerator::iterate(object *o){
hdstring *hds=(hdstring*)o;
if (hdp->treemode){
char *name=hds->getstr();
drives[ (name[1]==':') ? (name[0]-1)&0x1f : getdisk() ] = true;
treeViewer *tv=new treeViewer;
tv->processTree(hds->getstr());
tv->showTree();
delete tv;
return;
};
// files in container holen
hdfilecontainer *hdfc=
new hdfilecontainer(hds->getstr(),hdp->sc,hdp->sort_reverse);
hdfc->fill_container();
if (! (!hdp->showEmpty&&hdfc->getNumber()==0) ) {
con->printf("^fPath:^e%s^7\n",hds->getstr());
pathcount++;
char *name=hds->getstr();
drives[ (name[1]==':') ? (name[0]-1)&0x1f : getdisk() ] = true;
if (hdfc->getNumber()==0){
con->printf("no files found.\n");
} else {
// files anzeigen !!!
hdviewer *hdv=new hdviewer(hdp);
hdv->view( hdfc );
delete hdv;
ulong needed=hdfc->get_needed_size(),truesize=hdfc->get_true_size();
char line[32];
con->printf("^c%u^a files, using ^c%s^a bytes, ",
hdfc->getNumber(),format_ulong(truesize,line));
word rate=0;
if (needed!=0)
rate=(word)( ((ulong)truesize) / ((ulong)needed/100L) );
con->printf("needing ^c%s^a bytes (^c%u%%^a).^7\n",
format_ulong(needed,line),rate);
filecount+=hdfc->getNumber();
all_needed_size+=needed;
all_true_size+=truesize;
};
};
delete hdfc;
};
void hditerator::show_allpath_infos(){
char line[32];
con->printf("^4%u^2 paths, ^4%lu^2 files, using ^4%s^2 bytes, ",
pathcount,filecount,format_ulong(all_true_size,line));
con->printf("needing ^4%s^2 bytes.^7\n",format_ulong(all_needed_size,line));
};
void hditerator::show_drive_infos(char drive){
dfree df;
getdfree(drive&0x1f,&df);
ulong clsize=(ulong)df.df_bsec*df.df_sclus;
ulong free=(ulong)df.df_avail*clsize;
ulong total=(ulong)df.df_total*clsize;
char line[32];
con->printf("^adrive ^c%c:^a info: ^c%s^a bytes of ",drive,
format_ulong(free,line) );
con->printf("^c%s^a bytes available.^7\n",format_ulong(total,line));
word rate=0;
if (total!=0)
rate=(word)( ((ulong)free) / ((ulong)total/10000L) );
char path[8];
strcpy(path,"x:\\*.*");
path[0]=drive;
char *label=NULL;
ffblk ff;
if (findfirst(path,&ff,FA_LABEL)==0){
int res=0;
while ((ff.ff_attrib&0xc0)!=0&&res==0) res=findnext(&ff);
if (res==0)
label=ff.ff_name;
};
if (label==NULL)
label="^anone";
else
if (strlen(label)>=8)
for(int n=8;n<13;n++)label[n]=label[n+1];
con->printf(" ^c%u.%2.2u%%^a free; Label: ^e%.11s^7\n",
rate/100,rate%100,label);
};
| 21.145455 | 78 | 0.610203 | [
"object"
] |
cccf1d3bb1d2dba2253aecb886c95282ad639dd6 | 3,848 | cpp | C++ | src/main-window.cpp | fourtf/nm-popup | f15fd95d7b074233ea02ded3d4a08fe65f668399 | [
"MIT"
] | 1 | 2019-06-27T20:26:27.000Z | 2019-06-27T20:26:27.000Z | src/main-window.cpp | fourtf/nm-popup | f15fd95d7b074233ea02ded3d4a08fe65f668399 | [
"MIT"
] | null | null | null | src/main-window.cpp | fourtf/nm-popup | f15fd95d7b074233ea02ded3d4a08fe65f668399 | [
"MIT"
] | null | null | null | #include "main-window.hpp"
#include "config.hpp"
#include "function-event-filter.hpp"
#include "make-widget.hpp"
#include "network-table-model.hpp"
#include "networking.hpp"
#include "theme.hpp"
#include "util.hpp"
#include <QHeaderView>
#include <QKeyEvent>
#include <QPushButton>
#include <QStringListModel>
#include <QTableView>
#include <QThread>
#include <QDebug>
namespace {
constexpr int ssidColumn = 1;
QString selectedItem(QTableView *view) {
return view->currentIndex()
.siblingAtColumn(1)
.data(Qt::DisplayRole)
.toString();
}
void selectItem(QTableView *view, const QString &selected) {
// keep selection
if (selected.isNull()) {
if (view->model()->rowCount() > 0) {
view->setCurrentIndex(view->model()->index(0, 0));
}
} else {
for (int i = 0; i < view->model()->rowCount(); i++) {
auto index = view->model()->index(i, ssidColumn);
if (selected == index.data(Qt::DisplayRole).toString()) {
view->setCurrentIndex(index);
break;
}
}
}
}
auto windowType() {
unsigned type = Qt::Dialog;
if (config().borderless) {
type |= Qt::FramelessWindowHint;
}
return Qt::WindowFlags(type);
}
void connectWifi(const QString &ssid) {
networking().connectWifi(ssid, config().getPasswordForSsid(ssid));
}
} // namespace
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent, ::windowType()), creationTime_(QTime::currentTime()) {
this->model_ = new NetworkTableModel();
QObject::connect(&networking(), &Networking::wifiNetworksUpdated, this,
[this](auto &&items) {
auto selected = selectedItem(this->wifiList_);
this->model_->setItems(items);
this->wifiList_->resizeColumnsToContents();
selectItem(this->wifiList_, selected);
});
networking().queryWifiNetworks(false);
networking().queryWifiNetworks();
this->initLayout();
this->setStyleSheet(theme().qss);
this->setMinimumSize({350, 400});
}
void MainWindow::keyReleaseEvent(QKeyEvent *e) {
switch (e->key()) {
case Qt::Key_Escape:
case Qt::Key_Q: {
this->close();
} break;
case Qt::Key_R:
case Qt::Key_F5: {
networking().queryWifiNetworks();
} break;
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Space: {
return_if(this->creationTime_.addSecs(1) > QTime::currentTime());
// select item
auto selected = selectedItem(this->wifiList_);
return_if(selected.isNull());
connectWifi(selected);
// close on enter
if (e->key() != Qt::Key_Space) {
// this->close();
}
} break;
}
}
void MainWindow::initLayout() {
this->setCentralWidget(make([=](QWidget *w) {
// vertical layout
w->setLayout(makeLayout<QVBoxLayout>({
// table view containing list of wifi networks
make([=](QTableView *w) {
this->wifiList_ = w;
w->setSelectionBehavior(QAbstractItemView::SelectRows);
w->setSelectionMode(QAbstractItemView::SingleSelection);
w->verticalHeader()->hide();
w->setModel(this->model_);
w->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::ResizeToContents);
w->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::ResizeToContents);
w->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
w->horizontalHeader()->hide();
QObject::connect(
w, &QTableView::doubleClicked, this,
[=](const QModelIndex &index) {
connectWifi(
index.siblingAtColumn(ssidColumn).data().toString());
});
}),
}));
}));
}
| 27.683453 | 80 | 0.598493 | [
"model"
] |
ccd27fc23866b2900cc1d472a505f5e3747d17ba | 1,861 | cpp | C++ | lib/Analyses/AlgorithmLibraryAnalysis.cpp | hartogss/cxx-langstat | 397f48bac9de4e79ba6a1adea0c372119f27be32 | [
"Apache-2.0"
] | 3 | 2020-10-18T15:37:38.000Z | 2020-10-26T16:07:51.000Z | lib/Analyses/AlgorithmLibraryAnalysis.cpp | hartogss/cxx-langstat | 397f48bac9de4e79ba6a1adea0c372119f27be32 | [
"Apache-2.0"
] | 51 | 2020-11-11T10:12:16.000Z | 2021-07-05T14:25:20.000Z | lib/Analyses/AlgorithmLibraryAnalysis.cpp | hartogss/cxx-langstat | 397f48bac9de4e79ba6a1adea0c372119f27be32 | [
"Apache-2.0"
] | 1 | 2021-04-15T16:06:59.000Z | 2021-04-15T16:06:59.000Z | #include <iostream>
#include <vector>
#include "cxx-langstat/Analyses/AlgorithmLibraryAnalysis.h"
#include "cxx-langstat/Utils.h"
using namespace clang;
using namespace clang::ast_matchers;
using json = nlohmann::json;
using ordered_json = nlohmann::ordered_json;
//-----------------------------------------------------------------------------
// Construct a ALA by constructing a more constrained TIA.
AlgorithmLibraryAnalysis::AlgorithmLibraryAnalysis() : TemplateInstantiationAnalysis(
InstKind::Function,
hasAnyName(
// https://en.cppreference.com/w/cpp/algorithm
// Non-modifying sequence ooperations
"std::all_of", "std::any_of", "std::none_of",
"std::for_each", "std::for_each_n",
"std::count", "std::count_if",
"std::mismatch",
"std::find", "std::find_if", "std::find_if_not",
"std::find_end", "std::find_first_of", "std::adjacent_find",
"std::search", "std::search_n",
// Minimum/maximum operations
"std::max", "std::max_element", "std::min", "std::min_element",
"std::minmax", "std::minmax_element", "std::clamp",
// Modifying sequence operations
"std::move"
// This list of algorithms is incomplete
),
// libc++
"algorithm|"
// libstdc++
"bits/stl_algo.h|"
"bits/stl_algobase.h"
){
std::cout << "ALA ctor\n";
}
// Gathers data on how often each algorithm template was used.
void algorithmPrevalence(const ordered_json& in, ordered_json& out){
templatePrevalence(in, out);
}
void AlgorithmLibraryAnalysis::processFeatures(ordered_json j){
if(j.contains(FuncKey)){
ordered_json res;
algorithmPrevalence(j.at(FuncKey), res);
Statistics[AlgorithmPrevalenceKey] = res;
}
}
//-----------------------------------------------------------------------------
| 33.232143 | 85 | 0.599678 | [
"vector"
] |
ccd7172d676556086d7bf753770184264c90b5c3 | 1,755 | cxx | C++ | src/withrottle/ServerCommand.cxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 34 | 2015-05-23T03:57:56.000Z | 2022-03-27T03:48:48.000Z | src/withrottle/ServerCommand.cxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 214 | 2015-07-05T05:06:55.000Z | 2022-02-06T14:53:14.000Z | src/withrottle/ServerCommand.cxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 38 | 2015-08-28T05:32:07.000Z | 2021-07-06T16:47:23.000Z | /** @copyright
* Copyright (c) 2016, Stuart W Baker
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are strictly prohibited without written consent.
*
* 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 withrottle/ServerCommand.cxx
*
* This file provides the WiThrottle Server Command handler base object.
*
* @author Stuart Baker
* @date 27 December 2016
*/
#include "withrottle/ServerCommand.hxx"
#include "withrottle/Server.hxx"
namespace withrottle
{
/*
* ServerCommandBase::ServerCommandBase()
*/
ServerCommandBase::ServerCommandBase(ThrottleFlow *throttle, CommandType type)
: StateFlow<Buffer<ThrottleCommand>, QList<1>>(throttle->service())
, throttle(throttle)
{
throttle->dispatcher.register_handler(this, type, TYPE_MASK);
}
/*
* ServerCommandBase::ServerCommandBase()
*/
ServerCommandBase::~ServerCommandBase()
{
throttle->dispatcher.unregister_handler_all(this);
}
} /* namespace withrottle */
| 32.5 | 78 | 0.757265 | [
"object"
] |
ccd72496652b54197ce7dbd5b28e824b91201a5c | 5,279 | cpp | C++ | Source/GreatEscape/Private/GrabbingComponent.cpp | mvxt/escape | 1e56870f8a0adcc5319a17ff9701d547a75ae392 | [
"MIT"
] | null | null | null | Source/GreatEscape/Private/GrabbingComponent.cpp | mvxt/escape | 1e56870f8a0adcc5319a17ff9701d547a75ae392 | [
"MIT"
] | null | null | null | Source/GreatEscape/Private/GrabbingComponent.cpp | mvxt/escape | 1e56870f8a0adcc5319a17ff9701d547a75ae392 | [
"MIT"
] | null | null | null | // MIT License - Copyright (c) 2018 Michael Thanh
#include "Components/PrimitiveComponent.h"
#include "GrabbingComponent.h"
#include "Engine/World.h"
/*!
Constructor, sets basic system-level parameters for the game engine.
*/
UGrabbingComponent::UGrabbingComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame.
// You can turn these features off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
}
/*!
Called when game starts. Configures various modules and other
components
*/
void UGrabbingComponent::BeginPlay()
{
Super::BeginPlay();
// Look for attached PhysicsHandleComponent
GetPhysicsHandleComponent();
// Look for input component
BindInputActions();
}
/*!
Called every tick. See inline comments for functionality.
*/
void UGrabbingComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// TODO: Refactor, this is reused code
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
OUT PlayerViewPointLocation,
OUT PlayerViewPointRotation
);
FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;
// If a physics handle is attached, move the object we are holding.
if (PhysicsHandle->GrabbedComponent) {
PhysicsHandle->SetTargetLocation(LineTraceEnd);
}
}
/*!
Fetches the Input component to grab and release items. Binds to the
"Grab" input and calls the appropriate methods. If none is found,
exit game gracefully after printing error message to log.
@see UGrabbingComponent::Grab()
@see UGrabbingComponent::Release()
*/
void UGrabbingComponent::BindInputActions() {
InputComponent = GetOwner()->FindComponentByClass<UInputComponent>();
if (InputComponent)
{
// Input Component found
InputComponent->BindAction("Grab", IE_Pressed, this, &UGrabbingComponent::Grab);
InputComponent->BindAction("Grab", IE_Released, this, &UGrabbingComponent::Release);
}
else
{
UE_LOG(LogTemp, Error, TEXT("No InputComponent found on %s"), *GetOwner()->GetName());
FGenericPlatformMisc::RequestExit(false);
}
}
/*!
Ray-casts outward using LineTrace and returns a hit to any actor
with a PhysicsBody collision channel set.
@return FHitResult
*/
FHitResult UGrabbingComponent::GetFirstHitInReach() const
{
// Get player view point / where they are looking
// Ray-cast out forward, see what object is hit
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
OUT PlayerViewPointLocation,
OUT PlayerViewPointRotation
);
FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;
FHitResult Hit;
FCollisionQueryParams TraceParameters = FCollisionQueryParams(FName(TEXT("")), false, GetOwner());
// Ray-cast out to reach distance
GetWorld()->LineTraceSingleByObjectType(
OUT Hit,
PlayerViewPointLocation,
LineTraceEnd,
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
TraceParameters
);
return Hit;
}
/*!
Fetches the Physics Component. If no physics handle component found, exit
gracefully after printing error message to log.
@see UGrabbingComponent::Grab()
@see UGrabbingComponent::Release()
*/
void UGrabbingComponent::GetPhysicsHandleComponent() {
// Look for attached PhysicsHandleComponent
PhysicsHandle = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>();
if (PhysicsHandle)
{
// Physics Handle Component found
}
else
{
UE_LOG(LogTemp, Error, TEXT("No PhysicsHandleComponent found on %s"), *GetOwner()->GetName());
FGenericPlatformMisc::RequestExit(false);
}
}
/*!
Attempts to pick up any object the player is looking at if withing
reach.
@see UGrabbingComponent::GetFirstHitInReach()
*/
void UGrabbingComponent::Grab() {
// Raycast outward and return a hit if exists
auto Hit = GetFirstHitInReach();
// If we hit something, grab it by its ball. See following link:
// https://community.gamedev.tv/t/grabcomponent-working-but-getting-error-with-componenttograb-fix/34753
auto ActorHit = Hit.GetActor();
if (ActorHit)
{
UE_LOG(LogTemp, Warning, TEXT("Line trace hit: %s"), *(ActorHit->GetName()));
UPrimitiveComponent* ComponentToGrab = Hit.GetComponent();
PhysicsHandle->GrabComponent(
ComponentToGrab,
NAME_None,
ActorHit->GetActorLocation(),
true // Allow rotation
);
}
}
/*!
If an object is currently being grabbed, when the button is released, the
object will be released.
*/
void UGrabbingComponent::Release() {
PhysicsHandle->ReleaseComponent();
} | 32.189024 | 124 | 0.687441 | [
"object",
"vector"
] |
ccde0340ff13f17e841db6bcf04c13c1557410a6 | 690 | hpp | C++ | Plugins/Renderer/Public/Prismal/Renderer/Image.hpp | PrismalEngine/prismal-engine | 40b73594e603d82edf0052fd69ce71161f48549d | [
"MIT"
] | null | null | null | Plugins/Renderer/Public/Prismal/Renderer/Image.hpp | PrismalEngine/prismal-engine | 40b73594e603d82edf0052fd69ce71161f48549d | [
"MIT"
] | null | null | null | Plugins/Renderer/Public/Prismal/Renderer/Image.hpp | PrismalEngine/prismal-engine | 40b73594e603d82edf0052fd69ce71161f48549d | [
"MIT"
] | null | null | null | /**
* @file Image.hpp
* @author Zachary Frost
* @date Created on 2021-05-21
* @copyright See LICENSE.md at repo root
* @brief Renderer image types and utilities.
*/
#pragma once
#include <Prismal/API.hpp>
#include <Prismal/Primitive.hpp>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan.h>
namespace pr::render {
struct PR_API AllocatedImage
{
VkImage image;
VmaAllocation allocation;
u32 width;
u32 height;
VkFormat format;
void cleanup() const;
static AllocatedImage create(u32 width, u32 height, VkFormat format,
VkImageUsageFlags usage, VmaMemoryUsage memoryUsage);
};
} // namespace pr::render | 23 | 76 | 0.665217 | [
"render"
] |
ef99b918e49b0209956fb792060e382af30884d8 | 38,488 | cpp | C++ | src/ByteEngine/Render/RenderSystem.cpp | Game-Tek/Byte-Engine | 5da58971da77c3c92780437f8e3ca1a143cacd5c | [
"MIT"
] | 10 | 2020-05-05T03:21:34.000Z | 2022-01-22T23:01:22.000Z | src/ByteEngine/Render/RenderSystem.cpp | Game-Tek/Byte-Engine | 5da58971da77c3c92780437f8e3ca1a143cacd5c | [
"MIT"
] | null | null | null | src/ByteEngine/Render/RenderSystem.cpp | Game-Tek/Byte-Engine | 5da58971da77c3c92780437f8e3ca1a143cacd5c | [
"MIT"
] | 1 | 2020-09-07T03:04:48.000Z | 2020-09-07T03:04:48.000Z | #include "RenderSystem.h"
#include <GTSL/Window.h>
#include "ByteEngine/Application/Application.h"
#include "ByteEngine/Application/ThreadPool.h"
#include "ByteEngine/Application/Templates/GameApplication.h"
#include "ByteEngine/Debug/Assert.h"
#include "ByteEngine/Resources/PipelineCacheResourceManager.h"
#undef MemoryBarrier
class CameraSystem;
class RenderStaticMeshCollection;
PipelineCache RenderSystem::GetPipelineCache() const { return pipelineCaches[GTSL::Thread::ThisTreadID()]; }
void RenderSystem::CreateRayTracedMesh(const MeshHandle meshHandle)
{
auto& mesh = meshes[meshHandle()];
mesh.DerivedTypeIndex = rayTracingMeshes.Emplace();
BE_ASSERT(mesh.DerivedTypeIndex < MAX_INSTANCES_COUNT);
}
RenderSystem::MeshHandle RenderSystem::CreateMesh(Id name, uint32 customIndex)
{
auto meshIndex = meshes.Emplace(); auto& mesh = meshes[meshIndex];
mesh.CustomMeshIndex = customIndex;
return MeshHandle(meshIndex);
}
//RenderSystem::MeshHandle RenderSystem::CreateMesh(Id name, uint32 customIndex, uint32 vertexCount, uint32 vertexSize, const uint32 indexCount, const uint32 indexSize, MaterialInstanceHandle materialHandle)
//{
// auto meshIndex = meshes.Emplace(); auto& mesh = meshes[meshIndex];
// mesh.CustomMeshIndex = customIndex;
// mesh.MaterialHandle = materialHandle;
//
// auto meshHandle = MeshHandle(meshIndex);
//
// UpdateMesh(meshHandle, vertexCount, vertexSize, indexCount, indexSize);
// return meshHandle;
//}
void RenderSystem::UpdateRayTraceMesh(const MeshHandle meshHandle)
{
auto& mesh = meshes[meshHandle()]; auto& rayTracingMesh = rayTracingMeshes[mesh.CustomMeshIndex];
auto& buffer = buffers[mesh.Buffer()];
GAL::DeviceAddress meshDataAddress;
meshDataAddress = GetBufferDeviceAddress(mesh.Buffer);
uint32 scratchSize;
{
GAL::GeometryTriangles geometryTriangles;
geometryTriangles.IndexType = GAL::SizeToIndexType(mesh.IndexSize);
geometryTriangles.VertexPositionFormat = GAL::ShaderDataType::FLOAT3;
geometryTriangles.MaxVertices = mesh.VertexCount;
geometryTriangles.VertexData = meshDataAddress;
geometryTriangles.IndexData = meshDataAddress + GTSL::Math::RoundUpByPowerOf2(mesh.VertexCount * mesh.VertexSize, GetBufferSubDataAlignment());
geometryTriangles.VertexStride = mesh.VertexSize;
geometryTriangles.FirstVertex = 0;
GAL::Geometry geometry(geometryTriangles, GAL::GeometryFlags::OPAQUE, mesh.IndicesCount / 3, 0);
AllocateAccelerationStructureMemory(&rayTracingMesh.AccelerationStructure, &rayTracingMesh.StructureBuffer,
GTSL::Range<const GAL::Geometry*>(1, &geometry), &rayTracingMesh.StructureBufferAllocation, &scratchSize);
AccelerationStructureBuildData buildData;
buildData.ScratchBuildSize = scratchSize;
buildData.Destination = rayTracingMesh.AccelerationStructure;
addRayTracingInstance(geometry, buildData);
}
for (uint8 f = 0; f < pipelinedFrames; ++f) {
GAL::WriteInstance(rayTracingMesh.AccelerationStructure, mesh.CustomMeshIndex, GAL::GeometryFlags::OPAQUE, GetRenderDevice(), instancesAllocation[f].Data, mesh.DerivedTypeIndex, accelerationStructureBuildDevice);
GAL::WriteInstanceBindingTableRecordOffset(0, instancesAllocation[f].Data, mesh.DerivedTypeIndex);
}
}
void RenderSystem::UpdateMesh(MeshHandle meshHandle, uint32 vertexCount, uint32 vertexSize, const uint32 indexCount, const uint32 indexSize, GTSL::Range<const GAL::ShaderDataType*> vertexLayout)
{
auto& mesh = meshes[meshHandle()];
mesh.VertexSize = vertexSize; mesh.VertexCount = vertexCount; mesh.IndexSize = indexSize; mesh.IndicesCount = indexCount;
auto verticesSize = vertexCount * vertexSize; auto indecesSize = indexCount * indexSize;
auto meshSize = GTSL::Math::RoundUpByPowerOf2(verticesSize, GetBufferSubDataAlignment()) + indecesSize;
mesh.VertexDescriptor.PushBack(vertexLayout);
mesh.Buffer = CreateBuffer(meshSize, GAL::BufferUses::VERTEX | GAL::BufferUses::INDEX, true, false);
}
void RenderSystem::UpdateMesh(MeshHandle meshHandle)
{
auto& mesh = meshes[meshHandle()];
auto verticesSize = mesh.VertexSize * mesh.VertexCount; auto indecesSize = mesh.IndexSize * mesh.IndicesCount;
auto meshSize = GTSL::Math::RoundUpByPowerOf2(verticesSize, GetBufferSubDataAlignment()) + indecesSize;
++buffers[mesh.Buffer()].references;
BufferCopyData bufferCopyData;
bufferCopyData.Buffer = mesh.Buffer;
bufferCopyData.Offset = 0;
AddBufferUpdate(bufferCopyData);
}
void RenderSystem::RenderMesh(MeshHandle handle, const uint32 instanceCount)
{
auto& mesh = meshes[handle()];
auto& buffer = buffers[mesh.Buffer()];
//todo: is multi
graphicsCommandBuffers[GetCurrentFrame()].BindVertexBuffer(GetRenderDevice(), buffer.Buffer[0], mesh.VertexSize * mesh.VertexCount, 0, mesh.VertexSize);
graphicsCommandBuffers[GetCurrentFrame()].BindIndexBuffer(GetRenderDevice(), buffer.Buffer[0], mesh.IndexSize * mesh.IndicesCount, GTSL::Math::RoundUpByPowerOf2(mesh.VertexSize * mesh.VertexCount, GetBufferSubDataAlignment()), GAL::SizeToIndexType(mesh.IndexSize));
graphicsCommandBuffers[GetCurrentFrame()].DrawIndexed(GetRenderDevice(), mesh.IndicesCount, instanceCount);
}
void RenderSystem::SetMeshMatrix(const MeshHandle meshHandle, const GTSL::Matrix3x4& matrix)
{
const auto& mesh = meshes[meshHandle()];
GAL::WriteInstanceMatrix(matrix, instancesAllocation[GetCurrentFrame()].Data, mesh.DerivedTypeIndex);
}
void RenderSystem::SetMeshOffset(const MeshHandle meshHandle, const uint32 offset)
{
const auto& mesh = meshes[meshHandle()];
GAL::WriteInstanceBindingTableRecordOffset(offset, instancesAllocation[GetCurrentFrame()].Data, mesh.DerivedTypeIndex);
}
RenderSystem::RenderSystem(const InitializeInfo& initializeInfo) : System(initializeInfo, u8"RenderSystem"),
bufferCopyDatas{ { 16, GetPersistentAllocator() }, { 16, GetPersistentAllocator() }, { 16, GetPersistentAllocator() } },
textureCopyDatas{ { 16, GetPersistentAllocator() }, { 16, GetPersistentAllocator() }, { 16, GetPersistentAllocator() } }, meshes(16, GetPersistentAllocator()),
rayTracingMeshes(GetPersistentAllocator()), buffers(32, GetPersistentAllocator()),
buildDatas{ GetPersistentAllocator(), GetPersistentAllocator(), GetPersistentAllocator() }, geometries{ GetPersistentAllocator(), GetPersistentAllocator(), GetPersistentAllocator() }, pipelineCaches(16, decltype(pipelineCaches)::allocator_t()),
textures(16, GetPersistentAllocator())
{
//{
// GTSL::StaticVector<TaskDependency, 1> dependencies{ { "RenderSystem", AccessTypes::READ_WRITE } };
//
// auto renderEnableHandle = initializeInfo.ApplicationManager->StoreDynamicTask("RS::OnRenderEnable", Task<bool>::Create<RenderSystem, &RenderSystem::OnRenderEnable>(this), dependencies);
// initializeInfo.ApplicationManager->SubscribeToEvent("Application", GameApplication::GetOnFocusGainEventHandle(), renderEnableHandle);
//
// auto renderDisableHandle = initializeInfo.ApplicationManager->StoreDynamicTask("RS::OnRenderDisable", Task<bool>::Create<RenderSystem, &RenderSystem::OnRenderDisable>(this), dependencies);
// initializeInfo.ApplicationManager->SubscribeToEvent("Application", GameApplication::GetOnFocusGainEventHandle(), renderDisableHandle);
//}
{
const GTSL::StaticVector<TaskDependency, 8> actsOn{ { u8"RenderSystem", AccessTypes::READ_WRITE } };
initializeInfo.GameInstance->AddTask(u8"RenderSystem::frameStart", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::frameStart>(this), actsOn, u8"FrameStart", u8"RenderStart");
//initializeInfo.ApplicationManager->AddTask(u8"RenderSystem::executeTransfers", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::executeTransfers>(this), actsOn, u8"GameplayEnd", u8"RenderStart");
//initializeInfo.ApplicationManager->AddTask(u8"RenderSystem::waitForFences", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::waitForFences>(this), actsOn, u8"RenderStart", u8"RenderStartSetup");
initializeInfo.GameInstance->AddTask(u8"RenderSystem::beginCommandLists", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::beginGraphicsCommandLists>(this), actsOn, u8"RenderEndSetup", u8"RenderDo");
initializeInfo.GameInstance->AddTask(u8"RenderSystem::endCommandLists", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::renderFlush>(this), actsOn, u8"RenderFinished", u8"RenderEnd");
}
//apiAllocations.Initialize(128, GetPersistentAllocator());
apiAllocations.reserve(16);
RenderDevice::RayTracingCapabilities rayTracingCapabilities;
useHDR = BE::Application::Get()->GetOption(u8"hdr");
pipelinedFrames = static_cast<uint8>(GTSL::Math::Clamp(BE::Application::Get()->GetOption(u8"buffer"), 2u, 3u));
bool rayTracing = BE::Application::Get()->GetOption(u8"rayTracing");
{
RenderDevice::CreateInfo createInfo;
createInfo.ApplicationName = GTSL::StaticString<128>(BE::Application::Get()->GetApplicationName());
createInfo.ApplicationVersion[0] = 0; createInfo.ApplicationVersion[1] = 0; createInfo.ApplicationVersion[2] = 0;
createInfo.Debug = BE::Application::Get()->GetOption(u8"debug");
GTSL::StaticVector<GAL::QueueType, 5> queue_create_infos;
GTSL::StaticVector<RenderDevice::QueueKey, 5> queueKeys;
queue_create_infos.EmplaceBack(GAL::QueueTypes::GRAPHICS); queueKeys.EmplaceBack();
//queue_create_infos.EmplaceBack(GAL::QueueTypes::TRANSFER); queueKeys.EmplaceBack();
createInfo.Queues = queue_create_infos;
createInfo.QueueKeys = queueKeys;
GTSL::StaticVector<GTSL::Pair<RenderDevice::Extension, void*>, 8> extensions{ { RenderDevice::Extension::PIPELINE_CACHE_EXTERNAL_SYNC, nullptr } };
extensions.EmplaceBack(RenderDevice::Extension::SWAPCHAIN_RENDERING, nullptr);
extensions.EmplaceBack(RenderDevice::Extension::SCALAR_LAYOUT, nullptr);
if (rayTracing) { extensions.EmplaceBack(RenderDevice::Extension::RAY_TRACING, &rayTracingCapabilities); }
createInfo.Extensions = extensions;
createInfo.PerformanceValidation = true;
createInfo.SynchronizationValidation = true;
createInfo.DebugPrintFunction = GTSL::Delegate<void(const char*, RenderDevice::MessageSeverity)>::Create<RenderSystem, &RenderSystem::printError>(this);
createInfo.AllocationInfo.UserData = this;
createInfo.AllocationInfo.Allocate = GTSL::Delegate<void* (void*, uint64, uint64)>::Create<RenderSystem, &RenderSystem::allocateApiMemory>(this);
createInfo.AllocationInfo.Reallocate = GTSL::Delegate<void* (void*, void*, uint64, uint64)>::Create<RenderSystem, &RenderSystem::reallocateApiMemory>(this);
createInfo.AllocationInfo.Deallocate = GTSL::Delegate<void(void*, void*)>::Create<RenderSystem, &RenderSystem::deallocateApiMemory>(this);
renderDevice.Initialize(createInfo);
BE_LOG_MESSAGE("Started Vulkan API\n GPU: ", renderDevice.GetGPUInfo().GPUName);
graphicsQueue.Initialize(GetRenderDevice(), queueKeys[0]);
//transferQueue.Initialize(GetRenderDevice(), queueKeys[1]);
{
needsStagingBuffer = true;
auto memoryHeaps = renderDevice.GetMemoryHeaps(); GAL::VulkanRenderDevice::MemoryHeap& biggestGPUHeap = memoryHeaps[0];
for (auto& e : memoryHeaps)
{
if (e.HeapType & GAL::MemoryTypes::GPU) {
if (e.Size > biggestGPUHeap.Size) {
biggestGPUHeap = e;
for (auto& mt : e.MemoryTypes) {
if (mt & GAL::MemoryTypes::GPU && mt & GAL::MemoryTypes::HOST_COHERENT && mt & GAL::MemoryTypes::HOST_VISIBLE) {
needsStagingBuffer = false; break;
}
}
}
}
}
}
scratchMemoryAllocator.Initialize(renderDevice, GetPersistentAllocator());
localMemoryAllocator.Initialize(renderDevice, GetPersistentAllocator());
if (rayTracing) {
GAL::Geometry geometry(GAL::GeometryInstances(), GAL::GeometryFlag(), MAX_INSTANCES_COUNT, 0);
for (uint8 f = 0; f < pipelinedFrames; ++f) {
AllocateAccelerationStructureMemory(&topLevelAccelerationStructure[f], &topLevelAccelerationStructureBuffer[f],
GTSL::Range<const GAL::Geometry*>(1, &geometry), &topLevelAccelerationStructureAllocation[f],
&topLevelStructureScratchSize);
AllocateScratchBufferMemory(MAX_INSTANCES_COUNT * GetRenderDevice()->GetAccelerationStructureInstanceSize(), GAL::BufferUses::ADDRESS | GAL::BufferUses::BUILD_INPUT_READ, &instancesBuffer[f], &instancesAllocation[f]);
AllocateLocalBufferMemory(GTSL::Byte(GTSL::MegaByte(1)), GAL::BufferUses::ADDRESS | GAL::BufferUses::BUILD_INPUT_READ, &accelerationStructureScratchBuffer[f], &scratchBufferAllocation[f]);
}
shaderGroupHandleAlignment = rayTracingCapabilities.ShaderGroupHandleAlignment;
shaderGroupHandleSize = rayTracingCapabilities.ShaderGroupHandleSize;
scratchBufferOffsetAlignment = rayTracingCapabilities.ScratchBuildOffsetAlignment;
shaderGroupBaseAlignment = rayTracingCapabilities.ShaderGroupBaseAlignment;
accelerationStructureBuildDevice = rayTracingCapabilities.BuildDevice;
switch (rayTracingCapabilities.BuildDevice) {
case GAL::Device::CPU: break;
case GAL::Device::GPU:
case GAL::Device::GPU_OR_CPU:
buildAccelerationStructures = decltype(buildAccelerationStructures)::Create<RenderSystem, &RenderSystem::buildAccelerationStructuresOnDevice>();
break;
default:;
}
}
}
swapchainPresentMode = GAL::PresentModes::SWAP;
swapchainColorSpace = GAL::ColorSpace::SRGB_NONLINEAR;
swapchainFormat = GAL::FORMATS::BGRA_I8;
for (uint32 i = 0; i < pipelinedFrames; ++i) {
if constexpr (_DEBUG) { GTSL::StaticString<32> name(u8"Transfer semaphore. Frame: "); name += i; }
//transferDoneSemaphores[i].Initialize(GetRenderDevice());
//processedTextureCopies.EmplaceBack(0);
processedBufferCopies[i] = 0;
if constexpr (_DEBUG) {
//GTSL::StaticString<32> name("ImageAvailableSemaphore #"); name += i;
}
imageAvailableSemaphore[i].Initialize(GetRenderDevice());
if constexpr (_DEBUG) {
GTSL::StaticString<32> name(u8"RenderFinishedSemaphore #"); name += i;
}
renderFinishedSemaphore[i].Initialize(GetRenderDevice());
if constexpr (_DEBUG) {
GTSL::StaticString<32> name(u8"InFlightFence #"); name += i;
}
graphicsFences[i].Initialize(GetRenderDevice(), true);
if constexpr (_DEBUG) {
GTSL::StaticString<32> name(u8"TrasferFence #"); name += i;
}
//transferFences[i].Initialize(GetRenderDevice(), true);
if constexpr (_DEBUG) {
GTSL::StaticString<64> commandPoolName(u8"Transfer command pool #"); commandPoolName += i;
//commandPoolCreateInfo.Name = commandPoolName;
}
graphicsCommandBuffers[i].Initialize(GetRenderDevice(), graphicsQueue.GetQueueKey());
if constexpr (_DEBUG) {
GTSL::StaticString<64> commandPoolName(u8"Transfer command pool #"); commandPoolName += i;
//commandPoolCreateInfo.Name = commandPoolName;
}
//transferCommandBuffers[i].Initialize(GetRenderDevice(), transferQueue.GetQueueKey());
}
bool pipelineCacheAvailable;
auto* pipelineCacheManager = BE::Application::Get()->GetResourceManager<PipelineCacheResourceManager>(u8"PipelineCacheResourceManager");
pipelineCacheManager->DoesCacheExist(pipelineCacheAvailable);
if (pipelineCacheAvailable) {
uint32 cacheSize = 0;
pipelineCacheManager->GetCacheSize(cacheSize);
GTSL::Buffer pipelineCacheBuffer(cacheSize, 32, GetTransientAllocator());
pipelineCacheManager->GetCache(pipelineCacheBuffer);
for (uint8 i = 0; i < BE::Application::Get()->GetNumberOfThreads(); ++i) {
if constexpr (_DEBUG) {
GTSL::StaticString<32> name(u8"Pipeline cache. Thread: "); name += i;
}
pipelineCaches.EmplaceBack().Initialize(GetRenderDevice(), true, static_cast<GTSL::Range<const GTSL::byte*>>(pipelineCacheBuffer));
}
}
else {
for (uint8 i = 0; i < BE::Application::Get()->GetNumberOfThreads(); ++i)
{
if constexpr (_DEBUG) {
GTSL::StaticString<32> name(u8"Pipeline cache. Thread: "); name += i;
}
pipelineCaches.EmplaceBack().Initialize(GetRenderDevice(), true, {});
}
}
BE_LOG_MESSAGE("Initialized successfully");
}
void RenderSystem::Shutdown(const ShutdownInfo& shutdownInfo)
{
//graphicsQueue.Wait(GetRenderDevice()); transferQueue.Wait(GetRenderDevice());
renderDevice.Wait();
for (uint32 i = 0; i < pipelinedFrames; ++i) {
graphicsCommandBuffers[i].Destroy(&renderDevice);
//transferCommandBuffers[i].Destroy(&renderDevice);
}
if(renderContext.GetHandle())
renderContext.Destroy(&renderDevice);
if(surface.GetHandle())
surface.Destroy(&renderDevice);
//DeallocateLocalTextureMemory();
for(auto& e : imageAvailableSemaphore) { e.Destroy(&renderDevice); }
for(auto& e : renderFinishedSemaphore) { e.Destroy(&renderDevice); }
for(auto& e : graphicsFences) { e.Destroy(&renderDevice); }
//for(auto& e : transferFences) { e.Destroy(&renderDevice); }
for (auto& e : swapchainTextureViews) {
if (e.GetVkImageView())
e.Destroy(&renderDevice);
}
scratchMemoryAllocator.Free(renderDevice, GetPersistentAllocator());
localMemoryAllocator.Free(renderDevice, GetPersistentAllocator());
{
uint32 cacheSize = 0; PipelineCache pipelineCache;
pipelineCache.Initialize(GetRenderDevice(), pipelineCaches);
pipelineCache.GetCacheSize(GetRenderDevice(), cacheSize);
if (cacheSize) {
auto* pipelineCacheResourceManager = BE::Application::Get()->GetResourceManager<PipelineCacheResourceManager>(u8"PipelineCacheResourceManager");
GTSL::Buffer pipelineCacheBuffer(cacheSize, 32, GetTransientAllocator());
pipelineCache.GetCache(&renderDevice, pipelineCacheBuffer);
pipelineCacheResourceManager->WriteCache(pipelineCacheBuffer);
}
}
}
void RenderSystem::buildAccelerationStructuresOnDevice(CommandList& commandBuffer)
{
if (buildDatas[GetCurrentFrame()].GetLength()) {
GTSL::StaticVector<GAL::BuildAccelerationStructureInfo, 8> accelerationStructureBuildInfos;
GTSL::StaticVector<GTSL::StaticVector<GAL::Geometry, 8>, 16> geometryDescriptors;
uint32 offset = 0; auto scratchBufferAddress = accelerationStructureScratchBuffer[GetCurrentFrame()].GetAddress(GetRenderDevice());
for (uint32 i = 0; i < buildDatas[GetCurrentFrame()].GetLength(); ++i) {
geometryDescriptors.EmplaceBack();
geometryDescriptors[i].EmplaceBack(geometries[GetCurrentFrame()][i]);
GAL::BuildAccelerationStructureInfo buildAccelerationStructureInfo;
buildAccelerationStructureInfo.ScratchBufferAddress = scratchBufferAddress + offset; //TODO: ENSURE CURRENT BUILDS SCRATCH BUFFER AREN'T OVERWRITTEN ON TURN OF FRAME
buildAccelerationStructureInfo.SourceAccelerationStructure = AccelerationStructure();
buildAccelerationStructureInfo.DestinationAccelerationStructure = buildDatas[GetCurrentFrame()][i].Destination;
buildAccelerationStructureInfo.Geometries = geometryDescriptors[i];
buildAccelerationStructureInfo.Flags = buildDatas[GetCurrentFrame()][i].BuildFlags;
accelerationStructureBuildInfos.EmplaceBack(buildAccelerationStructureInfo);
offset += GTSL::Math::RoundUpByPowerOf2(buildDatas[GetCurrentFrame()][i].ScratchBuildSize, scratchBufferOffsetAlignment);
}
commandBuffer.BuildAccelerationStructure(GetRenderDevice(), accelerationStructureBuildInfos, GetTransientAllocator());
GTSL::StaticVector<CommandList::BarrierData, 1> barriers;
barriers.EmplaceBack(CommandList::MemoryBarrier{ GAL::AccessTypes::WRITE, GAL::AccessTypes::READ });
commandBuffer.AddPipelineBarrier(GetRenderDevice(), barriers, GAL::PipelineStages::ACCELERATION_STRUCTURE_BUILD, GAL::PipelineStages::ACCELERATION_STRUCTURE_BUILD, GetTransientAllocator());
}
buildDatas[GetCurrentFrame()].Resize(0);
geometries[GetCurrentFrame()].Resize(0);
}
bool RenderSystem::resize()
{
if (renderArea == 0) { return false; }
//graphicsQueue.Wait(GetRenderDevice());
if (!surface.GetHandle()) {
surface.Initialize(GetRenderDevice(), BE::Application::Get()->GetApplication(), *window);
}
Surface::SurfaceCapabilities surfaceCapabilities;
auto isSupported = surface.IsSupported(&renderDevice, &surfaceCapabilities);
renderArea = surfaceCapabilities.CurrentExtent;
if (!isSupported) {
BE::Application::Get()->Close(BE::Application::CloseMode::ERROR, GTSL::StaticString<64>(u8"No supported surface found!"));
}
auto supportedPresentModes = surface.GetSupportedPresentModes(&renderDevice);
swapchainPresentMode = supportedPresentModes[0];
auto supportedSurfaceFormats = surface.GetSupportedFormatsAndColorSpaces(&renderDevice);
{
GTSL::Pair<GAL::ColorSpace, GAL::FormatDescriptor> bestColorSpaceFormat;
for (uint8 topScore = 0; const auto& e : supportedSurfaceFormats) {
uint8 score = 0;
if (useHDR && e.First == GAL::ColorSpace::HDR10_ST2048) {
score += 2;
} else {
score += 1;
}
if(score > topScore) {
bestColorSpaceFormat = e;
topScore = score;
}
}
swapchainColorSpace = bestColorSpaceFormat.First; swapchainFormat = bestColorSpaceFormat.Second;
}
renderContext.InitializeOrRecreate(GetRenderDevice(), graphicsQueue, &surface, renderArea, swapchainFormat, swapchainColorSpace, GAL::TextureUses::STORAGE | GAL::TextureUses::TRANSFER_DESTINATION, swapchainPresentMode, pipelinedFrames);
for (auto& e : swapchainTextureViews) { e.Destroy(&renderDevice); }
//imageIndex = 0;
{
auto newSwapchainTextures = renderContext.GetTextures(GetRenderDevice());
for (uint8 f = 0; f < pipelinedFrames; ++f) {
swapchainTextures[f] = newSwapchainTextures[f];
swapchainTextureViews[f].Destroy(GetRenderDevice());
GTSL::StaticString<64> name(u8"Swapchain ImageView "); name += f;
swapchainTextureViews[f].Initialize(GetRenderDevice(), name, swapchainTextures[f], swapchainFormat, renderArea, 1);
}
}
lastRenderArea = renderArea;
return true;
}
void RenderSystem::beginGraphicsCommandLists(TaskInfo taskInfo)
{
auto& commandBuffer = graphicsCommandBuffers[GetCurrentFrame()];
graphicsFences[GetCurrentFrame()].Wait(GetRenderDevice());
graphicsFences[GetCurrentFrame()].Reset(GetRenderDevice());
commandBuffer.BeginRecording(GetRenderDevice());
if (BE::Application::Get()->GetOption(u8"rayTracing")) {
GAL::Geometry geometry(GAL::GeometryInstances{ instancesBuffer[GetCurrentFrame()].GetAddress(GetRenderDevice()) }, GAL::GeometryFlag(), rayTracingInstancesCount, 0);
//TODO: WHAT HAPPENS IF MESH IS REMOVED FROM THE MIDDLE OF THE COLLECTION, maybe: keep index of highest element in the colection
geometries[GetCurrentFrame()].EmplaceBack(geometry);
AccelerationStructureBuildData buildData;
buildData.BuildFlags = 0;
buildData.Destination = topLevelAccelerationStructure[GetCurrentFrame()];
buildData.ScratchBuildSize = topLevelStructureScratchSize;
buildDatas[GetCurrentFrame()].EmplaceBack(buildData);
buildAccelerationStructures(this, commandBuffer);
}
{
auto& bufferCopyData = bufferCopyDatas[GetCurrentFrame()];
for (auto& e : bufferCopyData) {
auto& buffer = buffers[e.Buffer()];
if (buffer.isMulti) {
__debugbreak();
} else {
commandBuffer.CopyBuffer(GetRenderDevice(), buffer.Staging[0], e.Offset, buffer.Buffer[0], 0, buffer.Size); //TODO: offset
--buffer.references;
}
}
processedBufferCopies[GetCurrentFrame()] = bufferCopyData.GetLength();
}
if (auto& textureCopyData = textureCopyDatas[GetCurrentFrame()]; textureCopyData.GetLength())
{
GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> sourceTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator());
GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> destinationTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator());
for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) {
sourceTextureBarriers.EmplaceBack(CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::UNDEFINED, GAL::TextureLayout::TRANSFER_DESTINATION, GAL::AccessTypes::READ, GAL::AccessTypes::WRITE, textureCopyData[i].Format });
destinationTextureBarriers.EmplaceBack(CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, GAL::TextureLayout::SHADER_READ, GAL::AccessTypes::WRITE, GAL::AccessTypes::READ, textureCopyData[i].Format });
}
commandBuffer.AddPipelineBarrier(GetRenderDevice(), sourceTextureBarriers, GAL::PipelineStages::TRANSFER, GAL::PipelineStages::TRANSFER, GetTransientAllocator());
for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) {
commandBuffer.CopyBufferToTexture(GetRenderDevice(), textureCopyData[i].SourceBuffer, textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, textureCopyData[i].Format, textureCopyData[i].Extent);
}
commandBuffer.AddPipelineBarrier(GetRenderDevice(), destinationTextureBarriers, GAL::PipelineStages::TRANSFER, GAL::PipelineStages::FRAGMENT, GetTransientAllocator());
textureCopyDatas[GetCurrentFrame()].Resize(0);
}
}
void RenderSystem::renderFlush(TaskInfo taskInfo)
{
auto& commandBuffer = graphicsCommandBuffers[GetCurrentFrame()];
auto beforeFrame = uint8(currentFrameIndex - uint8(1)) % GetPipelinedFrames();
for(auto& e : buffers) {
if (e.isMulti) {
if (e.writeMask[beforeFrame] && !e.writeMask[GetCurrentFrame()]) {
GTSL::MemCopy(e.Size, e.StagingAllocation[beforeFrame].Data, e.StagingAllocation[GetCurrentFrame()].Data);
}
}
e.writeMask[GetCurrentFrame()] = false;
}
commandBuffer.EndRecording(GetRenderDevice());
{
GTSL::StaticVector<Queue::WorkUnit, 8> workUnits;
auto& graphicsWork = workUnits.EmplaceBack();
graphicsWork.WaitSemaphore = &imageAvailableSemaphore[GetCurrentFrame()];
graphicsWork.WaitPipelineStage = GAL::PipelineStages::TRANSFER;
graphicsWork.SignalSemaphore = &renderFinishedSemaphore[GetCurrentFrame()];
graphicsWork.CommandBuffer = &graphicsCommandBuffers[GetCurrentFrame()];
if (surface.GetHandle())
{
graphicsWork.WaitPipelineStage |= GAL::PipelineStages::COLOR_ATTACHMENT_OUTPUT;
}
graphicsQueue.Submit(GetRenderDevice(), workUnits, graphicsFences[GetCurrentFrame()]);
GTSL::StaticVector<GPUSemaphore*, 8> presentWaitSemaphores;
if(surface.GetHandle()) {
presentWaitSemaphores.EmplaceBack(&renderFinishedSemaphore[GetCurrentFrame()]);
renderContext.Present(GetRenderDevice(), presentWaitSemaphores, imageIndex, graphicsQueue);
}
}
currentFrameIndex = (currentFrameIndex + 1) % pipelinedFrames;
}
void RenderSystem::frameStart(TaskInfo taskInfo)
{
auto& bufferCopyData = bufferCopyDatas[GetCurrentFrame()];
auto& textureCopyData = textureCopyDatas[GetCurrentFrame()];
}
void RenderSystem::executeTransfers(TaskInfo taskInfo)
{
//auto& commandBuffer = transferCommandBuffers[GetCurrentFrame()];
//auto& commandBuffer = graphicsCommandBuffers[GetCurrentFrame()];
//commandBuffer.BeginRecording(GetRenderDevice());
//{
// auto& bufferCopyData = bufferCopyDatas[GetCurrentFrame()];
//
// for (auto& e : bufferCopyData) //TODO: What to do with multibuffers.
// {
// auto& buffer = buffers[e.Buffer()]; auto& stagingBuffer = buffers[buffer.Staging()];
//
// commandBuffer.CopyBuffer(GetRenderDevice(), stagingBuffer.Buffer, e.Offset, buffer.Buffer, 0, buffer.Size); //TODO: offset
// --stagingBuffer.references;
// }
//
// processedBufferCopies[GetCurrentFrame()] = bufferCopyData.GetLength();
//}
//
//if (auto & textureCopyData = textureCopyDatas[GetCurrentFrame()]; textureCopyData.GetLength())
//{
// GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> sourceTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator());
// GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> destinationTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator());
//
// for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) {
// sourceTextureBarriers.EmplaceBack(CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::UNDEFINED, GAL::TextureLayout::TRANSFER_DESTINATION, GAL::AccessTypes::READ, GAL::AccessTypes::WRITE, textureCopyData[i].Format });
// destinationTextureBarriers.EmplaceBack(CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, GAL::TextureLayout::SHADER_READ, GAL::AccessTypes::WRITE, GAL::AccessTypes::READ, textureCopyData[i].Format });
// }
//
// commandBuffer.AddPipelineBarrier(GetRenderDevice(), sourceTextureBarriers, GAL::PipelineStages::TRANSFER, GAL::PipelineStages::TRANSFER, GetTransientAllocator());
//
// for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) {
// commandBuffer.CopyBufferToTexture(GetRenderDevice(), textureCopyData[i].SourceBuffer, textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, textureCopyData[i].Format, textureCopyData[i].Extent);
// }
//
// commandBuffer.AddPipelineBarrier(GetRenderDevice(), destinationTextureBarriers, GAL::PipelineStages::TRANSFER, GAL::PipelineStages::FRAGMENT, GetTransientAllocator());
// textureCopyDatas[GetCurrentFrame()].Resize(0);
//}
//processedTextureCopies[GetCurrentFrame()] = textureCopyData.GetLength();
//commandBuffer.EndRecording(GetRenderDevice());
////if (bufferCopyDatas[currentFrameIndex].GetLength() || textureCopyDatas[GetCurrentFrame()].GetLength())
////{
// GTSL::StaticVector<GAL::Queue::WorkUnit, 8> workUnits;
// auto& workUnit = workUnits.EmplaceBack();
// workUnit.CommandBuffer = &commandBuffer;
// workUnit.WaitPipelineStage = GAL::PipelineStages::TRANSFER;
// workUnit.SignalSemaphore = &transferDoneSemaphores[GetCurrentFrame()];
//
// graphicsQueue.Submit(GetRenderDevice(), workUnits, transferFences[currentFrameIndex]);
////}
}
RenderSystem::TextureHandle RenderSystem::CreateTexture(GTSL::Range<const char8_t*> name, GAL::FormatDescriptor formatDescriptor, GTSL::Extent3D extent, GAL::TextureUse textureUses, bool updatable)
{
//RenderDevice::FindSupportedImageFormat findFormat;
//findFormat.TextureTiling = TextureTiling::OPTIMAL;
//findFormat.TextureUses = TextureUses::TRANSFER_DESTINATION | TextureUses::SAMPLE;
//GTSL::StaticVector<TextureFormat, 16> candidates; candidates.EmplaceBack(ConvertFormat(textureInfo.Format)); candidates.EmplaceBack(TextureFormat::RGBA_I8);
//findFormat.Candidates = candidates;
//auto supportedFormat = renderSystem->GetRenderDevice()->FindNearestSupportedImageFormat(findFormat);
//GAL::Texture::ConvertTextureFormat(textureInfo.Format, GAL::TextureFormat::RGBA_I8, textureInfo.Extent, GTSL::AlignedPointer<byte, 16>(buffer.begin()), 1);
static uint32 index = 0;
TextureComponent textureComponent;
textureComponent.Extent = extent;
textureComponent.FormatDescriptor = formatDescriptor;
textureComponent.Uses = textureUses;
if (updatable) { textureComponent.Uses |= GAL::TextureUses::TRANSFER_DESTINATION; }
textureComponent.Layout = GAL::TextureLayout::UNDEFINED;
const auto textureSize = extent.Width * extent.Height * extent.Depth * formatDescriptor.GetSize();
if (updatable && needsStagingBuffer) {
AllocateScratchBufferMemory(textureSize, GAL::BufferUses::TRANSFER_SOURCE, &textureComponent.ScratchBuffer, &textureComponent.ScratchAllocation);
}
AllocateLocalTextureMemory(&textureComponent.Texture, textureComponent.Uses, textureComponent.FormatDescriptor, extent, GAL::Tiling::OPTIMAL,
1, &textureComponent.Allocation);
textureComponent.TextureView.Initialize(GetRenderDevice(), name, textureComponent.Texture, textureComponent.FormatDescriptor, extent, 1);
textureComponent.TextureSampler.Initialize(GetRenderDevice(), 0);
auto textureIndex = textures.Emplace(textureComponent);
return TextureHandle(textureIndex);
}
void RenderSystem::UpdateTexture(const TextureHandle textureHandle)
{
const auto& texture = textures[textureHandle()];
TextureCopyData textureCopyData;
textureCopyData.Layout = texture.Layout;
textureCopyData.Extent = texture.Extent;
textureCopyData.Allocation = texture.Allocation;
textureCopyData.DestinationTexture = texture.Texture;
textureCopyData.SourceOffset = 0;
textureCopyData.SourceBuffer = texture.ScratchBuffer;
textureCopyData.Format = texture.FormatDescriptor;
AddTextureCopy(textureCopyData);
//TODO: QUEUE BUFFER DELETION
}
void RenderSystem::OnRenderEnable(TaskInfo taskInfo, bool oldFocus)
{
if(!oldFocus)
{
//const GTSL::StaticVector<TaskDependency, 8> actsOn{ { u8"RenderSystem", AccessTypes::READ_WRITE } };
//taskInfo.ApplicationManager->AddTask(u8"frameStart", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::frameStart>(this), actsOn, u8"FrameStart", u8"RenderStart");
//taskInfo.ApplicationManager->AddTask(u8"executeTransfers", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::executeTransfers>(this), actsOn, u8"GameplayEnd", u8"RenderStart");
//taskInfo.ApplicationManager->AddTask(u8"renderSetup", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::beginGraphicsCommandLists>(this), actsOn, u8"RenderEndSetup", u8"RenderDo");
//taskInfo.ApplicationManager->AddTask(u8"renderFinished", GTSL::Delegate<void(TaskInfo)>::Create<RenderSystem, &RenderSystem::renderFlush>(this), actsOn, u8"RenderFinished", u8"RenderEnd");
BE_LOG_SUCCESS("Enabled rendering")
}
OnResize(window->GetFramebufferExtent());
}
void RenderSystem::OnRenderDisable(TaskInfo taskInfo, bool oldFocus)
{
if (oldFocus)
{
//taskInfo.ApplicationManager->RemoveTask(u8"frameStart", u8"FrameStart");
//taskInfo.ApplicationManager->RemoveTask(u8"executeTransfers", u8"GameplayEnd");
//taskInfo.ApplicationManager->RemoveTask(u8"waitForFences", u8"RenderStart");
//taskInfo.ApplicationManager->RemoveTask(u8"renderSetup", u8"RenderEndSetup");
//taskInfo.ApplicationManager->RemoveTask(u8"renderFinished", u8"RenderFinished");
BE_LOG_SUCCESS("Disabled rendering")
}
}
bool RenderSystem::AcquireImage()
{
bool result = false;
if(surface.GetHandle()) {
auto acquireResult = renderContext.AcquireNextImage(&renderDevice, imageAvailableSemaphore[GetCurrentFrame()]);
imageIndex = acquireResult.Get();
switch (acquireResult.State())
{
case GAL::VulkanRenderContext::AcquireState::OK: break;
case GAL::VulkanRenderContext::AcquireState::SUBOPTIMAL:
case GAL::VulkanRenderContext::AcquireState::BAD: resize(); result = true; break;
default:;
}
} else {
resize(); result = true; AcquireImage();
}
if (lastRenderArea != renderArea) { resize(); result = true; }
return result;
}
RenderSystem::BufferHandle RenderSystem::CreateBuffer(uint32 size, GAL::BufferUse flags, bool willWriteFromHost, bool updateable)
{
uint32 bufferIndex = buffers.Emplace(); auto& buffer = buffers[bufferIndex];
buffer.isMulti = updateable;
buffer.Size = size; buffer.Flags = flags;
++buffer.references;
auto frames = updateable ? GetPipelinedFrames() : 1;
for (uint8 f = 0; f < frames; ++f) {
if (willWriteFromHost) {
if (needsStagingBuffer) { //create staging buffer
AllocateScratchBufferMemory(size, flags | GAL::BufferUses::ADDRESS | GAL::BufferUses::TRANSFER_SOURCE,
&buffer.Staging[f], &buffer.StagingAllocation[f]);
flags |= GAL::BufferUses::TRANSFER_DESTINATION;
}
}
AllocateLocalBufferMemory(size, flags | GAL::BufferUses::ADDRESS, &buffer.Buffer[f], &buffer.Allocation[f]);
}
return BufferHandle(bufferIndex);
}
void RenderSystem::SetBufferWillWriteFromHost(BufferHandle bufferHandle, bool state)
{
auto& buffer = buffers[bufferHandle()];
if (buffer.isMulti) {
__debugbreak();
}
if(state) {
if(!buffer.Staging[0].GetVkBuffer()) {//if will write from host and we have no buffer
if (needsStagingBuffer) {
AllocateScratchBufferMemory(buffer.Size, buffer.Flags | GAL::BufferUses::ADDRESS | GAL::BufferUses::TRANSFER_SOURCE | GAL::BufferUses::STORAGE,
&buffer.Staging[0], &buffer.StagingAllocation[0]);
}
}
//if will write from host and we have buffer, do nothing
} else {
if (buffer.Staging[0].GetVkBuffer()) { //if won't write from host and we have a buffer
if (needsStagingBuffer) {
--buffer.references; //todo: what
}
}
//if won't write from host and we have no buffer, do nothing
}
}
void RenderSystem::printError(const char* message, const RenderDevice::MessageSeverity messageSeverity) const
{
switch (messageSeverity)
{
//case RenderDevice::MessageSeverity::MESSAGE: BE_LOG_MESSAGE(message) break;
case RenderDevice::MessageSeverity::WARNING: BE_LOG_WARNING(message) break;
case RenderDevice::MessageSeverity::ERROR: BE_LOG_ERROR(message); break;
default: break;
}
}
void* RenderSystem::allocateApiMemory(void* data, const uint64 size, const uint64 alignment)
{
void* allocation; uint64 allocated_size;
GetPersistentAllocator().Allocate(size, alignment, &allocation, &allocated_size);
//apiAllocations.Emplace(reinterpret_cast<uint64>(allocation), size, alignment);
{
GTSL::Lock lock(allocationsMutex);
BE_ASSERT(!apiAllocations.contains(reinterpret_cast<uint64>(allocation)), "")
apiAllocations.emplace(reinterpret_cast<uint64>(allocation), GTSL::Pair<uint64, uint64>(size, alignment));
}
return allocation;
}
void* RenderSystem::reallocateApiMemory(void* data, void* oldAllocation, uint64 size, uint64 alignment)
{
void* allocation; uint64 allocated_size;
GTSL::Pair<uint64, uint64> old_alloc;
{
GTSL::Lock lock(allocationsMutex);
//const auto old_alloc = apiAllocations.At(reinterpret_cast<uint64>(oldAllocation));
old_alloc = apiAllocations.at(reinterpret_cast<uint64>(oldAllocation));
}
GetPersistentAllocator().Allocate(size, old_alloc.Second, &allocation, &allocated_size);
//apiAllocations.Emplace(reinterpret_cast<uint64>(allocation), size, alignment);
apiAllocations.emplace(reinterpret_cast<uint64>(allocation), GTSL::Pair<uint64, uint64>(size, alignment));
GTSL::MemCopy(old_alloc.First, oldAllocation, allocation);
GetPersistentAllocator().Deallocate(old_alloc.First, old_alloc.Second, oldAllocation);
//apiAllocations.Remove(reinterpret_cast<uint64>(oldAllocation));
{
GTSL::Lock lock(allocationsMutex);
apiAllocations.erase(reinterpret_cast<uint64>(oldAllocation));
}
return allocation;
}
void RenderSystem::deallocateApiMemory(void* data, void* allocation)
{
GTSL::Pair<uint64, uint64> old_alloc;
{
GTSL::Lock lock(allocationsMutex);
old_alloc = apiAllocations.at(reinterpret_cast<uint64>(allocation));
//const auto old_alloc = apiAllocations.At(reinterpret_cast<uint64>(allocation));
}
GetPersistentAllocator().Deallocate(old_alloc.First, old_alloc.Second, allocation);
{
GTSL::Lock lock(allocationsMutex);
apiAllocations.erase(reinterpret_cast<uint64>(allocation));
//apiAllocations.Remove(reinterpret_cast<uint64>(allocation));
}
}
| 42.62237 | 266 | 0.770786 | [
"mesh",
"geometry",
"vector"
] |
efaa0757b1201b87afb8ef386a45c72c70eec64d | 3,900 | cpp | C++ | src/App.cpp | towa7bc/SDL2Template | b40a3a594c05a87559252b6f61cc7e1163ddc205 | [
"Unlicense"
] | null | null | null | src/App.cpp | towa7bc/SDL2Template | b40a3a594c05a87559252b6f61cc7e1163ddc205 | [
"Unlicense"
] | null | null | null | src/App.cpp | towa7bc/SDL2Template | b40a3a594c05a87559252b6f61cc7e1163ddc205 | [
"Unlicense"
] | null | null | null | //
// Created by Michael Wittmann on 06/06/2020.
//
#include "App.hpp"
#include <GL/glew.h> // Initialize with glewInit()
#include <SDL.h>
#include <memory>
#include <string>
#include "ImGUIHelper.hpp"
#include "detail/Log.hpp"
#include "detail/SDL2Core.hpp"
namespace app {
int App::Run() {
if (!Setup()) {
return -1;
}
SDL_Event sdlEvent;
while (running_) {
while (SDL_PollEvent(&sdlEvent) != 0) {
HandleSDL2Events(sdlEvent);
}
UpdateFPS();
Update();
RenderImGUI();
Render();
}
Cleanup();
return 0;
}
void App::HandleSDL2Events(const SDL_Event& event) {
ImGUIHelper::ProcessEvent(event);
switch (event.type) {
case SDL_QUIT:
running_ = false;
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_CLOSE &&
event.window.windowID == SDL_GetWindowID(window_)) {
running_ = false;
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_f: {
static bool isFullscreen{true};
SDL_SetRelativeMouseMode(SDL_TRUE);
if (isFullscreen) {
SDL_SetWindowFullscreen(window_, SDL_WINDOW_FULLSCREEN);
} else {
SDL_SetWindowFullscreen(window_, 0);
}
isFullscreen = !isFullscreen;
int w{0};
int h{0};
SDL_GetWindowSize(window_, &w, &h);
openGlManager_.reshape(w, h);
SDL_SetRelativeMouseMode(SDL_FALSE);
break;
}
case SDLK_q:
running_ = false;
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
break;
default:
break;
}
}
void App::RenderImGUI() { ImGUIHelper::RenderUI(window_); }
void App::Render() {
int w{0};
int h{0};
SDL_GetWindowSize(window_, &w, &h);
displaySize_.x = w;
displaySize_.y = h;
ImGUIHelper::RenderPrepare(displaySize_, clear_color_);
openGlManager_.render();
ImGUIHelper::RenderDrawData();
SDL_GL_SwapWindow(window_);
}
bool App::Setup() {
if (Log::logger() == nullptr) {
Log::Initialize();
}
Log::logger()->trace("program started.");
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}
SDL_GL_SetAttribute(
SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
// Create window with graphics context
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
auto window_flags = (SDL_WindowFlags)(
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
if ((window_ = SDL_CreateWindow("Particle Example", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, windowDefaultWidth_,
windowDefaultHeight_, window_flags)) ==
nullptr) {
Log::logger()->trace("Window error: " + std::string(SDL_GetError()));
return false;
}
glContext_ = SDL_GL_CreateContext(window_);
SDL_GL_MakeCurrent(window_, glContext_);
SDL_GL_SetSwapInterval(1);
App::RunOpenGLLoader();
clear_color_ = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
ImGUIHelper::Setup(window_, &glContext_, clear_color_);
openGlManager_.init();
return true;
}
App::App() : running_(true), window_(nullptr), glContext_(), openGlManager_() {}
void App::UpdateFPS() {}
void App::Cleanup() {
// Cleanup
ImGUIHelper::Cleanup();
SDL_GL_DeleteContext(glContext_);
cleanup(window_);
openGlManager_.clearResources();
SDL_Quit();
}
void App::Update() {}
bool App::RunOpenGLLoader() {
bool err = glewInit() != GLEW_OK;
return !err;
}
} // namespace app | 25.324675 | 80 | 0.649231 | [
"render"
] |
efab968f4e7816d9f9240e43656085d2ec8afd4e | 735 | cpp | C++ | TicTacToe/Clock.cpp | nenski/TicTacToe_SFML | 68a9e4c3d480dc9d946508fc9669cf23eb2a3094 | [
"MIT"
] | null | null | null | TicTacToe/Clock.cpp | nenski/TicTacToe_SFML | 68a9e4c3d480dc9d946508fc9669cf23eb2a3094 | [
"MIT"
] | null | null | null | TicTacToe/Clock.cpp | nenski/TicTacToe_SFML | 68a9e4c3d480dc9d946508fc9669cf23eb2a3094 | [
"MIT"
] | null | null | null | #include "Clock.h"
Clock::Clock()
{
clock = new sf::Clock;
}
Clock::~Clock()
{
delete clock;
}
//
//
//
// Getters
float Clock::getMicroseconds()
{
return (float)clock->getElapsedTime().asMicroseconds(); // we need to cast our object to a float so we can get a float value back
}
float Clock::getMilliseconds()
{
return (float)clock->getElapsedTime().asMilliseconds();
}
float Clock::getSeconds()
{
return (float)clock->getElapsedTime().asSeconds();
}
// Restart
float Clock::restartMicroseconds()
{
return (float)clock->restart().asMicroseconds();
}
float Clock::restartMilliseconds()
{
return (float)clock->restart().asMilliseconds();
}
float Clock::restartSeconds()
{
return (float)clock->restart().asSeconds();
} | 15.638298 | 132 | 0.696599 | [
"object"
] |
efaccd6941d0dcb7a0bd146b006ce94329deaebd | 6,083 | cpp | C++ | homework/Belyaev/05/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 10 | 2017-09-21T15:17:33.000Z | 2021-01-11T13:11:55.000Z | homework/Belyaev/05/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | null | null | null | homework/Belyaev/05/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 22 | 2017-09-21T15:45:08.000Z | 2019-02-21T19:15:25.000Z | #include <iostream>
#include <vector>
#include <cassert>
#include <cstring>
using namespace std;
template <class T>
class row{
public:
row<T>(size_t elem, T* ptr):
elem(elem),v(ptr){}
~row<T>() {}
T& operator[](const size_t pos){
if(pos >= elem){
assert(!"index out of range");;
}
return v[pos];
}
private:
size_t elem;
T *v;
};
template <class T>
class matrix{
public:
matrix<T>(size_t rows, size_t cols):
rows(rows),cols(cols)
{
if((cols < 1)||(rows < 1))
assert(!"index out of range");
a = new T[rows*cols];
memset(a, 0, sizeof(T) * rows * cols);
}
~matrix<T>(){
delete[] a;
}
matrix<T>(const matrix<T>& copied)
: rows(copied.rows)
, cols(copied.cols)
{
a = new T[rows*cols];
std::copy(copied.a, copied.a + rows * cols, a);
}
matrix<T>& operator=(const matrix<T>& copied)
{
if (this == &copied)
return *this;
if((this->cols != copied.cols) || (this->rows != copied.rows)){
delete[] a;
a = new T[copied.rows * copied.cols];
}
rows = copied.rows;
cols = copied.cols;
std::copy(copied.a, copied.a + rows * cols, a);
return *this;
}
matrix<T>(matrix<T>&& movied)
: rows(std::move(movied.rows))
, cols(std::move(movied.cols))
{
a = movied.a;
movied.a = nullptr;
}
matrix<T>& operator=(matrix<T>&& movied)
{
if (this == &movied)
return *this;
delete[] a;
rows = movied.rows;
cols = movied.cols;
a = movied.a;
movied.a = nullptr;
return *this;
}
bool nullptrCheck() const{
return(this->a == nullptr);
}
int getRows(){
return this->rows;
}
int getColumns(){
return this->cols;
}
row<T> operator[](const size_t val) const{
if(val >= (*this).rows)
assert(!"index out of range");
return row<T>(cols, a+val*cols);
}
matrix<T>& operator*=(const int rval){
for(size_t i = 0; i < rows; i++){
for(size_t j = 0; j < cols; j++){
(*this)[i][j] *= rval;
}
}
return *this;
}
matrix<T>& operator*(const int rval) const{
matrix<T> res(rows, cols);
for(size_t i = 0; i < rows; i++){
for(size_t j = 0; j < cols; j++){
res[i][j] = (*this)[i][j] * rval;
}
}
return res;
}
matrix<T>& operator*=(const vector<T> &rval){
if(cols != rval.size()){
assert(!"index out of range");
}
matrix<T>* res = new matrix<T>(rows,1);
for(size_t i = 0; i < rows; i++){
(*res)[i][0] = 0;
for(size_t j = 0; j < cols; j++){
(*res)[i][0] += (*this)[i][j] * rval[j];
}
}
delete[] this->a;
this->a = res->a;
this->cols = res->cols;
this->rows = res->rows;
res->a = nullptr;
delete res;
return *this;
}
matrix<T> operator*(vector<T> &rval) const{
if(cols != rval.size()){
assert(!"index out of range");
}
matrix<T> res = (*this);
res*=rval;
return res;
}
bool operator==(const matrix<T> &rval) const{
if((cols != rval.cols)||(rows != rval.rows)){
assert(!"index out of range");
}
for(size_t i = 0; i < rows; i++){
for(size_t j = 0; j < cols; j++){
if((*this)[i][j] != rval[i][j])
return false;
}
}
return true;
}
bool operator!=(const matrix<T> &rval) const{
return !(*this == rval);
}
private:
size_t rows;
size_t cols;
T *a;
};
void check(bool value)
{
if (!value)
cout << "error" << endl;
}
int main() {
matrix<double> t1(2, 2);
t1[0][0] = 1.0;
t1[0][1] = 2.0;
t1[1][0] = 3.0;
t1[1][1] = 4.0;
matrix<double> t2(2, 2);
t2[0][0] = 1.0;
t2[0][1] = 2.0;
t2[1][0] = 3.0;
t2[1][1] = 4.0;
matrix<double> t3(2, 2);
t3[0][0] = 1;
t3[0][1] = 2;
t3[1][0] = 2;
t3[1][1] = 4;
matrix<double> t4(2, 2);
t4[0][0] = 5;
t4[0][1] = 10;
t4[1][0] = 15;
t4[1][1] = 20;
check(t1[0][0] == 1); //Checking element acquisition ([])
check(t1 == t2); //Checking comparision (==)
check(t1 != t3); //Checking comparision (!=)
matrix<double> t5(15, 10);
check(t5.getRows() == 15); //Checking rows acquisition
check(t5.getColumns() == 10); //Checking columns acquisition
vector<double> vec1 = {-1, 1};
matrix<double> vec2(2,1);
matrix<double> vec3(2,1);
vec3[0][0] = 1;
vec3[1][0] = 1;
vec2 = t1 * vec1;
check(vec2 == vec3);//Checking matrix<T>-std::vector multiplication
t1 *= vec1;
check(t1 == vec3); //Checking *=
t2 *= 5;
check(t2 == t4); //Checking matrix<T>-number multiplication
matrix<double> t6 = t2;
check(t6 == t2);//Copying initializer check
matrix<double> t7 = t2;
t7 = t3;
check(t7 == t3);//Copying operator check(same dimensions)
matrix<double> t8(2,4);
t8 = t4;
check(t8 == t4);//Copying operator check(dimensions differ)
t8 = t8;
check(t8 == t4);//Copying to itself check
matrix<double> t9 = std::move(t8);//Moving constructor check
check(t9 == t4);
check(t8.nullptrCheck());
//Это должна была быть проверка на то, что при перемещении на себя данные не будут потеряны, но компилятор, проверяющий код, считает это ошибкой. Можно раскомментировать и проверить правильность.
//t9 = std::move(t9);
//check(t9 == t4);//Moving to itself check
matrix<double> t10 = t7;
t10 = std::move(t9);
check(t10 == t4);//Moving operator check
check(t9.nullptrCheck());
cout << "If no errors above - every function works properly" << endl;
return 0;
}
| 23.854902 | 199 | 0.491041 | [
"vector"
] |
efacdcc9583cc48378a1baf9c3489ab9d57f07bf | 5,589 | cpp | C++ | src/fsRayTracing.cpp | dormon/fit_opengl_examples | 84b64e0127976dfc462a54373f88624a3cd99a40 | [
"CC0-1.0"
] | null | null | null | src/fsRayTracing.cpp | dormon/fit_opengl_examples | 84b64e0127976dfc462a54373f88624a3cd99a40 | [
"CC0-1.0"
] | null | null | null | src/fsRayTracing.cpp | dormon/fit_opengl_examples | 84b64e0127976dfc462a54373f88624a3cd99a40 | [
"CC0-1.0"
] | null | null | null | #include<iostream>
#include<fstream>
#include<vector>
#include<cassert>
#include<memory>
#include<SDL2/SDL.h>
#include<GL/glew.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
#include<glm/gtc/matrix_access.hpp>
#include<window.h>
#include<loadTextFile.h>
#include<shader.h>
#include<camera.h>
#include<timer.h>
#include<debugging.h>
#include<programObject.h>
#include<textureObject.h>
struct Data{
struct{
uint32_t width = 1024;
uint32_t height = 768;
}window;
std::map<SDL_Keycode,bool>keyDown;
Timer<float> timer;
std::shared_ptr<CameraProjection>cameraProjection = nullptr;
std::shared_ptr<CameraTransform >cameraTransform = nullptr;
std::shared_ptr<ProgramObject>program = nullptr;
std::shared_ptr<TextureObject>cubeTexture = nullptr;
uint32_t waterSizeX = 10;
uint32_t waterSizeY = 10;
GLuint sphereBuffer = 0;
uint32_t nofSpheres;
GLuint emptyVAO = 0;
};
void init(Data*data);
void draw(Data*data);
void deinit(Data*data);
void mouseMove(SDL_Event event,Data*data);
void keyDown(SDL_Event event,Data*data);
void keyUp(SDL_Event event,Data*data);
int main(int32_t,char*[]){
Data data;
data.window.width = 1024;
data.window.height = 768;
SDLWindow window(data.window.width,data.window.height);
init(&data);
window.setIdle((SDLWindow::Callback)draw,&data);
window.setEvent(SDL_MOUSEMOTION,(SDLWindow::EventCallback)mouseMove ,&data);
window.setEvent(SDL_KEYDOWN ,(SDLWindow::EventCallback)keyDown ,&data);
window.setEvent(SDL_KEYUP ,(SDLWindow::EventCallback)keyUp ,&data);
window.mainLoop();
deinit(&data);
return EXIT_SUCCESS;
}
void draw(Data*data){
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
data->program->use();
data->program->setMatrix4fv("v",glm::value_ptr(data->cameraTransform->getView()));
data->program->setMatrix4fv("p",glm::value_ptr(data->cameraProjection->getProjection()));
data->cubeTexture->bind(0);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,data->sphereBuffer);
data->program->set1ui("nofSpheres",data->nofSpheres);
glBindVertexArray(data->emptyVAO);
glDrawArrays(GL_TRIANGLE_STRIP,0,4);
glBindVertexArray(0);
float frameTime = data->timer.elapsedFromLast();
(void)frameTime;
}
void init(Data*data){
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback((GLDEBUGPROC)defaultDebugMessage,NULL);
FreeImage_Initialise(TRUE);
data->cameraTransform = std::make_shared<OrbitCamera>();
data->cameraProjection = std::make_shared<PerspectiveCamera>(
glm::half_pi<float>(),
(float)data->window.width/data->window.height,0.001);
data->program = std::make_shared<ProgramObject>(createProgram(
compileShader(GL_VERTEX_SHADER ,
"#version 450\n",
loadFile("shaders/fsRayTracing.vp")),
compileShader(GL_FRAGMENT_SHADER,
"#version 450\n",
loadFile("shaders/fsRayTracing.fp"))));
data->cubeTexture = std::make_shared<TextureObject>(
/*
"textures/volareft.tga",
"textures/volarebk.tga",
"textures/volareup.tga",
"textures/volaredn.tga",
"textures/volarelf.tga",
"textures/volarert.tga",
// */
//*
"textures/cube0.png",
"textures/cube1.png",
"textures/cube2.png",
"textures/cube3.png",
"textures/cube4.png",
"textures/cube5.png",
// */
GL_RGBA,true);
glGenBuffers(1,&data->sphereBuffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER,data->sphereBuffer);
struct Sphere{
glm::vec4 positionRadius;
glm::vec4 color;
};
data->nofSpheres = 30;
Sphere*spheres = new Sphere[data->nofSpheres];
for(uint32_t i=0;i<data->nofSpheres;++i){
float t = (float)i/data->nofSpheres;
float angle = glm::radians<float>(3*360.f*t);
spheres[i].positionRadius = glm::vec4(glm::cos(angle),t*4,glm::sin(angle),glm::sin(t*10)*.2f+.3f);
spheres[i].color = glm::vec4(0.f,1.f,0.f,1.f);
}
glBufferData(GL_SHADER_STORAGE_BUFFER,sizeof(Sphere)*data->nofSpheres,spheres,GL_STATIC_DRAW);
delete[]spheres;
glGenVertexArrays(1,&data->emptyVAO);
glClearColor(0,0,0,1);
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
}
void deinit(Data*data){
FreeImage_DeInitialise();
glDeleteVertexArrays(1,&data->emptyVAO);
}
void mouseMove(SDL_Event event,Data*data){
if(event.motion.state & SDL_BUTTON_LMASK){
float sensitivity = 0.01;
auto orbitCamera = std::dynamic_pointer_cast<OrbitCamera>(data->cameraTransform);
if(orbitCamera){
orbitCamera->setXAngle(orbitCamera->getXAngle() + event.motion.yrel*sensitivity);
orbitCamera->setYAngle(orbitCamera->getYAngle() + event.motion.xrel*sensitivity);
}
}
if(event.motion.state & SDL_BUTTON_RMASK){
float step = 0.01;
auto orbitCamera = std::dynamic_pointer_cast<OrbitCamera>(data->cameraTransform);
if(orbitCamera){
orbitCamera->setDistance(glm::clamp(orbitCamera->getDistance() + event.motion.yrel*step,0.1f,10.f));
}
}
if(event.motion.state & SDL_BUTTON_MMASK){
auto orbitCamera = std::dynamic_pointer_cast<OrbitCamera>(data->cameraTransform);
orbitCamera->addXPosition(+orbitCamera->getDistance()*event.motion.xrel/data->window.width*2.);
orbitCamera->addYPosition(-orbitCamera->getDistance()*event.motion.yrel/data->window.width*2.);
}
}
void keyDown(SDL_Event event,Data*data){
data->keyDown[event.key.keysym.sym]=true;
}
void keyUp(SDL_Event event,Data*data){
data->keyDown[event.key.keysym.sym]=false;
}
| 29.415789 | 106 | 0.709966 | [
"vector"
] |
efacdfc317b99620a7b4afbce195898b2a0f7c38 | 18,088 | hh | C++ | bwt.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | 9 | 2019-09-17T10:33:58.000Z | 2021-07-29T10:03:42.000Z | bwt.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | null | null | null | bwt.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | 1 | 2019-10-05T04:31:22.000Z | 2019-10-05T04:31:22.000Z | // Copyright Stephan T. Lavavej, http://nuwen.net .
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://boost.org/LICENSE_1_0.txt .
#ifndef PHAM_BWT_HH
#define PHAM_BWT_HH
#include "compiler.hh"
#ifdef NUWEN_PLATFORM_MSVC
#pragma once
#endif
#include "typedef.hh"
#include "vector.hh"
#include "external_begin.hh"
#include <algorithm>
#include <list>
#include <stack>
#include <stdexcept>
#include <utility>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/utility.hpp>
#include "external_end.hh"
namespace nuwen {
inline vuc_t bwt(const vuc_t& v);
inline vuc_t unbwt(const vuc_t& v);
}
// Uncomment to enable internal logic checks that should never fire.
// #define PHAM_BWT_LOGIC_CHECKS
namespace pham {
namespace ukk {
// Let there be N bytes.
// Infinity is the location of the sentinel, which is N.
// The sentineled length is N + 1.
// There are N + 1 leaves.
// There are at most N + 1 nodes including root and bottom.
const nuwen::vuc_s_t MIN_ALLOWED_SIZE = 1;
const nuwen::vuc_s_t MAX_ALLOWED_SIZE = 512 * 1048576;
typedef nuwen::us_t symbol_t;
typedef nuwen::sl_t index_t;
const symbol_t SENTINEL = 256;
const symbol_t SIGMA = 257;
const symbol_t FILLER = 0;
class wrapped_text : public boost::noncopyable {
public:
explicit wrapped_text(const nuwen::vuc_t& v) : m_v(v), m_infinity(static_cast<index_t>(v.size())) { }
index_t infinity() const { return m_infinity; }
symbol_t operator[](const index_t i) const {
if (i == m_infinity) {
return SENTINEL;
} else if (i < 0) {
return static_cast<symbol_t>(-i - 1);
} else {
return m_v[static_cast<nuwen::vuc_s_t>(i)];
}
}
private:
const nuwen::vuc_t& m_v;
const index_t m_infinity;
};
template <typename T> class flex_alloc : public boost::noncopyable {
public:
// There are at most *roughly* N hybrid_edges.
// A hybrid_edge is 20 bytes.
// Using N / 20 for K would result in roughly 1 N wasted space at most.
// Using N / 200 for K reduces this to .1 N.
// As the list and vector scheme incurs some overhead, a lower limit of 1000 is placed on K.
explicit flex_alloc(const nuwen::vuc_s_t n)
: m_k(std::max<nuwen::vuc_s_t>(n / 200, 1000)), m_lst(), m_next(NULL), m_end(NULL) { }
T * make() {
if (m_next == m_end) {
m_lst.push_back(std::vector<T>());
m_lst.back().resize(m_k);
m_next = &m_lst.back()[0];
m_end = m_next + m_k;
}
return m_next++;
}
private:
const nuwen::vuc_s_t m_k;
std::list<std::vector<T> > m_lst;
T * m_next;
const T * m_end;
};
template <typename T> class hard_alloc : public boost::noncopyable {
public:
explicit hard_alloc(const nuwen::vuc_s_t n)
: m_v(n), m_next(&m_v[0]), m_begin(&m_v[0]), m_end(m_begin + m_v.size()) { }
T * make() {
#ifdef PHAM_BWT_LOGIC_CHECKS
if (m_next == m_end) {
throw std::logic_error("LOGIC ERROR: pham::ukk::hard_alloc<T>::make() - Out of space.");
}
#endif
return m_next++;
}
bool contains(const T * const p) const {
return p >= m_begin && p < m_end;
}
private:
std::vector<T> m_v;
T * m_next;
const T * const m_begin;
const T * const m_end;
};
// left and right are INCLUSIVE indices.
// The first symbol of an edge is at the left index.
// A node contains only a suffix link and an edge_list.
// Ukkonen never travels the suffix links of leaves.
// Leaves are never given any children.
// Therefore, leaves contain no useful information.
// Therefore, an edge to a leaf has a NULL child.
struct edge {
edge * m_next;
index_t m_left;
edge * next() const { return m_next; }
index_t left() const { return m_left; }
};
// The edges are kept sorted by their first symbols in increasing order.
class edge_list {
public:
edge_list() : m_head(NULL) { }
std::pair<edge *, edge *> find(const symbol_t a, const wrapped_text& text) const {
edge * old = NULL;
for (edge * p = m_head; p != NULL; old = p, p = p->next()) {
const symbol_t x = text[p->left()];
if (x < a) {
// Keep looking.
} else if (x == a) {
return std::make_pair(old, p); // Found it.
} else {
return std::pair<edge *, edge *>(old, NULL); // Stop looking.
}
}
return std::pair<edge *, edge *>(old, NULL); // We looked at everything and didn't find it.
}
bool exists(const symbol_t a, const wrapped_text& text) const {
return find(a, text).second != NULL;
}
edge * get(const symbol_t a, const wrapped_text& text) const {
edge * const p = find(a, text).second;
#ifdef PHAM_BWT_LOGIC_CHECKS
if (p == NULL) {
throw std::logic_error("LOGIC ERROR: pham::ukk::edge_list::get() - Edge not found.");
}
#endif
return p;
}
void push(hard_alloc<edge>& leaf_alloc, const wrapped_text& text, const index_t left) {
const symbol_t a = text[left];
edge * old = NULL;
for (edge * p = m_head; p != NULL; old = p, p = p->next()) {
const symbol_t x = text[p->left()];
if (x < a) {
// Keep looking.
} else {
#ifdef PHAM_BWT_LOGIC_CHECKS
// Case 1: Edit this edge.
if (x == a) {
throw std::logic_error("LOGIC ERROR: pham::ukk::edge_list::push() - Editing NULL, or non-NULL becoming NULL.");
}
#endif
// Case 2: Insert before this edge.
insert_between(leaf_alloc, old, p, left);
return;
}
}
// Case 3: Insert at the end.
insert_between(leaf_alloc, old, NULL, left);
}
edge * head() const { return m_head; }
void set_head(edge * const p) { m_head = p; }
private:
void insert_between(hard_alloc<edge>& leaf_alloc, edge * const old, edge * const p, const index_t left) {
#ifdef PHAM_BWT_LOGIC_CHECKS
if (left < 0) {
throw std::logic_error("LOGIC ERROR: pham::ukk::edge_list::insert_between() - Negative leaf edge.");
}
#endif
edge * const nu = leaf_alloc.make();
nu->m_next = p;
nu->m_left = left;
if (old) {
old->m_next = nu;
} else {
m_head = nu;
}
}
edge * m_head;
};
struct node {
node() : m_edges(), m_link(NULL) { }
edge_list m_edges;
node * m_link;
};
struct hybrid_edge {
edge m_first; // The 9.2/17 trick.
index_t m_right;
node m_node;
};
class tree : public boost::noncopyable {
public:
explicit tree(const nuwen::vuc_t& v)
: m_hybrid_alloc(v.size()), m_leaf_alloc(v.size() + 1), m_negative_alloc(SIGMA), m_root(), m_bottom(), m_text(v) {
m_root.m_link = &m_bottom;
// We build the list of negative edges in reverse order, from the end to the beginning.
for (int j = SIGMA; j >= 1; --j) {
edge * const p = m_negative_alloc.make();
p->m_next = m_bottom.m_edges.head();
p->m_left = -j;
m_bottom.m_edges.set_head(p);
}
// Algorithm 2, Steps 4 - 8
std::pair<node *, index_t> curr(&m_root, 0);
for (index_t i = 0; i <= m_text.infinity(); ++i) {
curr = update(curr.first, curr.second, i);
curr = canonize(curr.first, curr.second, i);
}
}
template <typename Functor> void dfs(Functor f) {
typedef std::pair<edge *, index_t> pair_t;
std::stack<pair_t, std::vector<pair_t> > stak; // Vector-based for speed.
stak.push(std::make_pair(m_root.m_edges.head(), 0));
while (!stak.empty()) {
edge * const e = stak.top().first;
if (e) {
stak.top().first = e->next();
const index_t len = stak.top().second + get_right(e) - e->left() + 1;
if (m_leaf_alloc.contains(e)) {
f(static_cast<nuwen::ul_t>(len));
} else {
stak.push(std::make_pair(get_child(e)->m_edges.head(), len));
}
} else {
stak.pop();
}
}
}
private:
index_t get_right(const edge * const p) const {
if (m_leaf_alloc.contains(p)) {
return m_text.infinity();
} else if (m_negative_alloc.contains(p)) {
return p->left();
} else {
return reinterpret_cast<const hybrid_edge *>(p)->m_right;
}
}
node * get_child(edge * const p) {
if (m_leaf_alloc.contains(p)) {
return NULL;
} else if (m_negative_alloc.contains(p)) {
return &m_root;
} else {
return &reinterpret_cast<hybrid_edge *>(p)->m_node;
}
}
// Ukkonen: e->left() = k' get_right(e) = p' get_child(e) = s'
std::pair<node *, index_t> canonize(node * s, index_t k, const index_t p) {
if (k <= p) {
edge * e = s->m_edges.get(m_text[k], m_text);
while (get_right(e) - e->left() <= p - k) {
k += get_right(e) - e->left() + 1;
s = get_child(e);
if (k <= p) {
e = s->m_edges.get(m_text[k], m_text);
}
}
}
return std::make_pair(s, k);
}
std::pair<bool, node *> test_and_split(node * const s, const index_t k, const index_t p, const symbol_t t) {
if (k > p) {
return std::make_pair(s->m_edges.exists(t, m_text), s);
}
edge * old;
edge * e;
boost::tie(old, e) = s->m_edges.find(m_text[k], m_text);
const index_t kprime = e->left();
#ifdef PHAM_BWT_LOGIC_CHECKS
if (m_text[kprime] != m_text[k]) {
throw std::logic_error("LOGIC ERROR: pham::ukk::tree::test_and_split() - Symbol mismatch.");
}
#endif
if (t == m_text[kprime + p - k + 1]) {
return std::make_pair(true, s);
}
hybrid_edge * const nu_hybrid = m_hybrid_alloc.make();
edge * const nu = reinterpret_cast<edge *>(nu_hybrid);
if (old) {
old->m_next = nu;
} else {
s->m_edges.set_head(nu);
}
nu->m_next = e->next();
nu->m_left = kprime;
nu_hybrid->m_right = kprime + p - k;
node * const r = &nu_hybrid->m_node;
// We can now modify e.
e->m_next = NULL;
e->m_left = kprime + p - k + 1;
r->m_edges.set_head(e);
return std::make_pair(false, r);
}
std::pair<node *, index_t> update(node * s, index_t k, const index_t i) {
bool endpoint;
node * r;
node * oldr = &m_root;
boost::tie(endpoint, r) = test_and_split(s, k, i - 1, m_text[i]);
while (!endpoint) {
r->m_edges.push(m_leaf_alloc, m_text, i);
if (oldr != &m_root) {
oldr->m_link = r;
}
oldr = r;
boost::tie(s, k) = canonize(s->m_link, k, i - 1);
boost::tie(endpoint, r) = test_and_split(s, k, i - 1, m_text[i]);
}
if (oldr != &m_root) {
oldr->m_link = s;
}
return std::make_pair(s, k);
}
flex_alloc<hybrid_edge> m_hybrid_alloc;
hard_alloc<edge> m_leaf_alloc;
hard_alloc<edge> m_negative_alloc;
node m_root;
node m_bottom;
const wrapped_text m_text;
};
class bwt_helper {
public:
bwt_helper(const nuwen::vuc_t& src, nuwen::vuc_t& dest)
: m_src(src.begin()), m_n(src.size()), m_dest(dest.begin() + 8), m_dest_orig(m_dest),
m_primarydest(dest.begin()), m_sentineldest(dest.begin() + 4) { }
void operator()(const nuwen::ul_t len) {
if (len < m_n) {
*m_dest++ = m_src[static_cast<index_t>(m_n - len)];
} else if (len == m_n) {
const nuwen::vuc_t primaryindex = nuwen::vuc_from_ul(static_cast<nuwen::ul_t>(m_dest - m_dest_orig));
std::copy(primaryindex.begin(), primaryindex.end(), m_primarydest);
*m_dest++ = m_src[0];
} else {
const nuwen::vuc_t sentinelindex = nuwen::vuc_from_ul(static_cast<nuwen::ul_t>(m_dest - m_dest_orig));
std::copy(sentinelindex.begin(), sentinelindex.end(), m_sentineldest);
*m_dest++ = FILLER;
}
}
private:
nuwen::vuc_ci_t m_src;
nuwen::vuc_s_t m_n;
nuwen::vuc_i_t m_dest;
nuwen::vuc_ci_t m_dest_orig;
nuwen::vuc_i_t m_primarydest;
nuwen::vuc_i_t m_sentineldest;
};
}
}
inline nuwen::vuc_t nuwen::bwt(const vuc_t& v) {
using namespace std;
using namespace pham::ukk;
if (v.size() < MIN_ALLOWED_SIZE) {
throw logic_error("LOGIC ERROR: nuwen::bwt() - v is too small.");
}
if (v.size() > MAX_ALLOWED_SIZE) {
throw runtime_error("RUNTIME ERROR: nuwen::bwt() - v is too big.");
}
vuc_t ret(v.size() + 9);
tree st(v);
st.dfs(bwt_helper(v, ret));
return ret;
}
inline nuwen::vuc_t nuwen::unbwt(const vuc_t& v) {
using namespace std;
using namespace pham::ukk;
if (v.size() < 9 + MIN_ALLOWED_SIZE) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - v is too small.");
}
if (v.size() > 9 + MAX_ALLOWED_SIZE) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - v is too big.");
}
const ul_t primaryindex = ul_from_vuc(v, 0);
const ul_t sentinelindex = ul_from_vuc(v, 4);
const vuc_ci_t src = v.begin() + 8;
const vuc_s_t n = v.size() - 8;
if (primaryindex >= n) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - Invalid primary index.");
}
if (sentinelindex >= n) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - Invalid sentinel index.");
}
if (src[static_cast<index_t>(sentinelindex)] != FILLER) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - Sentinel index doesn't contain filler.");
}
vul_t freqs(SIGMA, 0); // Fenwick's K
for (vuc_s_t i = 0; i < n; ++i) {
++freqs[static_cast<vul_s_t>(i == sentinelindex ? SENTINEL : src[static_cast<index_t>(i)])];
}
vul_t mapping(SIGMA); // Fenwick's M
mapping[0] = 0;
for (ul_t i = 1; i < SIGMA; ++i) {
mapping[i] = mapping[i - 1] + freqs[i - 1];
}
vul_t links(n); // Fenwick's L
for (vuc_s_t i = 0; i < n; ++i) {
links[i] = mapping[static_cast<vul_s_t>(i == sentinelindex ? SENTINEL : src[static_cast<index_t>(i)])]++;
}
vuc_t ret(n);
ul_t index = primaryindex;
for (vuc_ri_t i = ret.rbegin(); i != ret.rend(); ++i) {
index = links[index];
*i = src[static_cast<index_t>(index)];
}
if (ret.back() != FILLER) {
throw runtime_error("RUNTIME ERROR: nuwen::unbwt() - ret's last byte isn't filler.");
}
ret.pop_back();
return ret;
}
#undef PHAM_BWT_LOGIC_CHECKS
#endif // Idempotency
| 32.242424 | 139 | 0.4728 | [
"vector"
] |
efafbac2384c10adf2e62c88e6a118b195473e68 | 8,413 | cpp | C++ | src/engine/animation/animation.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | src/engine/animation/animation.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | src/engine/animation/animation.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file animation.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2005-02-24
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/engine/precompiled.h"
#include "o3d/engine/animation/animation.h"
#include "o3d/engine/animation/animationnode.h"
#include "o3d/engine/hierarchy/node.h"
#include "o3d/core/templatemanager.h"
#include "o3d/core/filemanager.h"
#include "o3d/core/classfactory.h"
using namespace o3d;
O3D_IMPLEMENT_DYNAMIC_CLASS1(Animation, ENGINE_ANIMATION, SceneResource)
/*---------------------------------------------------------------------------------------
constructor
---------------------------------------------------------------------------------------*/
Animation::Animation(BaseObject *parent) :
SceneResource(parent),
m_fatherNode(nullptr),
m_numObjects(0),
m_duration(1.f),
m_computed(False)
{
}
/*---------------------------------------------------------------------------------------
destructor
---------------------------------------------------------------------------------------*/
Animation::~Animation()
{
deletePtr(m_fatherNode);
}
/*---------------------------------------------------------------------------------------
get an anim range by its name (return false if not found)
---------------------------------------------------------------------------------------*/
Bool Animation::getAnimRange(const String &name, AnimRange &range)
{
for (UInt32 i = 0 ; i < m_animRange.size() ; ++i)
{
if (m_animRange[i].name.length() && (m_animRange[i].name == name))
{
range.start = m_animRange[i].start;
range.end = m_animRange[i].end;
range.breaking = m_animRange[i].breaking;
range.name = m_animRange[i].name;
return True;
}
}
return False;
}
/*---------------------------------------------------------------------------------------
update the animation subtree (0..t..1)
---------------------------------------------------------------------------------------*/
void Animation::update(
class Animatable *anim,
Float time,
Animation::BlendMode blendMode,
Float weight)
{
if (m_fatherNode)
m_fatherNode->update(anim, time, blendMode, weight);
}
/*---------------------------------------------------------------------------------------
round to the nearest keyframes
---------------------------------------------------------------------------------------*/
void Animation::roundToNearestKeyFrame(
Animatable* target,
Float &stime,
Float &etime)
{
Float nstime,netime;
if (m_fatherNode)
m_fatherNode->findTrackTime(target, stime, etime, nstime, netime);
else
nstime = netime = 0.f;
stime = nstime;
etime = netime;
}
/*---------------------------------------------------------------------------------------
use an anim range for pTarget
---------------------------------------------------------------------------------------*/
void Animation::useAnimRange(Animatable* target, UInt32 id) const
{
O3D_ASSERT(id < (UInt32)m_animRange.size());
if (m_fatherNode)
m_fatherNode->useRange(target, id);
}
/*---------------------------------------------------------------------------------------
use full range anim for pTarget
---------------------------------------------------------------------------------------*/
void Animation::useFullRange(Animatable* target) const
{
if (m_fatherNode)
m_fatherNode->defineFullRange(target);
}
/*---------------------------------------------------------------------------------------
precompute all animation range for tracks
---------------------------------------------------------------------------------------*/
void Animation::computeAnimRange()
{
if (!m_fatherNode)
return;
Float inv = 1.f / (Float)(m_frame-1);
for (UInt32 i = 0 ; i < m_animRange.size() ; ++i)
{
m_fatherNode->computeRange(m_animRange[i].start * inv, m_animRange[i].end * inv);
}
m_computed = True;
}
/*---------------------------------------------------------------------------------------
draw the trajectories of all subtree
---------------------------------------------------------------------------------------*/
void Animation::drawTrajectory(Node *currentNode, const DrawInfo &drawInfo)
{
if (m_fatherNode) {
m_fatherNode->drawTrajectory(currentNode, drawInfo);
}
}
/*---------------------------------------------------------------------------------------
according to the node that is selected in the hierarchy tree, compute the corresponding
---------------------------------------------------------------------------------------*/
AnimationNode* Animation::computeStartNode(
AnimationNode *currentAnimationNode,
Node *currentNode,
Node *selectedNode)
{
if (currentNode == selectedNode)
return currentAnimationNode;
// recurse sons
const T_SonList &SonList = currentNode->getSonList();
T_AnimationNodeList &AnimationSonList = currentAnimationNode->getSonList();
IT_AnimationNodeList a_it = AnimationSonList.begin();
for (CIT_SonList n_it = SonList.begin(); n_it != SonList.end() ; ++n_it)
{
if (a_it == AnimationSonList.end())
{
// animation node has not enough sons
O3D_WARNING("Animation node has not enough sons");
return nullptr;
}
// recurse childs
if ((*n_it)->isNodeObject())
{
AnimationNode *pRet = computeStartNode(*a_it, ((Node*)(*n_it)), selectedNode);
if (pRet != nullptr)
return pRet;
}
++a_it;
}
if (a_it != AnimationSonList.end())
{
// animation node has too much sons
O3D_WARNING("Animation node has too much sons");
return nullptr;
}
return nullptr;
}
/*---------------------------------------------------------------------------------------
serialisation
---------------------------------------------------------------------------------------*/
Bool Animation::writeToFile(
OutStream &os,
Node *hierarchyRoot,
Node *selectedNode)
{
BaseObject::writeToFile(os);
// set animation name
m_name = selectedNode->getName();
// write animation data
os << m_numObjects
<< m_frame
<< m_duration;
// write all animation ranges
os << (Int32)m_animRange.size();
for (IT_AnimRangeVector it = m_animRange.begin() ; it != m_animRange.end() ; ++it)
{
os << (*it).start
<< (*it).end
<< (*it).breaking
<< (*it).name;
}
// compute the animation node corresponding to the hierarchy selected node
AnimationNode *pStartNode = computeStartNode(m_fatherNode, hierarchyRoot, selectedNode);
if (pStartNode == nullptr)
{
O3D_ERROR(E_InvalidFormat("Can't retrieve the root node of the animation"));
}
else
{
os << *pStartNode; // write the subtree animation node
}
return True;
}
Bool Animation::writeToFile(OutStream &os)
{
BaseObject::writeToFile(os);
// write animation data
os << m_numObjects
<< m_frame
<< m_duration;
// write all animation ranges
os << (Int32)m_animRange.size();
for (IT_AnimRangeVector it = m_animRange.begin(); it != m_animRange.end(); ++it)
{
os << (*it).start
<< (*it).end
<< (*it).breaking
<< (*it).name;
}
// write the sub tree of animation node
os << *m_fatherNode;
return True;
}
Bool Animation::readFromFile(InStream &is)
{
BaseObject::readFromFile(is);
// read animation data
is >> m_numObjects
>> m_frame
>> m_duration;
// read all animation ranges
Int32 numRange;
is >> numRange;
for (Int32 i = 0; i < numRange; ++i)
{
AnimRange range;
is >> range.start
>> range.end
>> range.breaking
>> range.name;
m_animRange.push_back(range);
}
// create the father node
m_fatherNode = new AnimationNode(nullptr);
// read recursively the hierarchy
is >> *m_fatherNode;
// finally precompute animation range tracks keys
computeAnimRange();
return True;
}
// Save the animation file (*.o3dan) into the specified path and using the defined filename
Bool Animation::save()
{
// need to define a filename
if (m_filename.isEmpty())
O3D_ERROR(E_InvalidPrecondition("The animation file name must be previously defined"));
// open the file
FileOutStream *os = FileManager::instance()->openOutStream(m_filename, FileOutStream::CREATE);
// write the animation according to its object type
if (!ClassFactory::writeToFile(*os, *this))
{
deletePtr(os);
return False;
}
deletePtr(os);
return True;
}
| 26.623418 | 98 | 0.526328 | [
"object"
] |
efb7468c6cebd8c7c9a4e06094a38b5a878d208c | 745 | cpp | C++ | benchmarks/c_bench/c_bench.cpp | chenglin/lleaves | 54e07cd39279a7f0407e3cc8adb5862b3bc41bda | [
"MIT"
] | 116 | 2021-06-25T14:33:26.000Z | 2022-03-30T07:32:29.000Z | benchmarks/c_bench/c_bench.cpp | chenglin/lleaves | 54e07cd39279a7f0407e3cc8adb5862b3bc41bda | [
"MIT"
] | 13 | 2021-07-28T07:12:40.000Z | 2022-03-30T05:59:10.000Z | benchmarks/c_bench/c_bench.cpp | chenglin/lleaves | 54e07cd39279a7f0407e3cc8adb5862b3bc41bda | [
"MIT"
] | 5 | 2021-06-28T16:44:49.000Z | 2022-03-23T02:40:21.000Z | #include "c_bench.h"
#include <cnpy.h>
#include <benchmark/benchmark.h>
#include <algorithm>
#include <cstdlib>
#include <iostream>
static void bm_lleaves(benchmark::State& state) {
char *model_name = std::getenv("LLEAVES_BENCHMARK_MODEL");
std::ostringstream model_stream;
model_stream << "../../data/" << model_name << ".npy";
std::string model_file = model_stream.str();
cnpy::NpyArray arr = cnpy::npy_load(model_file);
auto *loaded_data = arr.data<double>();
ulong n_preds = arr.shape[0];
auto *out = (double *)(malloc(n_preds * sizeof(double)));
for (auto _ : state){
// predict over the whole input array
forest_root(loaded_data, out, (int)0, (int)n_preds);
}
}
BENCHMARK(bm_lleaves);
BENCHMARK_MAIN(); | 27.592593 | 60 | 0.687248 | [
"shape"
] |
efb79dadf3114831a9540a9a4d738e4b8882577b | 349 | cpp | C++ | Lucy/src/lucy/game_objects/particle.cpp | Tremah/LucyEngine | b5bcb6232ddbe07fffa19009e582d8e6caba42ec | [
"MIT"
] | null | null | null | Lucy/src/lucy/game_objects/particle.cpp | Tremah/LucyEngine | b5bcb6232ddbe07fffa19009e582d8e6caba42ec | [
"MIT"
] | null | null | null | Lucy/src/lucy/game_objects/particle.cpp | Tremah/LucyEngine | b5bcb6232ddbe07fffa19009e582d8e6caba42ec | [
"MIT"
] | null | null | null | #include <lupch.h>
#include "particle.h"
namespace Lucy
{
Particle::Particle(PhysicsComponent* transform, GraphicsComponent* graphics) : physics_ { transform }, graphics_{graphics} {}
PhysicsComponent& Particle::physics() const
{
return *physics_;
}
GraphicsComponent& Particle::graphics() const
{
return *graphics_;
}
}
| 16.619048 | 127 | 0.702006 | [
"transform"
] |
efbcdff7d2dae470064a285bfd55e20aa0aafd1b | 2,759 | hpp | C++ | lib/boost_1.78.0/boost/geometry/core/coordinate_promotion.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | lib/boost_1.78.0/boost/geometry/core/coordinate_promotion.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | lib/boost_1.78.0/boost/geometry/core/coordinate_promotion.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry
// Copyright (c) 2021 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_CORE_COORDINATE_PROMOTION_HPP
#define BOOST_GEOMETRY_CORE_COORDINATE_PROMOTION_HPP
#include <boost/geometry/core/coordinate_type.hpp>
// TODO: move this to a future headerfile implementing traits for these types
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
namespace boost { namespace geometry
{
namespace traits
{
// todo
} // namespace traits
/*!
\brief Meta-function converting, if necessary, to "a floating point" type
\details
- if input type is integer, type is double
- else type is input type
\ingroup utility
*/
// TODO: replace with, or call, promoted_to_floating_point
template <typename T, typename PromoteIntegerTo = double>
struct promote_floating_point
{
typedef std::conditional_t
<
std::is_integral<T>::value,
PromoteIntegerTo,
T
> type;
};
// TODO: replace with promoted_to_floating_point
template <typename Geometry>
struct fp_coordinate_type
{
typedef typename promote_floating_point
<
typename coordinate_type<Geometry>::type
>::type type;
};
namespace detail
{
// Promote any integral type to double. Floating point
// and other user defined types stay as they are, unless specialized.
// TODO: we shold add a coordinate_promotion traits for promotion to
// floating point or (larger) integer types.
template <typename Type>
struct promoted_to_floating_point
{
using type = std::conditional_t
<
std::is_integral<Type>::value, double, Type
>;
};
// Boost.Rational goes to double
template <typename T>
struct promoted_to_floating_point<boost::rational<T>>
{
using type = double;
};
// Any Boost.Multiprecision goes to double (for example int128_t),
// unless specialized
template <typename Backend>
struct promoted_to_floating_point<boost::multiprecision::number<Backend>>
{
using type = double;
};
// Boost.Multiprecision binary floating point numbers are used as FP.
template <unsigned Digits>
struct promoted_to_floating_point
<
boost::multiprecision::number
<
boost::multiprecision::cpp_bin_float<Digits>
>
>
{
using type = boost::multiprecision::number
<
boost::multiprecision::cpp_bin_float<Digits>
>;
};
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_CORE_COORDINATE_PROMOTION_HPP
| 24.633929 | 79 | 0.710765 | [
"geometry"
] |
efccfb1d532e7f23322a3f8af626f86919b0c55e | 14,599 | cpp | C++ | tcb/src/v20180608/model/DescribeCloudBaseRunOneClickTaskExternalResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcb/src/v20180608/model/DescribeCloudBaseRunOneClickTaskExternalResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcb/src/v20180608/model/DescribeCloudBaseRunOneClickTaskExternalResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcb/v20180608/model/DescribeCloudBaseRunOneClickTaskExternalResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcb::V20180608::Model;
using namespace std;
DescribeCloudBaseRunOneClickTaskExternalResponse::DescribeCloudBaseRunOneClickTaskExternalResponse() :
m_externalIdHasBeenSet(false),
m_envIdHasBeenSet(false),
m_userUinHasBeenSet(false),
m_serverNameHasBeenSet(false),
m_versionNameHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_stageHasBeenSet(false),
m_statusHasBeenSet(false),
m_failReasonHasBeenSet(false),
m_userEnvIdHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_stepsHasBeenSet(false)
{
}
CoreInternalOutcome DescribeCloudBaseRunOneClickTaskExternalResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("ExternalId") && !rsp["ExternalId"].IsNull())
{
if (!rsp["ExternalId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ExternalId` IsString=false incorrectly").SetRequestId(requestId));
}
m_externalId = string(rsp["ExternalId"].GetString());
m_externalIdHasBeenSet = true;
}
if (rsp.HasMember("EnvId") && !rsp["EnvId"].IsNull())
{
if (!rsp["EnvId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EnvId` IsString=false incorrectly").SetRequestId(requestId));
}
m_envId = string(rsp["EnvId"].GetString());
m_envIdHasBeenSet = true;
}
if (rsp.HasMember("UserUin") && !rsp["UserUin"].IsNull())
{
if (!rsp["UserUin"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserUin` IsString=false incorrectly").SetRequestId(requestId));
}
m_userUin = string(rsp["UserUin"].GetString());
m_userUinHasBeenSet = true;
}
if (rsp.HasMember("ServerName") && !rsp["ServerName"].IsNull())
{
if (!rsp["ServerName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ServerName` IsString=false incorrectly").SetRequestId(requestId));
}
m_serverName = string(rsp["ServerName"].GetString());
m_serverNameHasBeenSet = true;
}
if (rsp.HasMember("VersionName") && !rsp["VersionName"].IsNull())
{
if (!rsp["VersionName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `VersionName` IsString=false incorrectly").SetRequestId(requestId));
}
m_versionName = string(rsp["VersionName"].GetString());
m_versionNameHasBeenSet = true;
}
if (rsp.HasMember("CreateTime") && !rsp["CreateTime"].IsNull())
{
if (!rsp["CreateTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_createTime = string(rsp["CreateTime"].GetString());
m_createTimeHasBeenSet = true;
}
if (rsp.HasMember("Stage") && !rsp["Stage"].IsNull())
{
if (!rsp["Stage"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Stage` IsString=false incorrectly").SetRequestId(requestId));
}
m_stage = string(rsp["Stage"].GetString());
m_stageHasBeenSet = true;
}
if (rsp.HasMember("Status") && !rsp["Status"].IsNull())
{
if (!rsp["Status"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(rsp["Status"].GetString());
m_statusHasBeenSet = true;
}
if (rsp.HasMember("FailReason") && !rsp["FailReason"].IsNull())
{
if (!rsp["FailReason"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FailReason` IsString=false incorrectly").SetRequestId(requestId));
}
m_failReason = string(rsp["FailReason"].GetString());
m_failReasonHasBeenSet = true;
}
if (rsp.HasMember("UserEnvId") && !rsp["UserEnvId"].IsNull())
{
if (!rsp["UserEnvId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserEnvId` IsString=false incorrectly").SetRequestId(requestId));
}
m_userEnvId = string(rsp["UserEnvId"].GetString());
m_userEnvIdHasBeenSet = true;
}
if (rsp.HasMember("StartTime") && !rsp["StartTime"].IsNull())
{
if (!rsp["StartTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `StartTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_startTime = string(rsp["StartTime"].GetString());
m_startTimeHasBeenSet = true;
}
if (rsp.HasMember("Steps") && !rsp["Steps"].IsNull())
{
if (!rsp["Steps"].IsArray())
return CoreInternalOutcome(Core::Error("response `Steps` is not array type"));
const rapidjson::Value &tmpValue = rsp["Steps"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
OneClickTaskStepInfo item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_steps.push_back(item);
}
m_stepsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_externalIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExternalId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_externalId.c_str(), allocator).Move(), allocator);
}
if (m_envIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EnvId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_envId.c_str(), allocator).Move(), allocator);
}
if (m_userUinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserUin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userUin.c_str(), allocator).Move(), allocator);
}
if (m_serverNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ServerName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_serverName.c_str(), allocator).Move(), allocator);
}
if (m_versionNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "VersionName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_versionName.c_str(), allocator).Move(), allocator);
}
if (m_createTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator);
}
if (m_stageHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Stage";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_stage.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator);
}
if (m_failReasonHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FailReason";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_failReason.c_str(), allocator).Move(), allocator);
}
if (m_userEnvIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserEnvId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userEnvId.c_str(), allocator).Move(), allocator);
}
if (m_startTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_stepsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Steps";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_steps.begin(); itr != m_steps.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetExternalId() const
{
return m_externalId;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::ExternalIdHasBeenSet() const
{
return m_externalIdHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetEnvId() const
{
return m_envId;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::EnvIdHasBeenSet() const
{
return m_envIdHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetUserUin() const
{
return m_userUin;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::UserUinHasBeenSet() const
{
return m_userUinHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetServerName() const
{
return m_serverName;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::ServerNameHasBeenSet() const
{
return m_serverNameHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetVersionName() const
{
return m_versionName;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::VersionNameHasBeenSet() const
{
return m_versionNameHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetCreateTime() const
{
return m_createTime;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetStage() const
{
return m_stage;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::StageHasBeenSet() const
{
return m_stageHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetStatus() const
{
return m_status;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetFailReason() const
{
return m_failReason;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::FailReasonHasBeenSet() const
{
return m_failReasonHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetUserEnvId() const
{
return m_userEnvId;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::UserEnvIdHasBeenSet() const
{
return m_userEnvIdHasBeenSet;
}
string DescribeCloudBaseRunOneClickTaskExternalResponse::GetStartTime() const
{
return m_startTime;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
vector<OneClickTaskStepInfo> DescribeCloudBaseRunOneClickTaskExternalResponse::GetSteps() const
{
return m_steps;
}
bool DescribeCloudBaseRunOneClickTaskExternalResponse::StepsHasBeenSet() const
{
return m_stepsHasBeenSet;
}
| 32.298673 | 129 | 0.674978 | [
"object",
"vector",
"model"
] |
efd75b5c809f7ee4aab2f683ae6da32b8e52959b | 17,222 | cc | C++ | sdk/predictor/predictor_sdk_thrift_api.cc | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | 2 | 2021-06-29T13:42:22.000Z | 2021-09-06T10:57:34.000Z | sdk/predictor/predictor_sdk_thrift_api.cc | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | null | null | null | sdk/predictor/predictor_sdk_thrift_api.cc | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | 5 | 2021-06-29T13:42:26.000Z | 2022-02-08T02:41:34.000Z | #include "predictor_client_sdk.h"
#include "predictor_sdk_util.h"
#include "common/serialize_util.h"
#include "folly/GLog.h"
#include "folly/Random.h"
#include "folly/init/Init.h"
#include "gflags/gflags.h"
#include "gflags/gflags_declare.h"
#include "feature_master/if/gen-cpp2/feature_master_types.tcc"
#include "predictor/if/gen-cpp2/predictor_types.tcc"
#include "predictor/if/gen-cpp2/PredictorService.h"
#include "predictor/if/gen-cpp2/PredictorServiceAsyncClient.h"
#include "service_router/http.h"
#include "service_router/thrift.h"
#include <dirent.h>
#include <sstream>
#include <sys/types.h>
namespace service_router {
DECLARE_string(router_consul_addresses);
DECLARE_int32(thrift_timeout_retry);
DECLARE_int32(thrift_connection_retry);
} // namespace service_router
namespace predictor {
std::vector<PredictResponse> PredictResponsesThriftFutureImpl::get() {
// blocks until the async call is done
PredictResponses predict_responses;
try {
predict_responses = fut_ptr->get();
} catch (const std::exception& e) {
std::stringstream err_msg;
err_msg << typeid(e).name() << ":" << e.what() << " req_ids: " << req_ids;
LOG(ERROR) << SDK_MODULE_NAME << " fut_ptr->get() (thrift future_predict) caught exception: " << err_msg.str();
markMeters(ASYNC_GET_EXCEPTION_METER, channel_model_names, service_name);
return {};
}
// pack response
const std::vector<PredictResponse>& responses = predict_responses.get_resps();
if (responses.empty()) {
LOG(ERROR) << SDK_MODULE_NAME << " Got back empty responses (thrift future_predict). req_ids: " << req_ids;
markMeters(ASYNC_GET_EMPTY_RESP_METER, channel_model_names, service_name);
return {};
}
return responses;
}
MultiPredictResponse MultiPredictResponseFutureImpl::get() {
// blocks until the async call is done
MultiPredictResponse predict_response;
try {
predict_response = fut_ptr->get();
} catch (const std::exception& e) {
std::stringstream err_msg;
err_msg << typeid(e).name() << ":" << e.what() << " req_id: " << req_id;
LOG(ERROR) << SDK_MODULE_NAME << " fut_ptr->get() (multi_predict) caught exception: " << err_msg.str();
markMeters(ASYNC_GET_EXCEPTION_METER, model_names, channel, service_name, request_type);
return {};
}
if (predict_response.get_model_responses().empty()) {
LOG(ERROR) << SDK_MODULE_NAME << " Got back empty responses (multi_predict). request id: " << req_id;
markMeters(ASYNC_GET_EMPTY_RESP_METER, model_names, channel, service_name, request_type);
return {};
}
return predict_response;
}
std::vector<CalculateVectorResponse> CalculateVectorResponsesThriftFuture::get() {
// blocks until the async call is done
CalculateVectorResponses calculate_vector_responses;
try {
calculate_vector_responses = fut_ptr->get();
} catch (const std::exception& e) {
std::stringstream err_msg;
err_msg << typeid(e).name() << ":" << e.what();
LOG(ERROR) << SDK_MODULE_NAME << " calculate_vector fut_ptr->get() (thrift) caught exception: " << err_msg.str();
markMeters(ASYNC_GET_EXCEPTION_METER, channel_model_names, service_name);
return {};
}
// pack response
const std::vector<CalculateVectorResponse>& responses = calculate_vector_responses.get_resps();
if (responses.empty()) {
LOG(ERROR) << SDK_MODULE_NAME << " calculate_vector Got back empty responses (thrift). req_ids: " << req_ids;
markMeters(ASYNC_GET_EMPTY_RESP_METER, channel_model_names, service_name);
return {};
}
return responses;
}
std::vector<CalculateBatchVectorResponse> CalculateBatchVectorResponsesThriftFuture::get() {
// blocks until the async call is done
CalculateBatchVectorResponses calculate_batch_vector_responses;
try {
calculate_batch_vector_responses = fut_ptr->get();
} catch (const std::exception& e) {
std::stringstream err_msg;
err_msg << typeid(e).name() << ":" << e.what();
LOG(ERROR) << SDK_MODULE_NAME
<< " calculate_batch_vector fut_ptr->get() (thrift) caught exception: "
<< err_msg.str();
markMeters(ASYNC_GET_EXCEPTION_METER, channel_model_names, service_name);
return {};
}
// pack response
const std::vector<CalculateBatchVectorResponse>& responses = calculate_batch_vector_responses.get_resps();
if (responses.empty()) {
LOG(ERROR)
<< SDK_MODULE_NAME
<< " calculate_batch_vector Got back empty responses (thrift). request ids: "
<< req_ids;
markMeters(ASYNC_GET_EMPTY_RESP_METER, channel_model_names, service_name);
return {};
}
return responses;
}
namespace client_util {
// make thrift feature from name and value
feature_master::Feature makeFeature(const std::string& name, int64_t value) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::INT64_LIST);
feature.set_int64_values(std::vector<int64_t>{value});
return feature;
}
feature_master::Feature makeFeature(const std::string& name, double value) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::FLOAT_LIST);
feature.set_float_values(std::vector<double>{value});
return feature;
}
feature_master::Feature makeFeature(const std::string& name, const std::string& value) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::STRING_LIST);
feature.set_string_values(std::vector<std::string>{value});
return feature;
}
feature_master::Feature makeFeature(const std::string& name, const std::vector<int64_t>& value_vec) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::INT64_LIST);
feature.set_int64_values(value_vec);
return feature;
}
feature_master::Feature makeFeature(const std::string& name, const std::vector<double>& value_vec) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::FLOAT_LIST);
feature.set_float_values(value_vec);
return feature;
}
feature_master::Feature makeFeature(const std::string& name, const std::vector<std::string>& value_vec) {
feature_master::Feature feature;
feature.set_feature_name(name);
feature.set_feature_type(feature_master::FeatureType::STRING_LIST);
feature.set_string_values(value_vec);
return feature;
}
} // namespace client_util
// sync interface
bool PredictorClientSDK::predict(std::vector<PredictResponse>* responses,
const PredictRequests& requests) {
const auto& request_option = requests.get_request_option();
const auto &reqs = requests.get_reqs();
markMeters(SYNC_REQ_METER, reqs, request_option.predictor_service_name);
PredictResponses predict_responses;
// client predict
const bool rc = service_router::thriftServiceCall<PredictorServiceAsyncClient>(
makeServiceRouterClientOption(request_option),
[&requests, &predict_responses, &request_option](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
client->sync_predict(rpc_options, predict_responses, requests);
} catch (PredictException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << SDK_MODULE_NAME << " Failed calling predictor service (thrift predict). req_ids: "
<< getReqIds(reqs);
markMeters(SYNC_PREDICT_ERROR, reqs, request_option.predictor_service_name);
return false;
}
// pack response
if (predict_responses.get_resps().empty()) {
LOG(ERROR) << SDK_MODULE_NAME << " Got back empty responses (thrift predict). req_ids: "
<< getReqIds(reqs);
markMeters(SYNC_PREDICT_EMPTY, reqs, request_option.predictor_service_name);
} else {
*responses = std::move(predict_responses.get_resps());
}
return true;
}
// async interface
bool PredictorClientSDK::future_predict(std::unique_ptr<PredictResponsesThriftFuture>* response_future,
const PredictRequests& requests) {
const auto& request_option = requests.get_request_option();
const auto &reqs = requests.get_reqs();
markMeters(ASYNC_REQ_METER, reqs, request_option.predictor_service_name);
// client predict
const bool rc = service_router::thriftServiceCall<PredictorServiceAsyncClient>(
makeServiceRouterClientOption(request_option),
[&requests, &response_future, &request_option, &reqs](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
auto fut_impl = std::make_unique<PredictResponsesThriftFutureImpl>();
fut_impl->fut_ptr = std::move(std::make_unique<folly::Future<PredictResponses>>(
client->future_predict(rpc_options, requests)));
fut_impl->req_ids = getReqIds(reqs);
fut_impl->service_name = request_option.predictor_service_name;
for (const auto& req : reqs) {
fut_impl->channel_model_names.emplace_back(req.get_channel(), req.get_model_name());
}
*response_future = std::move(fut_impl);
} catch (PredictException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << "Failed calling predictor service (thrift future_predict). req_ids: " << getReqIds(reqs);
markMeters(ASYNC_ERROR_METER, reqs, request_option.predictor_service_name);
return false;
}
return true;
}
// multi_predict interface
bool PredictorClientSDK::multi_predict(MultiPredictResponse* response,
const MultiPredictRequest& request) {
const auto &request_option = request.get_request_option();
markMeters(ASYNC_REQ_METER, request.get_model_names(), request.get_single_request().get_channel(),
request_option.predictor_service_name);
// client predict
const bool rc = service_router::thriftServiceCall<PredictorServiceAsyncClient>(
makeServiceRouterClientOption(request_option),
[&request, &response, &request_option](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
client->sync_multiPredict(rpc_options, *response, request);
} catch (PredictException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << SDK_MODULE_NAME << " Failed calling predictor service (multi_predict). request id: "
<< request.get_req_id();
markMeters(SYNC_PREDICT_ERROR, request.get_model_names(), request.get_single_request().get_channel(),
request_option.predictor_service_name);
return false;
}
// pack response
if (response->get_model_responses().empty()) { // empty response considered call success
LOG(ERROR) << SDK_MODULE_NAME << " Got back empty responses (multi_predict). request id: "
<< request.get_req_id();
markMeters(SYNC_PREDICT_EMPTY, request.get_model_names(), request.get_single_request().get_channel(),
request_option.predictor_service_name);
}
return true;
}
// future_multi_predict interface
bool PredictorClientSDK::future_multi_predict(std::unique_ptr<MultiPredictResponseFuture>* response_future,
const MultiPredictRequest &request) {
const std::string request_type = getRequestType(request.single_request.get_context());
const auto &request_option = request.get_request_option();
markMeters(ASYNC_REQ_METER, request.get_model_names(), request.get_single_request().get_channel(),
request_option.predictor_service_name, request_type);
// client predict
const bool rc = service_router::thriftServiceCall<PredictorServiceAsyncClient>(
makeServiceRouterClientOption(request_option),
[&request, &response_future, &request_option, &request_type](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
auto fut_impl = std::make_unique<MultiPredictResponseFutureImpl>();
fut_impl->fut_ptr = std::move(std::make_unique<folly::Future<MultiPredictResponse>>(
client->future_multiPredict(rpc_options, request)));
fut_impl->req_id = request.get_req_id();
fut_impl->service_name = request_option.predictor_service_name;
fut_impl->request_type = request_type;
fut_impl->model_names = request.get_model_names();
fut_impl->channel = request.get_single_request().get_channel();
*response_future = std::move(fut_impl);
} catch (PredictException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << "caught PredictException: " << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << "Failed calling predictor: api=multi_predict req_id=" << request.get_req_id();
markMeters(ASYNC_ERROR_METER, request.get_model_names(), request.get_single_request().get_channel(),
request_option.predictor_service_name, request_type);
return false;
}
return true;
}
bool PredictorClientSDK::future_calculate_vector(
std::unique_ptr<CalculateVectorResponsesThriftFuture>* response_future,
const CalculateVectorRequests& requests) {
const auto &reqs = requests.get_reqs();
const auto &request_option = requests.get_request_option();
markMeters(ASYNC_REQ_METER, reqs, request_option.predictor_service_name);
// client predict
const bool rc = service_router::thriftServiceCall<PredictorServiceAsyncClient>(
makeServiceRouterClientOption(request_option),
[&requests, &response_future, &request_option, &reqs](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
auto fut_impl = std::make_unique<CalculateVectorResponsesThriftFuture>();
fut_impl->fut_ptr = std::move(std::make_unique<folly::Future<CalculateVectorResponses>>(
client->future_calculateVector(rpc_options, requests)));
fut_impl->req_ids = getReqIds(reqs);
fut_impl->service_name = request_option.predictor_service_name;
for (const auto& req : reqs) {
fut_impl->channel_model_names.emplace_back(req.get_channel(), req.get_model_name());
}
*response_future = std::move(fut_impl);
} catch (CalculateVectorException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << "Failed calling predictor service calculateVector (async thrift). req_ids: " << getReqIds(reqs);
markMeters(ASYNC_ERROR_METER, reqs, request_option.predictor_service_name);
return false;
}
return true;
}
bool PredictorClientSDK::future_calculate_batch_vector(
std::unique_ptr<CalculateBatchVectorResponsesThriftFuture>* batch_responses_future,
const CalculateBatchVectorRequests& batch_requests) {
const auto &reqs = batch_requests.get_reqs();
const auto& request_option = batch_requests.get_request_option();
markMeters(ASYNC_REQ_METER, reqs, request_option.predictor_service_name);
// client predict
service_router::ClientOption option = makeServiceRouterClientOption(request_option);
const bool rc = service_router::thriftServiceCall<
PredictorServiceAsyncClient>(
option,
[&batch_requests, &batch_responses_future,
&request_option, &reqs](auto client) {
apache::thrift::RpcOptions rpc_options;
rpc_options.setTimeout(std::chrono::milliseconds(request_option.request_timeout));
try {
auto fut_impl = std::make_unique<CalculateBatchVectorResponsesThriftFuture>();
fut_impl->fut_ptr = std::move(std::make_unique<folly::Future<CalculateBatchVectorResponses>>(
client->future_calculateBatchVector(rpc_options, batch_requests)));
fut_impl->req_ids = getReqIds(reqs);
fut_impl->service_name = request_option.predictor_service_name;
for (const auto& batch_request : batch_requests.get_reqs()) {
fut_impl->channel_model_names.emplace_back(std::make_pair(batch_request.get_channel(),
batch_request.get_model_name()));
}
*batch_responses_future = std::move(fut_impl);
} catch (CalculateVectorException& ex) {
FB_LOG_EVERY_MS(ERROR, 2000) << ex.get_message();
throw ex;
}
});
if (!rc) {
LOG(ERROR) << "Failed calling predictor service calculateBatchVector (batch "
"async thrift). request ids: " << getReqIds(reqs);
markMeters(ASYNC_ERROR_METER, reqs, request_option.predictor_service_name);
return false;
}
return true;
}
} // namespace predictor
| 44.158974 | 117 | 0.713796 | [
"vector"
] |
efdd9998ed4c5b15f11d95a0dac53444daad92d1 | 38,511 | cpp | C++ | app/vcc.cpp | darrenstrash/ReduVCC | 89221c13608826778cfd5f1c94b522098764b17c | [
"MIT"
] | 2 | 2021-11-08T14:54:03.000Z | 2021-11-08T17:40:26.000Z | app/vcc.cpp | darrenstrash/ReduVCC | 89221c13608826778cfd5f1c94b522098764b17c | [
"MIT"
] | null | null | null | app/vcc.cpp | darrenstrash/ReduVCC | 89221c13608826778cfd5f1c94b522098764b17c | [
"MIT"
] | null | null | null |
/******************************************************************************
* vcc.cpp
* *
* Source of ReduVCC
* Darren Strash <dstrash@hamilton.edu>
* Louise Thompson <lmthomps@hamilton.edu>
*****************************************************************************/
#include <argtable3.h>
#include <iostream>
#include <fstream>
#include <math.h>
#include <regex.h>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <utility> // for std::pair
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <climits>
#ifdef BETA
#include <boost/functional/hash.hpp>
#endif // BETA
#include "balance_configuration.h"
#include "data_structure/graph_access.h"
#include "data_structure/matrix/normal_matrix.h"
#include "data_structure/matrix/online_distance_matrix.h"
#include "graph_io.h"
#include "macros_assertions.h"
#include "mapping/mapping_algorithms.h"
#include "parse_parameters.h"
#include "partition/graph_partitioner.h"
#include "partition/partition_config.h"
#include "partition/uncoarsening/refinement/cycle_improvements/cycle_refinement.h"
#include "quality_metrics.h"
#include "random_functions.h"
#include "timer.h"
#include "mis/initial_mis/greedy_mis.h"
#include "mis/kernel/branch_and_reduce_algorithm.h"
#include "ccp/Chalupa/cli.h"
#include <time.h>
#include "redu_vcc/redu_vcc.h"
#include "redu_vcc/reducer.h"
#include "branch_and_reduce/b_and_r.h"
#include "sigmod_mis/Graph.h"
#include "mis/mis_config.h"
#ifdef BETA
namespace std
{
template<> struct hash<std::pair<NodeID,NodeID>>
{
std::size_t operator()(std::pair<NodeID,NodeID> const & node_pair) const noexcept
{
std::size_t seed = 0;
boost::hash_combine(seed, std::get<0>(node_pair));
boost::hash_combine(seed, std::get<1>(node_pair));
return seed;
}
};
};
void transform_graph(graph_access const &G,
graph_access &transformed_graph,
std::vector<std::pair<NodeID,NodeID>> &vertex_to_edge) {
// Step 1: acyclic orientation
std::vector<NodeID> order;
order.reserve(G.number_of_nodes());
for (NodeID node = 0; node < G.number_of_nodes(); node++) {
order.push_back(node);
}
// Step 2: line graph
std::unordered_set<std::pair<NodeID,NodeID>> neighbor_hash(G.number_of_edges());
forall_nodes(G, v) {
forall_out_edges(G, e, v) {
NodeID u = G.getEdgeTarget(e);
neighbor_hash.insert(std::pair<NodeID,NodeID>(u,v));
neighbor_hash.insert(std::pair<NodeID,NodeID>(v,u));
} endfor
} endfor
vertex_to_edge.clear();
vertex_to_edge.reserve(G.number_of_edges() / 2);
std::unordered_map<std::pair<NodeID, NodeID>, NodeID> edge_to_vertex(G.number_of_edges() / 2);
std::vector<std::vector<NodeID>> edge_to_edges(G.number_of_edges() / 2);
std::vector<NodeID> const empty;
std::cout << "Making transformed graph..." << std::endl;
std::size_t full_num_edges = 0;
forall_nodes(G, v) {
forall_out_edges(G, e, v) {
NodeID u = G.getEdgeTarget(e);
std::pair<NodeID,NodeID> node_pair(u, v);
if (order[v] < order[u]) {
node_pair = std::pair<NodeID,NodeID>(v, u);
}
if (edge_to_vertex.find(node_pair) == edge_to_vertex.end()) {
vertex_to_edge.push_back(node_pair);
edge_to_vertex[node_pair] = vertex_to_edge.size() - 1;
//edge_to_edges.push_back(empty);
}
} endfor
forall_out_edges(G, e1, v) {
NodeID u = G.getEdgeTarget(e1);
std::pair<NodeID,NodeID> first_pair(v, u);
if (order[u] < order[v]) {
first_pair = std::pair<NodeID,NodeID>(u, v);
}
forall_out_edges(G, e2, v) {
NodeID w = G.getEdgeTarget(e2);
if (w < u) continue;
if (w == u) continue;
std::pair<NodeID,NodeID> second_pair(v, w);
if (order[w] < order[v]) {
second_pair = std::pair<NodeID,NodeID>(w, v);
}
bool bad = std::get<0>(first_pair) == std::get<0>(second_pair);
std::pair<NodeID,NodeID> const bad_edge =
std::pair<NodeID,NodeID>(std::get<1>(first_pair), std::get<1>(second_pair));
bad = bad and (neighbor_hash.find(bad_edge) != neighbor_hash.end());
if (bad) continue;
// Step 3: filter triples, TODO/DS: appears to work
edge_to_edges[edge_to_vertex[first_pair]].push_back(edge_to_vertex[second_pair]);
edge_to_edges[edge_to_vertex[second_pair]].push_back(edge_to_vertex[first_pair]);
full_num_edges++;
} endfor
} endfor
} endfor
// Step 3: trim triples (integrated above)
std::cout << "Sorting neighborhoods..." << std::endl;
std::size_t num_edges = 0;
for (std::vector<NodeID> &neighbors : edge_to_edges) {
std::sort(neighbors.begin(), neighbors.end());
num_edges += neighbors.size();
}
num_edges /= 2;
std::cout << "Transformed Graph has " << edge_to_edges.size() << " vertices and " << num_edges << " edges" << std::endl;
std::cout << "Constructing graph_access data structure..." << std::endl;
transformed_graph.start_construction(edge_to_edges.size(), 2 * num_edges);
for (NodeID v = 0; v < edge_to_edges.size(); v++) {
NodeID shadow_node = transformed_graph.new_node();
transformed_graph.setPartitionIndex(shadow_node, 0);
transformed_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : edge_to_edges[v]) {
EdgeID shadow_edge = transformed_graph.new_edge(shadow_node, neighbor);
transformed_graph.setEdgeWeight(shadow_edge, 1);
}
}
transformed_graph.finish_construction();
//graph_io::writeGraph(transformed_graph, "transformed.graph");
//graph_access new_transformed_graph;
//graph_io::readGraphWeighted(new_transformed_graph, "transformed-sorted.graph");
}
void transform_is_to_clique_cover(
graph_access &transformed_graph,
std::vector<std::pair<NodeID, NodeID>> const &vertex_to_edge,
std::size_t const num_vertices_original_graph,
NodeID *solution_is,
std::size_t const num_cliques,
std::vector<std::vector<int>> &clique_cover) {
std::cout << "Reconstructing clique cover..." << std::endl;
clique_cover.clear();
clique_cover.reserve(num_cliques);
unordered_map<NodeID, NodeID> vertex_to_clique_id(num_cliques);
std::vector<bool> covered(num_vertices_original_graph, false);
forall_nodes(transformed_graph, v) {
if (solution_is[v] == 1) {
std::pair<NodeID,NodeID> const &edge = vertex_to_edge[v];
//std::cout << "Edge " << std::get<0>(edge) << "," << std::get<1>(edge)
// << " is in the independent set" << std::endl;
if (vertex_to_clique_id.find(std::get<0>(edge))
== vertex_to_clique_id.end()) {
vertex_to_clique_id[std::get<0>(edge)] = clique_cover.size();
clique_cover.push_back(std::vector<int>{std::get<0>(edge)});
covered[std::get<0>(edge)] = true;
}
clique_cover[vertex_to_clique_id[std::get<0>(edge)]].push_back(std::get<1>(edge));
covered[std::get<1>(edge)] = true;
}
} endfor
for (NodeID v = 0; v < num_vertices_original_graph; v++) {
if (!covered[v]) {
//std::cout << "DS: Vertex " << v << " is uncovered...covering with singleton" << std::endl;
clique_cover.emplace_back(std::vector<int>{v});
}
}
std::cout << "clique_cover has size: " << clique_cover.size() << std::endl;
}
void run_ils(ils &ils_instance,
PartitionConfig const &partition_config,
graph_access &graph,
timer &the_timer,
std::size_t const is_offset) {
std::cout << "Performing ILS..." << std::endl;
MISConfig ils_config;
ils_config.seed = partition_config.seed;
ils_config.time_limit = partition_config.solver_time_limit;
ils_config.force_cand = 4;
ils_config.ils_iterations = UINT_MAX;
ils_instance.perform_ils(ils_config, graph, ils_config.ils_iterations,
the_timer.elapsed(), is_offset, partition_config.mis);
}
void run_peeling(graph_access &graph,
graph_access &peeled_graph,
std::vector<NodeID> &new_to_old_id,
std::size_t &cover_offset) {
Graph mis_G;
mis_G.read_graph(graph);
std::vector<std::vector<NodeID>> kernel;
cover_offset = 0;
std::cout << "Running peeling..." << endl;
std::vector<bool> in_initial_is;
unsigned int res_mis = mis_G.near_linear_kernel_and_offset(kernel, new_to_old_id, in_initial_is, cover_offset);
std::cout << " Reduced " << graph.number_of_nodes() << " -> " << kernel.size() << " nodes" << std::endl;
std::cout << " Offset = " << cover_offset << std::endl;
std::size_t num_edges = 0;
for (std::vector<NodeID> & neighbors : kernel) {
std::sort(neighbors.begin(), neighbors.end());
num_edges += neighbors.size();
}
num_edges /= 2;
peeled_graph.set_partition_count(2);
peeled_graph.start_construction(kernel.size(), 2 * num_edges);
for (NodeID v = 0; v < kernel.size(); v++) {
NodeID shadow_node = peeled_graph.new_node();
peeled_graph.setPartitionIndex(shadow_node, in_initial_is[v] ? 1 : 0);
peeled_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : kernel[v]) {
EdgeID shadow_edge = peeled_graph.new_edge(shadow_node, neighbor);
peeled_graph.setEdgeWeight(shadow_edge, 1);
}
}
peeled_graph.finish_construction();
}
#endif // BETA
int main(int argn, char **argv) {
PartitionConfig partition_config;
std::string graph_filename;
bool is_graph_weighted = false;
bool suppress_output = false;
bool recursive = false;
int ret_code = parse_parameters(argn, argv,
partition_config,
graph_filename,
is_graph_weighted,
suppress_output, recursive);
if(ret_code) {
return 0;
}
std::streambuf* backup = std::cout.rdbuf();
std::ofstream ofs;
ofs.open("/dev/null");
if(suppress_output) {
std::cout.rdbuf(ofs.rdbuf());
}
partition_config.LogDump(stdout);
graph_access G;
timer t;
graph_io::readGraphWeighted(G, graph_filename);
timer s;
if (partition_config.run_type == "Chalupa") {
timer total_timer;
redu_vcc reduVCC(G);
reduVCC.build_cover();
double time_to_solution = 0.0;
reduVCC.solveKernel(partition_config, total_timer, time_to_solution, 0 /* clique cover offset */);
reduVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "input_graph_vertices=" << G.number_of_nodes() << std::endl;
std::cout << "input_graph_edges=" << G.number_of_edges() / 2 << std::endl;
std::cout << "total_time_to_best=" << time_to_solution << std::endl;
std::cout << "clique_cover_size=" << reduVCC.clique_cover.size() << std::endl;
std::cout << "verified_cover=" << (reduVCC.validateCover(G) ? "passed" : "failed") << std::endl;
std::cout << "optimal=" << (reduVCC.clique_cover.size() == partition_config.mis ? "yes" : "unknown") << std::endl;
return 0;
}
else if (partition_config.run_type == "Redu") {
redu_vcc reduVCC(G);
std::vector<unsigned int> iso_degree;
iso_degree.assign(G.number_of_nodes(), 0);
std::vector<unsigned int> dom_degree;
dom_degree.assign(G.number_of_nodes(), 0);
reducer R;
R.exhaustive_reductions(reduVCC, iso_degree, dom_degree);
reduVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
return 0;
} else if (partition_config.run_type == "ReduVCC") {
redu_vcc reduVCC(G);
std::vector<unsigned int> iso_degree;
iso_degree.assign(G.number_of_nodes(), 0);
std::vector<unsigned int> dom_degree;
dom_degree.assign(G.number_of_nodes(), 0);
reducer R;
R.exhaustive_reductions(reduVCC, iso_degree, dom_degree);
reduVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
reduVCC.build_cover();
std::cout << "cover build" << std::endl;
double time_to_solution = 0.0;
reduVCC.solveKernel(partition_config, s, time_to_solution, R.get_cover_size_offset());
std::cout << "kernel solve" << std::endl;
timer unwind_timer;
R.unwindReductions(reduVCC, time_to_solution);
std::cout << "unwind redutions" << std::endl;
double time_to_unwind = unwind_timer.elapsed();
reduVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "input_graph_vertices=" << G.number_of_nodes() << std::endl;
std::cout << "input_graph_edges=" << G.number_of_edges() / 2 << std::endl;
std::cout << "reduced_graph_vertices=" << reduVCC.kernel_adj_list.size() << std::endl;
std::cout << "reduced_graph_edges=" << reduVCC.kernel_edges << std::endl;
std::cout << "total_time_to_best=" << time_to_solution << std::endl;
std::cout << "time_to_best_without_unwind=" << time_to_solution - time_to_unwind << std::endl;
std::cout << "clique_cover_size=" << reduVCC.clique_cover.size() << std::endl;
std::cout << "verified_cover=" << (reduVCC.validateCover(G) ? "passed" : "failed") << std::endl;
std::cout << "optimal=" << (reduVCC.clique_cover.size() == partition_config.mis ? "yes" : "unknown") << std::endl;
return 0;
}
#ifdef BETA
else if (partition_config.run_type == "transform") {
timer transformation_timer;
// Step 1: acyclic orientation
std::vector<NodeID> order;
order.reserve(G.number_of_nodes());
for (NodeID node = 0; node < G.number_of_nodes(); node++) {
order.push_back(node);
}
// Step 2: line graph
std::unordered_set<std::pair<NodeID,NodeID>> neighbor_hash;
forall_nodes(G, v) {
forall_out_edges(G, e, v) {
NodeID u = G.getEdgeTarget(e);
neighbor_hash.insert(std::pair<NodeID,NodeID>(u,v));
neighbor_hash.insert(std::pair<NodeID,NodeID>(v,u));
} endfor
} endfor
std::unordered_map<std::pair<NodeID, NodeID>, NodeID> edge_to_vertex;
std::vector<std::pair<NodeID, NodeID>> vertex_to_edge;
std::vector<std::vector<NodeID>> edge_to_edges;
std::vector<NodeID> const empty;
std::cout << "Making filtered line graph..." << std::endl;
std::size_t full_num_edges = 0;
forall_nodes(G, v) {
forall_out_edges(G, e, v) {
NodeID u = G.getEdgeTarget(e);
std::pair<NodeID,NodeID> node_pair(u, v);
if (order[v] < order[u]) {
node_pair = std::pair<NodeID,NodeID>(v, u);
}
if (edge_to_vertex.find(node_pair) == edge_to_vertex.end()) {
vertex_to_edge.push_back(node_pair);
edge_to_vertex[node_pair] = vertex_to_edge.size() - 1;
edge_to_edges.push_back(empty);
}
} endfor
forall_out_edges(G, e1, v) {
NodeID u = G.getEdgeTarget(e1);
std::pair<NodeID,NodeID> first_pair(v, u);
if (order[u] < order[v])
first_pair = std::pair<NodeID,NodeID>(u, v);
forall_out_edges(G, e2, v) {
NodeID w = G.getEdgeTarget(e2);
if (w <= u) continue;
std::pair<NodeID,NodeID> second_pair(v, w);
if (order[w] < order[v]) {
second_pair = std::pair<NodeID,NodeID>(w, v);
}
// Step 3: filter triples, TODO/DS: appears to work
if (std::get<0>(first_pair) == std::get<0>(second_pair) &&
(neighbor_hash.find(std::pair<NodeID,NodeID>(std::get<1>(first_pair),std::get<1>(second_pair))) != neighbor_hash.end()) &&
(neighbor_hash.find(std::pair<NodeID,NodeID>(std::get<1>(second_pair),std::get<1>(first_pair))) != neighbor_hash.end())) continue;
edge_to_edges[edge_to_vertex[first_pair]].push_back(edge_to_vertex[second_pair]);
edge_to_edges[edge_to_vertex[second_pair]].push_back(edge_to_vertex[first_pair]);
full_num_edges++;
} endfor
} endfor
} endfor
// Step 3: trim triples (integrated above)
double transformation_time = transformation_timer.elapsed();
// Step 4: Compute MIS
if (false) // just peeling
{
Graph mis_G;
mis_G.read_graph(edge_to_edges);
unsigned int res_mis = mis_G.degree_two_kernal_dominate_lp_and_remove_max_degree_without_contraction();
std::size_t const cover_upper_bound = G.number_of_nodes() - res_mis;
std::cout << "Original Graph = " << G.number_of_nodes() << ", MIS=" << res_mis << std::endl;
std::cout << "Transform (Near Linear) Upper Bound = " << cover_upper_bound << std::endl;
}
if (false) // just ILS
{
std::size_t num_edges = 0;
for (std::vector<NodeID> &neighbors : edge_to_edges) {
std::sort(neighbors.begin(), neighbors.end());
num_edges += neighbors.size();
}
num_edges /= 2;
std::cout << "Graph has " << edge_to_edges.size() << " vertices and " << num_edges << " edges" << std::endl;
std::cout << "Constructing graph_access data structure..." << std::endl;
graph_access new_graph;
new_graph.start_construction(edge_to_edges.size(), 2 * num_edges);
for (NodeID v = 0; v < edge_to_edges.size(); v++) {
NodeID shadow_node = new_graph.new_node();
new_graph.setPartitionIndex(shadow_node, 0);
new_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : edge_to_edges[v]) {
EdgeID shadow_edge = new_graph.new_edge(shadow_node, neighbor);
new_graph.setEdgeWeight(shadow_edge, 1);
}
}
new_graph.finish_construction();
//graph_io::writeGraph(new_graph, "transformed.graph");
//graph_access new_new_graph;
//graph_io::readGraphWeighted(new_new_graph, "transformed-sorted.graph");
timer ils_timer;
greedy_mis greedy;
greedy.initial_partition(partition_config.seed, new_graph);
std::cout << "Preparing ILS..." << std::endl;
MISConfig ils_config;
ils_config.seed = partition_config.seed;
ils_config.time_limit = partition_config.solver_time_limit;
ils_config.force_cand = 4;
ils_config.ils_iterations = UINT_MAX;
ils ils_instance;
std::cout << "Performing ILS..." << std::endl;
ils_instance.perform_ils(ils_config, new_graph, ils_config.ils_iterations);
cout << "ILS Running time: " << ils_timer.elapsed() << std::endl;
std::size_t const ils_cover = G.number_of_nodes() - ils_instance.get_best_solution_size();
std::cout << "Transform (ILS) Upper Bound = " << ils_cover << std::endl;
}
if (false) // just branch-and-reduce
{
std::cout << "Building a sorted int version of adjacency list..." << std::endl;
vector<vector<int>> adjlist(edge_to_edges.size());
for (NodeID v = 0; v < edge_to_edges.size(); v++) {
std::sort(edge_to_edges[v].begin(), edge_to_edges[v].end());
adjlist[v].reserve(edge_to_edges[v].size());
for (NodeID const neighbor : edge_to_edges[v])
adjlist[v].push_back(neighbor);
}
branch_and_reduce_algorithm mis_bnr(adjlist, adjlist.size());
timer bnr_timer;
bool timeout = mis_bnr.solve(bnr_timer, partition_config.solver_time_limit) == -1;
std::size_t const exact_cover = G.number_of_nodes() - mis_bnr.get_current_is_size();
std::cout << "BNR Running time: " << bnr_timer.elapsed() << std::endl;
std::cout << "Transform (BNR) Upper Bound = " << exact_cover << std::endl;
std::cout << " Upper bound is " << (timeout ? "inexact" : "exact") << endl;
}
if (true) // peeling + ILS
{
timer total_timer;
Graph mis_G;
mis_G.read_graph(edge_to_edges);
std::vector<std::vector<NodeID>> kernel;
std::size_t offset = 0;
std::cout << "Running reducing-peeling..." << endl;
std::vector<bool> in_initial_is;
timer peeling_timer;
std::vector<NodeID> new_to_old_id_unused;
unsigned int res_mis = mis_G.near_linear_kernel_and_offset(kernel, new_to_old_id_unused, in_initial_is, offset);
double peeling_time = peeling_timer.elapsed();
std::cout << "Done with reducing-peeling..." << endl;
std::cout << " Reduced " << edge_to_edges.size() << " -> " << kernel.size() << " nodes" << std::endl;
std::cout << " Offset = " << offset << std::endl;
std::size_t num_edges = 0;
for (std::vector<NodeID> & neighbors : kernel) {
std::sort(neighbors.begin(), neighbors.end());
num_edges += neighbors.size();
}
num_edges /= 2;
graph_access new_graph;
new_graph.set_partition_count(2);
new_graph.start_construction(kernel.size(), 2 * num_edges);
for (NodeID v = 0; v < kernel.size(); v++) {
NodeID shadow_node = new_graph.new_node();
new_graph.setPartitionIndex(shadow_node, in_initial_is[v] ? 1 : 0);
new_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : kernel[v]) {
EdgeID shadow_edge = new_graph.new_edge(shadow_node, neighbor);
new_graph.setEdgeWeight(shadow_edge, 1);
}
}
new_graph.finish_construction();
timer ils_timer;
MISConfig ils_config;
ils_config.seed = partition_config.seed;
ils_config.time_limit = partition_config.solver_time_limit;
ils_config.force_cand = 4;
ils_config.ils_iterations = UINT_MAX;
ils ils_instance;
std::size_t solution_offset = G.number_of_nodes() - offset;
ils_instance.perform_ils(ils_config, new_graph, ils_config.ils_iterations, total_timer.elapsed(), solution_offset, partition_config.mis);
cout << "ILS Running time: " << ils_timer.elapsed() << std::endl;
std::size_t const near_linear_ils_cover = G.number_of_nodes() - (ils_instance.get_best_solution_size() + offset);
std::cout << "Transform (Near Linear / ILS) Upper Bound = " << near_linear_ils_cover << std::endl;
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "transformation_time=" << transformation_time << std::endl;
std::cout << "transformed_graph_vertices=" << edge_to_edges.size() << std::endl;
std::cout << "transformed_graph_edges=" << full_num_edges << std::endl;
std::cout << "peeling_time=" << peeling_time << std::endl;
std::cout << "reduced_transformed_graph_vertices=" << new_graph.number_of_nodes() << std::endl;
std::cout << "reduced_transformed_graph_edges=" << new_graph.number_of_edges() / 2 << std::endl;
std::cout << "ils_time_to_best=" << ils_instance.get_last_update_time() << std::endl;
std::cout << "total_time_to_best=" << ils_instance.get_last_total_update_time() << std::endl;
std::cout << "clique_cover_size=" << near_linear_ils_cover << std::endl;
std::cout << "verified_cover=no" << std::endl;
std::cout << "optimal=" << (near_linear_ils_cover == partition_config.mis ? "yes":"unknown") << std::endl;
}
return 0;
} else if (partition_config.run_type == "Redutransform") {
timer total_timer;
timer vcc_reductions_timer;
redu_vcc oldVCC(G);
std::vector<unsigned int> iso_degree;
iso_degree.assign(G.number_of_nodes(), 0);
std::vector<unsigned int> dom_degree;
dom_degree.assign(G.number_of_nodes(), 0);
reducer R;
R.exhaustive_reductions(oldVCC, iso_degree, dom_degree);
oldVCC.build_cover();
std::size_t const cover_size_offset = R.get_cover_size_offset();
std::cout << "cover_size_offset=" << cover_size_offset << std::endl;
oldVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
double vcc_reduction_time = vcc_reductions_timer.elapsed();
oldVCC.buildKernel();
graph_access kernel_graph;
kernel_graph.start_construction(oldVCC.kernel_adj_list.size(), oldVCC.kernel_edges);
for (NodeID v = 0; v < oldVCC.kernel_adj_list.size(); v++) {
NodeID shadow_node = kernel_graph.new_node();
kernel_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : oldVCC.kernel_adj_list[v]) {
EdgeID shadow_edge = kernel_graph.new_edge(shadow_node, neighbor);
kernel_graph.setEdgeWeight(shadow_edge, 1);
}
}
kernel_graph.finish_construction();
timer transformation_timer;
graph_access transformed_graph;
std::vector<std::pair<NodeID, NodeID>> vertex_to_edge;
transform_graph(kernel_graph, transformed_graph, vertex_to_edge);
double transformation_time = transformation_timer.elapsed();
//graph_io::writeGraph(new_graph, "transformed.graph");
// Step 4: Compute MIS
if (true) // Exhaustive MIS Reductions + Sigmod + ILS
{
std::cout << "Making copy of transformed graph..." << std::endl;
std::vector<std::vector<int>> line_copy;
line_copy.reserve(transformed_graph.number_of_nodes());
forall_nodes(transformed_graph, v) {
std::vector<int> int_neighbors(transformed_graph.getNodeDegree(v));
forall_out_edges(transformed_graph, e, v) {
NodeID u = transformed_graph.getEdgeTarget(e);
int_neighbors.push_back(u);
} endfor
line_copy.emplace_back(int_neighbors);
} endfor
timer mis_reductions;
std::cout << "Initializing branch-and-reduce..." << std::endl;
branch_and_reduce_algorithm mis_bnr(line_copy, line_copy.size());
std::cout << "Applying exhaustive MIS reductions..." << std::endl;
mis_bnr.reduce();
std::cout << "After exhaustive MIS reductions: " << line_copy.size() << " -> " << mis_bnr.number_of_nodes_remaining() << std::endl;
std::vector<NodeID> reverse_mapping;
double mis_reduction_time = mis_reductions.elapsed();
graph_access full_kernel;
mis_bnr.convert_adj_lists(full_kernel, reverse_mapping);
std::cout << "Preparing ILS on full kernel of filtered line graph..." << std::endl;
Graph mis_G;
mis_G.read_graph(full_kernel);
std::vector<std::vector<NodeID>> kernel;
std::size_t offset = 0;
std::cout << "Running reducing-peeling..." << endl;
std::vector<bool> in_initial_is;
timer peeling_timer;
std::vector<NodeID> new_to_old_id;
unsigned int res_mis = mis_G.near_linear_kernel_and_offset(kernel, new_to_old_id, in_initial_is, offset);
double peeling_time = peeling_timer.elapsed();
std::cout << "Done with reducing-peeling..." << endl;
assert(offset == 0);
std::cout << " Reduced " << full_kernel.number_of_nodes() << " -> " << kernel.size() << " nodes" << std::endl;
std::cout << " Offset = " << offset << std::endl;
std::size_t num_kernel_edges = 0;
for (std::vector<NodeID> & neighbors : kernel) {
std::sort(neighbors.begin(), neighbors.end());
num_kernel_edges += neighbors.size();
}
num_kernel_edges /= 2;
graph_access peeled_graph;
peeled_graph.set_partition_count(2);
peeled_graph.start_construction(kernel.size(), 2 * num_kernel_edges);
for (NodeID v = 0; v < kernel.size(); v++) {
NodeID shadow_node = peeled_graph.new_node();
peeled_graph.setPartitionIndex(shadow_node, in_initial_is[v] ? 1 : 0);
peeled_graph.setNodeWeight(shadow_node, 1);
for (NodeID const neighbor : kernel[v]) {
EdgeID shadow_edge = peeled_graph.new_edge(shadow_node, neighbor);
peeled_graph.setEdgeWeight(shadow_edge, 1);
}
}
peeled_graph.finish_construction();
//std::cout << "Writing out post-peeling graph peeled.graph" << std::endl;
//graph_io::writeGraph(peeled_graph, "peeled.graph");
//// cout << "cover_size_offset=" << cover_size_offset << std::endl;
//// cout << "kernel_graph_number_of_nodes=" << kernel_graph.number_of_nodes() << std::endl;
//// cout << "mis_bnr.get_is_offset=" << mis_bnr.get_is_offset() << std::endl;
//// cout << "offset=" << offset << std::endl;
timer ils_timer;
ils ils_instance;
std::size_t const ils_print_offset = cover_size_offset + kernel_graph.number_of_nodes() - (mis_bnr.get_is_offset() + offset /* from peeling **/);
run_ils(ils_instance, partition_config, peeled_graph, total_timer, ils_print_offset);
double time_for_ils = ils_timer.elapsed();
cout << "ILS Running time: " << time_for_ils << std::endl;
std::size_t const ils_cover = kernel_graph.number_of_nodes() - (ils_instance.get_best_solution_size() + mis_bnr.get_is_offset() + offset);
double time_to_unwind = 0.0;
// reconstruct is / cover
{
timer unwind_timer;
std::vector<bool> full_is(line_copy.size(), false);
for (NodeID v = 0; v < peeled_graph.number_of_nodes(); v++) {
if (ils_instance.get_best_solution()[v] == 1)
full_is[reverse_mapping[new_to_old_id[v]]] = true;
}
std::cout << "Unwinding MIS reductions..." << std::endl;
mis_bnr.extend_finer_is(full_is);
NodeID *solution_is = new NodeID[line_copy.size()];
for (NodeID v = 0; v < line_copy.size(); v++) {
solution_is[v] = full_is[v] ? 1 : 0;
}
std::vector<std::vector<int>> clique_cover;
std::cout << "Transforming IS to VCC..." << std::endl;
transform_is_to_clique_cover(transformed_graph, vertex_to_edge,
kernel_graph.number_of_nodes(), solution_is, ils_cover, clique_cover);
//// std::cout << "Adding " << clique_cover.size() << " kernel cliques..." << std::endl;
oldVCC.addKernelCliques(clique_cover);
std::cout << "Unwinding VCC reductions..." << std::endl;
R.unwindReductions(oldVCC);
std::cout << "Done unwinding..." << std::endl;
oldVCC.analyzeGraph(graph_filename, G, s, false /* don't check cover */);
time_to_unwind = unwind_timer.elapsed();
}
double const time_to_best = ils_instance.get_last_total_update_time() + time_to_unwind;
cout << "Total Running time (beginning to end): " << total_timer.elapsed() << std::endl;
std::cout << "Transform (Exhaustive+Peeling+ILS) Upper Bound = " << ils_cover + cover_size_offset << std::endl;
std::size_t const clique_cover_size = ils_cover + cover_size_offset;
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "vcc_reduction_time=" << vcc_reduction_time << std::endl;
std::cout << "transformation_time=" << transformation_time << std::endl;
std::cout << "transformed_graph_vertices=" << transformed_graph.number_of_nodes() << std::endl;
std::cout << "transformed_graph_edges=" << transformed_graph.number_of_edges() / 2 << std::endl;
std::cout << "mis_reduction_time=" << mis_reduction_time << std::endl;
std::cout << "reduced_transformed_graph_vertices=" << full_kernel.number_of_nodes() << std::endl;
std::cout << "reduced_transformed_graph_edges=" << full_kernel.number_of_edges() / 2 << std::endl;
std::cout << "peeling_time=" << peeling_time << std::endl;
std::cout << "ils_time_to_best=" << ils_instance.get_last_update_time() << std::endl;
std::cout << "total_time_to_best=" << time_to_best << std::endl;
std::cout << "time_to_best_without_unwind=" << time_to_best - time_to_unwind << std::endl;
std::cout << "clique_cover_size=" << clique_cover_size << std::endl;
std::cout << "verified_cover=" << (oldVCC.validateCover(G) ? "passed" : "failed") << std::endl;
std::cout << "optimal=" << (clique_cover_size == partition_config.mis ? "yes":"unknown") << std::endl;
}
return 0;
}
#endif // BETA
else if (partition_config.run_type == "bnr") {
redu_vcc reduVCC;
branch_and_reduce B(G, reduVCC, partition_config);
bool finished = false;
vertex_queue *queue = nullptr;
if (partition_config.redu_type == "cascading") queue = new vertex_queue(reduVCC);
finished = B.bandr(reduVCC, 0, queue, partition_config, s);
double total_time = s.elapsed();
B.analyzeGraph(graph_filename, G, reduVCC, s);
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "input_graph_vertices=" << G.number_of_nodes() << std::endl;
std::cout << "input_graph_edges=" << G.number_of_edges() / 2 << std::endl;
std::cout << "total_time_to_best=" << total_time << std::endl;
std::cout << "branch_count=" << B.branch_count << std::endl;
std::cout << "prune_count=" << B.prune_count << endl;
std::cout << "decompose_count=" << B.decompose_count << std::endl;
std::cout << "clique_cover_size=" << reduVCC.clique_cover.size() << std::endl;
std::cout << "verified_cover=" << (reduVCC.validateCover(G) ? "passed" : "failed") << std::endl;
std::cout << "optimal=" << (finished ? "yes" : "unknown") << std::endl;
return 0;
}
else if (partition_config.run_type == "edge_bnr") {
redu_vcc reduVCC;
branch_and_reduce B(G, reduVCC, partition_config);
bool finished = false;
vertex_queue *queue = nullptr;
if (partition_config.redu_type == "cascading") queue = new vertex_queue(reduVCC);
finished = B.edge_bandr(reduVCC, 0, queue, partition_config, s, 0);
double total_time = s.elapsed();
B.analyzeGraph(graph_filename, G, reduVCC, s);
std::cout << "BEGIN_OUTPUT_FOR_TABLES" << std::endl;
std::cout << "run_type=" << partition_config.run_type << std::endl;
std::cout << "input_graph_vertices=" << G.number_of_nodes() << std::endl;
std::cout << "input_graph_edges=" << G.number_of_edges() / 2 << std::endl;
std::cout << "total_time_to_best=" << total_time << std::endl;
std::cout << "branch_count=" << B.branch_count << std::endl;
std::cout << "prune_count=" << B.prune_count << endl;
std::cout << "decompose_count=" << B.decompose_count << std::endl;
std::cout << "clique_cover_size=" << reduVCC.clique_cover.size() << std::endl;
std::cout << "verified_cover=" << (reduVCC.validateCover(G) ? "passed" : "failed") << std::endl;
std::cout << "optimal=" << (finished ? "yes" : "unknown") << std::endl;
return 0;
}
#ifdef BETA
else if (partition_config.run_type == "test") {
timer total_timer;
timer transformation_timer;
graph_access transformed_graph;
std::vector<std::pair<NodeID, NodeID>> vertex_to_edge;
transform_graph(G, transformed_graph, vertex_to_edge);
double transformation_time = transformation_timer.elapsed();
// Step 4: Compute MIS
if (true) // just ILS
{
timer ils_timer;
greedy_mis greedy;
greedy.initial_partition(partition_config.seed, transformed_graph);
ils ils_instance;
run_ils(ils_instance, partition_config, transformed_graph, total_timer, G.number_of_nodes());
cout << "ILS Running time: " << ils_timer.elapsed() << std::endl;
std::size_t const ils_cover = G.number_of_nodes() - ils_instance.get_best_solution_size();
std::cout << "Transform (ILS) Upper Bound = " << ils_cover << std::endl;
std::vector<std::vector<int>> clique_cover;
size_t const num_cliques = G.number_of_nodes() - ils_instance.get_best_solution_size();
transform_is_to_clique_cover(transformed_graph,
vertex_to_edge,
G.number_of_nodes(),
ils_instance.get_best_solution(),
num_cliques,
clique_cover);
}
return 0;
}
#endif // BETA
}
| 43.12542 | 154 | 0.599958 | [
"vector",
"transform"
] |
efde928aeadc256f0799023c2332c45418f8f0dd | 3,350 | cpp | C++ | src/graphic/opengl3/mesh.cpp | HenryAWE/learn-electron | 6705954ce3f08431fcf5767ef617632bf7e540df | [
"BSD-3-Clause"
] | null | null | null | src/graphic/opengl3/mesh.cpp | HenryAWE/learn-electron | 6705954ce3f08431fcf5767ef617632bf7e540df | [
"BSD-3-Clause"
] | null | null | null | src/graphic/opengl3/mesh.cpp | HenryAWE/learn-electron | 6705954ce3f08431fcf5767ef617632bf7e540df | [
"BSD-3-Clause"
] | null | null | null | // Author: HenryAWE
// License: The 3-clause BSD License
#include "mesh.hpp"
#include <cassert>
#include "renderer.hpp"
namespace awe::graphic::opengl3
{
namespace detailed
{
void ApplyVertexAttrib(
GLuint idx,
const VertexAttribData& attr,
GLsizei stride,
std::size_t offset
) {
glVertexAttribPointer(
idx,
attr.component,
GetGLType(attr.type),
GL_FALSE,
stride,
reinterpret_cast<const void*>(offset)
);
glEnableVertexAttribArray(idx);
}
}
Mesh::Mesh(Renderer& renderer, bool dynamic)
: Super(renderer, dynamic) {}
Mesh::~Mesh() noexcept
{
Deinitialize();
}
void Mesh::Submit()
{
if(IsSubmitted() || !GetData())
return;
if(!m_init)
Initialize();
auto& data = *GetData();
glBindVertexArray(m_gldata.vao);
glBindBuffer(GL_ARRAY_BUFFER, m_gldata.vbo);
glBufferData(
GL_ARRAY_BUFFER,
data.vertices.size(),
data.vertices.data(),
IsDynamic() ? GL_DYNAMIC_DRAW : GL_STATIC_READ
);
const std::size_t stride = data.descriptor.Stride();
for(std::size_t i = 0; i < data.descriptor.attributes.size(); ++i)
{
detailed::ApplyVertexAttrib(
static_cast<GLuint>(i),
data.descriptor.attributes[i],
static_cast<GLsizei>(stride),
data.descriptor.Offset(i)
);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_gldata.ebo);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
data.indices.size(),
data.indices.data(),
IsDynamic() ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW
);
glBindVertexArray(0);
m_drawcfg.mode = GL_TRIANGLES;
m_drawcfg.count = static_cast<GLsizei>(data.indices.size() / SizeOf(data.indices_type));
m_drawcfg.type = GetGLType(data.indices_type);
DataSubmitted();
}
void Mesh::Draw()
{
Submit();
glBindVertexArray(m_gldata.vao);
glDrawElements(
m_drawcfg.mode,
m_drawcfg.count,
m_drawcfg.type,
reinterpret_cast<const void*>(0)
);
glBindVertexArray(0);
}
Renderer& Mesh::GetRenderer() noexcept
{
assert(dynamic_cast<Renderer*>(&Super::GetRenderer()));
return static_cast<Renderer&>(Super::GetRenderer());
}
void Mesh::Initialize()
{
if(m_init)
return;
glGenVertexArrays(1, &m_gldata.vao);
GLuint buffers[2];
glGenBuffers(2, buffers);
m_gldata.vbo = buffers[0];
m_gldata.ebo = buffers[1];
m_init = true;
}
void Mesh::Deinitialize() noexcept
{
if(!m_init)
return;
GetRenderer().PushClearCommand([gldata = m_gldata]{
glDeleteVertexArrays(1, &gldata.vao);
const GLuint buffers[2] { gldata.vbo, gldata.ebo };
glDeleteBuffers(2, buffers);
});
std::memset(&m_gldata, 0, sizeof(GLData));
m_init = false;
}
}
| 26.587302 | 96 | 0.540597 | [
"mesh"
] |
efe577ad20b7b7fbca7eb3b385264c7dc06622e3 | 721 | cpp | C++ | esp/main/app/task_debug.cpp | binh8994/esp_pthead | 13a67e7699d6492dbdd379aa2664e509e8c32af1 | [
"MIT"
] | 1 | 2020-07-27T06:36:17.000Z | 2020-07-27T06:36:17.000Z | esp/main/app/task_debug.cpp | binh8994/esp_pthead | 13a67e7699d6492dbdd379aa2664e509e8c32af1 | [
"MIT"
] | null | null | null | esp/main/app/task_debug.cpp | binh8994/esp_pthead | 13a67e7699d6492dbdd379aa2664e509e8c32af1 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <vector>
#include "app.h"
#include "app_data.h"
#include "app_dbg.h"
#include "task_list.h"
#include "task_debug.h"
q_msg_t gw_task_debug_mailbox;
void* gw_task_debug_entry(void*) {
ak_msg_t* msg = AK_MSG_NULL;
wait_all_tasks_started();
APP_DBG("[STARTED] gw_task_debug_entry\n");
while (1) {
/* get messge */
msg = ak_msg_rev(GW_TASK_DEBUG_ID);
switch (msg->header->sig) {
case GW_DEBUG_1: {
APP_DBG("GW_DEBUG_1\n");
}
break;
default:
break;
}
/* free message */
ak_msg_free(msg);
}
return (void*)0;
}
| 14.42 | 44 | 0.667129 | [
"vector"
] |
efe655dc9afb301acbd5474ca9f108f57f2c0f00 | 4,495 | cpp | C++ | AnimalCooking/Food.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | AnimalCooking/Food.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | 23 | 2020-03-02T16:43:28.000Z | 2020-04-16T09:58:08.000Z | AnimalCooking/Food.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | #include "Food.h"
#include "SDL_macros.h"
#include "PlayState.h"
#include "FSM.h"
#include "TimerViewer.h"
#include "Entity.h"
#include "GPadController.h"
#include "Tracker.h"
#include "TrackerEvents/IngredientDespawnEvent.h"
Food::Food(Vector2D position, Resources::FoodType type, Transport* p1, Transport* p2, Texture* explosion) : Pickable(p1, p2, nullptr),
timer_(new FoodTimer()),
canDraw(true),
type_(type),
foodPool_(nullptr),
texture_(nullptr),
showHelp(true),
explosion_(explosion),
explosionFrame_(),
lastFrameTime_()
{
position_ = position;
jute::jValue& jsonGeneral = SDLGame::instance()->getJsonGeneral();
size_ = Vector2D(jsonGeneral["Foods"]["size"]["width"].as_double() * SDLGame::instance()->getCasillaX(), jsonGeneral["Foods"]["size"]["height"].as_double() * SDLGame::instance()->getCasillaY());
speed_ = Vector2D();
GETCMP2(SDLGame::instance()->getTimersViewer(), TimerViewer)->addTimer(timer_);
}
Food::Food(Resources::FoodType type, Texture* explosion) : Pickable(nullptr, nullptr, nullptr),
timer_(new FoodTimer()),
type_(type),
foodPool_(nullptr),
canDraw(true),
showHelp(true),
explosion_(explosion),
explosionFrame_(),
lastFrameTime_()
{
position_ = Vector2D();
jute::jValue& jsonGeneral = SDLGame::instance()->getJsonGeneral();
size_ = Vector2D(jsonGeneral["Foods"]["size"]["width"].as_double() * SDLGame::instance()->getCasillaX(), jsonGeneral["Foods"]["size"]["height"].as_double() * SDLGame::instance()->getCasillaY());
speed_ = Vector2D();
GETCMP2(SDLGame::instance()->getTimersViewer(), TimerViewer)->addTimer(timer_);
}
void Food::setFoodPool(FoodPool* foodPool, std::vector<Food*>::iterator it)
{
foodPool_ = foodPool;
iterator_ = it;
}
void Food::Destroy()
{
GETCMP2(SDLGame::instance()->getTimersViewer(), TimerViewer)->deleteTimer(timer_);
foodPool_->RemoveFood(iterator_);
dead = true;
}
void Food::update()
{
Pickable::update();
timer_->update();
if (timer_->isTimerEnd()) {
IngredientDespawnEvent* u = new IngredientDespawnEvent();
u->setIngredient(this->getType())
->setLevelId(SDLGame::instance()->getCurrentLevel());
Tracker::Instance()->trackEvent(u);
Destroy();
}
}
void Food::draw()
{
SDL_Rect destRect = RECT(position_.getX(), position_.getY(), size_.getX(), size_.getY());
texture_->render(destRect);
if (explosion_ != nullptr && explosionFrame_ < explosion_->getNumCols())
{
int time = SDLGame::instance()->getTime();
if (time - lastFrameTime_ >= 160)
{
explosionFrame_++;
lastFrameTime_ = time;
}
destRect.w += .4 * destRect.w;
destRect.x -= .15 * destRect.w;
destRect.h += .2 * destRect.h;
explosion_->renderFrame(destRect, 0, explosionFrame_, 0);
/*if (explosionFrame_ == explosion_->getNumCols())
{
i->setHasToPlayExplosion(false);
explosionFrame_ = 0;
}*/
}
}
void Food::draw(SDL_Rect r)
{
texture_->render(r);
}
void Food::onDrop(bool onfloor)
{
if (onfloor) {
Pickable::onDrop(onfloor);
timer_->timerStart();
SDLGame::instance()->getAudioMngr()->playChannel(Resources::AudioId::Drop, 0);
showHelp = true;
inHands = false;
}
}
void Food::onFloor()
{
//El gameControl llamaba al m�todo onDrop pero siempre con true, se necesita hacer est� distinci�n
//porque sino el gameControl al generar una comida desencadena que se reproduzca el sonido de dejar caer cuando no deber�a
Pickable::onDrop(true);
timer_->timerStart();
}
void Food::action1(int player)
{
if (player == Resources::Player1)
{
if (!inHands) player1_->pick(this, Resources::PickableType::Food);
}
else
{
if (!inHands) player2_->pick(this, Resources::PickableType::Food);
}
showHelp = false;
}
void Food::feedback(int player)
{
if (!inHands && !dead && feedbackVisual_ != nullptr) {
SDL_Rect destRect = RECT(position_.getX(), position_.getY(), size_.getX(), size_.getY());
feedbackVisual_->render(destRect);
if (showHelp && SDLGame::instance()->getOptions().showKeyToPress) {
if (GPadController::instance()->playerControllerConnected(player))
SDLGame::instance()->renderFeedBack(position_, "Pick up", SDL_GameControllerGetStringForButton(SDLGame::instance()->getOptions().players_gPadButtons[player].PICKUP), player, true);
else
SDLGame::instance()->renderFeedBack(position_, "Pick up", SDL_GetKeyName(SDLGame::instance()->getOptions().players_keyboardKeys[player].PICKUP), player);
}
}
}
void Food::onPick() {
inHands = true;
timer_->timerReset();
SDLGame::instance()->getAudioMngr()->playChannel(Resources::AudioId::PickUp, 0);
}
| 28.09375 | 195 | 0.70812 | [
"render",
"vector"
] |
efeb60cf214dd010362c3cccf041cecbfb08bf73 | 21,816 | cpp | C++ | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/AllocationMap.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/AllocationMap.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/AllocationMap.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | #include <klee/Expr.h>
#include <klee/util/ExprTemplates.h>
#include <s2e/S2E.h>
#include <s2e/Utils.h>
#include "AllocationMap.h"
#include "util.h"
using namespace klee;
namespace s2e {
namespace plugins {
S2E_DEFINE_PLUGIN(AllocManager, "Kernel memory allocation management",
"AllocManager", "KernelFunctionModels", "OptionsManager");
void AllocManager::initialize() {
m_kernelFunc = s2e()->getPlugin<models::KernelFunctionModels>();
m_options = s2e()->getPlugin<OptionsManager>();
m_kmem_caches[PAGE_ALLOCATOR] = kmem_cache(0, "page");
m_kmem_caches[SLAB_ALLOCATOR] = kmem_cache(0, "slab");
initializeConfiguration();
}
void AllocManager::initializeConfiguration() {
bool ok = false;
ConfigFile *cfg = s2e()->getConfig();
ConfigFile::string_list funcList =
cfg->getListKeys(getConfigKey() + ".functions");
if (funcList.size() == 0) {
getWarningsStream() << "no functions configured\n";
}
foreach2(it, funcList.begin(), funcList.end()) {
std::stringstream s;
s << getConfigKey() << ".functions." << *it << ".";
MemFunctionCfg func;
func.funcName = cfg->getString(s.str() + "funcName", "", &ok);
EXIT_ON_ERROR(ok, "You must specify " + s.str() + "funcName");
func.address = cfg->getInt(s.str() + "address", -1, &ok);
EXIT_ON_ERROR(ok, "You must specify " + s.str() + "address");
func.type = cfg->getInt(s.str() + "type", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify " + s.str() + "type");
func.sizeArg = cfg->getInt(s.str() + "sizeArg", 0, &ok);
EXIT_ON_ERROR(func.type != FUNC_ALLOCATE || ok,
"You must specify " + s.str() + "type");
m_hookfuncs.insert({func.address, func});
}
ConfigFile::integer_list sizeList = cfg->getIntegerList("AlignedSizes");
foreach2(it, sizeList.begin(), sizeList.end()) {
alignedSize.push_back(*it);
}
sort(alignedSize.begin(), alignedSize.end()); // sort
slab_offset = cfg->getInt(getConfigKey() + ".slab_offset", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify slab_offset");
name_offset = cfg->getInt(getConfigKey() + ".name_offset", 0, &ok);
EXIT_ON_ERROR(ok, "You must specify name_offset");
// adjust options with respect to their relationship
bool init_obj = false;
switch (m_options->mode) {
case MODE_PRE_ANALYSIS:
break;
case MODE_ANALYSIS:
init_obj = true;
break;
case MODE_RESOLVE:
init_obj = true;
break;
}
if (init_obj) {
ConfigFile::string_list objList =
cfg->getListKeys(getConfigKey() + ".symbolic");
foreach2(it, objList.begin(), objList.end()) {
std::stringstream s;
s << getConfigKey() << ".symbolic." << *it << ".";
AllocCfg obj;
ConfigFile::integer_list backtrace;
backtrace = cfg->getIntegerList(s.str() + "callsite", backtrace, &ok);
for (auto addr : backtrace)
obj.backtrace.push_back(addr);
EXIT_ON_ERROR(ok, "You must specify " + s.str() + "callsite");
unsigned size = cfg->getInt(s.str() + "size", 0, &ok);
obj.arg = E_CONST(size, Expr::Int32);
EXIT_ON_ERROR(ok, "You must specify " + s.str() + "size");
m_vulobjs.push_back(obj);
}
}
}
void AllocManager::registerHandler(PcMonitor *PcMonitor,
S2EExecutionState *state, uint64_t cr3) {
// Functions to hook
foreach2(it, m_hookfuncs.begin(), m_hookfuncs.end()) {
getDebugStream() << "Hook Function: " << it->second.funcName << " at "
<< hexval(it->second.address) << "\n";
// we already filter out any other process at PcMonitor, it's ok not to
// give
// cr3 here
PcMonitor::CallSignalPtr CallSignal =
PcMonitor->getCallSignal(state, it->second.address, cr3);
CallSignal->connect(sigc::mem_fun(*this, &AllocManager::onFunctionCall),
ALLOCATE_PRIORITY);
}
}
/*
* Extract the base address of a symbolic pointer.
* Fail if the base address is not a symbolic value.
*/
bool AllocManager::getBaseAddr(S2EExecutionState *state, ref<Expr> dstExpr,
uint64_t &base_addr) {
ref<ReadExpr> sym_base;
std::string prefix = "alc_";
if (isa<ConstantExpr>(dstExpr)) {
return false;
}
if (findSymBase(dstExpr, sym_base, prefix)) {
std::string name = sym_base->getUpdates()->getRoot()->getName();
base_addr = getValueFromName(name, prefix);
return true;
}
return false;
}
void AllocManager::onFunctionCall(S2EExecutionState *state, PcMonitorState *fns,
uint64_t pc) {
MemFunctionCfg cfg = m_hookfuncs[pc];
uint64_t val, kcache;
AllocCfg alloc;
kmem_cache cache;
switch (cfg.type) {
case FUNC_ALLOCATE:
alloc.funcName = cfg.funcName;
alloc.allocator = getAllocator(cfg.funcName);
alloc.arg = m_kernelFunc->readSymArgument(state, cfg.sizeArg, true);
if (!m_kernelFunc->dump_stack(state, state->regs()->getSp(), 0, alloc.backtrace, 2)) {
getWarningsStream(state) << "Failed to retrieve the backtrace\n";
}
// we need to retrieve the return value
PCMON_REGISTER_RETURN_A(state, fns, AllocManager::onFunctionRet, alloc);
break;
case SLAB_ALLOCATE:
alloc.funcName = cfg.funcName;
m_kernelFunc->readArgument(state, cfg.sizeArg, kcache, true);
alloc.allocator = kcache;
if (m_kmem_caches.find(kcache) != m_kmem_caches.end()) {
val = m_kmem_caches[kcache].object_size;
} else {
m_kernelFunc->readMemory(state, kcache + name_offset,
sizeof(target_ulong) * CHAR_BIT, val,
false);
cache.name = m_kernelFunc->readString(state, val);
m_kernelFunc->readMemory(state, kcache + slab_offset,
sizeof(unsigned int) * CHAR_BIT, val,
false);
cache.object_size = val;
m_kmem_caches[kcache] = cache;
getDebugStream(state) << "create kmem_cache: " << cache.name << "\n";
}
alloc.arg = E_CONST(val, Expr::Int64);
if (!m_kernelFunc->dump_stack(state, state->regs()->getSp(), 0, alloc.backtrace, 2)) {
getWarningsStream(state) << "Failed to retrieve the backtrace\n";
}
PCMON_REGISTER_RETURN_A(state, fns, AllocManager::onFunctionRet, alloc);
break;
case FUNC_FREE:
if (m_options->track_access) {
uint64_t base_addr;
ref<Expr> dstAddr =
m_kernelFunc->readSymArgument(state, cfg.sizeArg, false);
if (!getBaseAddr(state, dstAddr, base_addr)) {
uint64_t ip = getRetAddr(state);
getDebugStream(state)
<< "[Delete] {\"base\": "
<< std::to_string(readExpr<uint64_t>(state, dstAddr))
<< ", \"callsite\": " << std::to_string(ip) << "}\n";
}
}
m_kernelFunc->readArgument(state, cfg.sizeArg, val, true);
if (val == 0) {
break;
}
if (m_options->track_object) {
std::stringstream ss;
ss << "[object] {";
ss << "\"op\": \"free\", \"base\": " << std::to_string(val);
ss << "}\n";
getDebugStream(state) << ss.str() << "\n";
onRelease.emit(state, val);
}
erase(state, val);
break;
}
}
void AllocManager::onFunctionRet(S2EExecutionState *state, AllocCfg cfg) {
uint64_t ret;
// Ret value from kmalloc
m_kernelFunc->getRetValue(state, ret);
if (ret == 0) { // malloc failed
return;
}
// getDebugStream(state) << "Return from " << cfg.funcName << " with " <<
// cfg.allocator << ": " << hexval(ret) << "\n";
insert(cfg.funcName, ret, cfg.arg, cfg.allocator);
callsites[ret] = cfg.backtrace;
if (m_options->track_object) {
std::stringstream ss;
ss << "[object] {";
ss << "\"op\": \"alloc\", \"base\": " << std::to_string(ret);
ss << ", \"site\": " << std::to_string(cfg.backtrace[0]);
ss << ", \"alloc\": \"" << getAllocator(cfg.allocator) << "\"";
ss << ", \"size\": "
<< std::to_string(readExpr<uint64_t>(state, cfg.arg));
ss << "}\n";
getDebugStream(state) << ss.str();
onAllocate.emit(state, &cfg, ret);
}
if (!m_options->concrete) {
for (auto obj : m_vulobjs) {
bool match = true;
if (obj.backtrace.size() != cfg.backtrace.size())
continue;
for (int i = 0; i < obj.backtrace.size(); i++)
if (obj.backtrace[i] != cfg.backtrace[i]) {
match = false;
break;
}
if (!match)
continue;
// check if size matches
uint64_t width = readExpr<uint64_t>(state, cfg.arg);
uint64_t size = getSize(cfg.funcName, width);
uint64_t vuln_size = dyn_cast<ConstantExpr>(obj.arg)->getZExtValue();
getDebugStream(state)
<< "size: " << hexval(size)
<< ", required: " << hexval(vuln_size) << "\n";
if (vuln_size != 0 && size != vuln_size)
return;
std::stringstream ss;
ss << "alc_" << hexval(ret);
ref<Expr> sym = m_kernelFunc->makeSymbolic(
state, CPU_OFFSET(regs[R_EAX]), ss.str(), true);
getDebugStream(state) << "Make return value symbolic"
<< "\n";
// Add constraint on this memory
AlloConstraint.addConstraint(
E_EQ(sym, E_CONST(ret, sizeof(target_ulong) * CHAR_BIT)));
if (m_options->track_access) {
uint64_t size = readExpr<uint64_t>(state, cfg.arg);
getDebugStream(state)
<< "[Create] "
<< "{\"base\": " << std::to_string(ret) << ", \"len\": " << size
<< ", \"callsite\": " << std::to_string(cfg.backtrace[0]) << "}\n";
}
}
}
}
// Call this function right after a function is invoked
target_ulong AllocManager::getRetAddr(S2EExecutionState *state) {
target_ulong addr;
bool ok = m_kernelFunc->readStack(state, 0, 0, addr);
EXIT_ON_ERROR(ok, "Something wrong when getting ret addr");
return addr;
}
void AllocManager::insert(uint64_t addr, uint64_t width, uint64_t alloc) {
allocMap.insert(std::make_pair(addr, AllocObj(width, alloc)));
}
void AllocManager::insert(uint64_t addr, ref<Expr> width, uint64_t alloc) {
allocMap.insert(std::make_pair(addr, AllocObj(width, alloc)));
}
void AllocManager::insert(std::string funcName, uint64_t addr, uint64_t width,
uint64_t alloc) {
uint64_t size = getSize(funcName, width);
insert(addr, size, alloc);
}
void AllocManager::insert(std::string funcName, uint64_t addr, ref<Expr> width,
uint64_t alloc) {
// keep in oder
auto it = sequences.rbegin();
if (it == sequences.rend()) {
// We haven't started yet.
return;
} else {
it->push_back(addr);
}
if (isa<ConstantExpr>(width)) {
ConstantExpr *expr = dyn_cast<ConstantExpr>(width);
uint64_t value = expr->getZExtValue();
insert(funcName, addr, value, alloc);
return;
}
ref<Expr> size = getSize(funcName, width);
insert(addr, size, alloc);
}
void AllocManager::erase(S2EExecutionState *state, uint64_t addr) {
auto it = allocMap.find(addr);
if (it == allocMap.end()) {
return;
}
// FIXME: How to do it efficiently
bool found = false;
foreach2(iter, sequences.begin(), sequences.end()) {
foreach2(itt, iter->begin(), iter->end()) {
if (*itt == addr) {
iter->erase(itt);
found = true;
break;
}
}
if (found) {
break;
}
}
if (m_options->mode == MODE_PRE_ANALYSIS) {
AllocObj obj = it->second;
freeMap.insert({addr, obj});
}
allocMap.erase(it);
}
uint64_t AllocManager::getAllocator(std::string funcName) {
if (funcName == "__get_free_pages") {
return PAGE_ALLOCATOR;
}
return SLAB_ALLOCATOR;
}
uint64_t AllocManager::getSize(std::string funcName, uint64_t size) {
if (funcName == "__get_free_pages") {
return (1 << size) * PAGE_SIZE;
} else {
return size;
}
}
ref<Expr> AllocManager::getSize(std::string funcName, ref<Expr> size) {
if (funcName == "__get_free_pages") {
return ShlExpr::create(
E_CONST(PAGE_SIZE, sizeof(target_ulong) * CHAR_BIT), size);
} else {
return size;
}
}
uint64_t AllocManager::roundSize(uint64_t size) {
uint64_t maximum = 8192;
if (size > maximum) {
return (size / 4096 + ((size & 0x1000) == 0 ? 0 : 1)) * 4096;
} else {
for (auto it : alignedSize) {
if (it >= size) {
return it;
}
}
return 0;
}
}
uint64_t AllocManager::lowerSize(uint64_t size) {
uint64_t maximum = 8192;
if (size > maximum) {
return ((maximum - 1) / 4096) * 4096;
} else {
uint64_t last = 0;
for (auto it : alignedSize) {
if (it >= size) {
return last;
}
last = it;
}
return 0;
}
}
void AllocManager::print(Plugin *plugin) {
plugin->getDebugStream() << "Allocation: " << allocMap.size() << "\n";
for (auto it = allocMap.begin(); it != allocMap.end(); ++it) {
if (it->second.tag == AllocObj::CONCRETE) {
plugin->getDebugStream()
<< hexval(it->first) << ": " << it->second.width << "\n";
} else {
plugin->getDebugStream() << hexval(it->first) << ": "
<< "sym"
<< "\n";
}
}
}
bool AllocManager::get(S2EExecutionState *state, uint64_t addr,
AllocObj &obj, bool concretize) {
auto it = allocMap.find(addr);
if (it == allocMap.end()) {
return false;
}
if (concretize) {
this->concretize(state, it->second);
}
obj = it->second;
return true;
}
bool AllocManager::getFreeObj(S2EExecutionState *state, uint64_t addr,
AllocObj &obj, bool concretize) {
auto it = freeMap.find(addr);
if (it == freeMap.end()) {
return false;
}
if (concretize) {
this->concretize(state, it->second);
}
obj = it->second;
return true;
}
void AllocManager::concretize(S2EExecutionState *state, AllocObj &obj) {
if (obj.tag == AllocObj::SYMBOLIC && obj.width == 0) {
ConstantExpr *expr =
dyn_cast<ConstantExpr>(state->concolics->evaluate(obj.sym_width));
assert(expr && "Failed to concretize");
obj.width = expr->getZExtValue();
}
}
// We want to know the heap layout, basically we have two solution
// getAggregate: One implemented below assumes that objects with the same size are contiguous.
// getWidelength: Another way we can consider is to collect all objects
// potential to be allocated in contiguous memory,
// because we want to take into account race condition where different syscalls
// interleave with each other and our
// sequences are out of order. Race condition is somewhat complex. If we want to
// tackle this, we could introducing thread ID.
AllocObj AllocManager::getWidelength(S2EExecutionState *state, uint64_t addr) {
auto it = allocMap.find(addr);
assert(it != allocMap.end());
AllocObj ret(it->second);
concretize(state, ret);
ret.width = roundSize(ret.width);
while (++it != allocMap.end()) {
if (addr + ret.width != it->first) { // non-contiguous memory addresses
return ret;
}
AllocObj next(it->second);
concretize(state, next);
next.width = roundSize(next.width);
ret += next;
}
return ret;
}
// Method 2
// If the size of vulneralbe object is variable, the objects we consider should
// also have the new size.
// Note: update the objects of old_size with new_size
AllocObj AllocManager::getAggregate(S2EExecutionState *state, uint64_t addr,
unsigned new_size) {
auto it = allocMap.find(addr);
unsigned old_size = roundSize(it->second.width);
unsigned counter = 1;
assert(it != allocMap.end());
AllocObj ret(it->second);
concretize(state, ret);
ret.width = roundSize(new_size);
// ret.width = roundSize(ret.width);
// only consider objects allocated after the target one, but still within
// the execution of the same syscall
bool found = false;
for (auto seq : sequences) {
for (auto itt : seq) {
if (itt == addr) {
found = true;
continue;
}
if (found) {
AllocObj obj;
if (!get(state, itt, obj)) {
continue;
}
// Check the allocators are the same or not
if (obj.allocator != ret.allocator) {
continue;
}
concretize(state, obj); // concetize obj and round up width
obj.width = roundSize(obj.width); // update width
switch (obj.tag) {
case AllocObj::SYMBOLIC:
// check whether the symbolic value can equal new_size
if (old_size ==
obj.width) { // object of the same old rounded size
obj.width = new_size;
ret += obj;
counter++;
}
break;
case AllocObj::CONCRETE:
if (new_size == obj.width) { // object of the same new size
ret += obj;
counter++;
}
break;
}
}
}
if (found) {
break;
}
}
g_s2e->getDebugStream()
<< "Found " << std::to_string(counter) << " objects with the same size "
<< std::to_string(new_size) << "\n";
return ret;
}
bool AllocManager::getLayout(S2EExecutionState *state, uint64_t addr,
std::vector<unsigned> &layout) {
auto it = allocMap.find(addr);
unsigned size = roundSize(it->second.width);
assert(it != allocMap.end());
AllocObj ret(it->second);
concretize(state, ret);
ret.width = roundSize(ret.width);
bool found = false;
for (auto seq : sequences) {
for (auto itt : seq) {
if (itt == addr) {
found = true;
break;
}
}
if (found) {
for (auto itt : seq) {
if (itt == addr) {
layout.push_back(0);
continue;
}
AllocObj obj;
if (!get(state, itt, obj)) {
continue;
}
if (obj.allocator != ret.allocator) {
continue;
}
concretize(state, obj); // concetize obj and round up width
switch (obj.tag) {
case AllocObj::SYMBOLIC:
if (size == roundSize(obj.width)) {
layout.push_back(1);
}
break;
case AllocObj::CONCRETE:
layout.push_back(roundSize(obj.width));
break;
}
}
break;
}
}
return true;
}
// syscall analyze
bool AllocManager::getSyscallIndex(uint64_t addr, unsigned &allocIndex,
unsigned &defIndex,
std::vector<unsigned> &syscalls) {
unsigned index = 0;
bool found = false;
for (auto seq : sequences) {
for (auto itt : seq) {
if (itt == addr) {
allocIndex = index;
found = true;
break;
}
}
if (found)
break;
++index;
}
if (!found)
return false;
defIndex = m_defIndex;
if (m_defIndex == -1)
return false;
syscalls.clear();
syscalls.insert(syscalls.end(), m_syscalls.begin(), m_syscalls.end());
return true;
}
// find the nearest object in the busy list
uint64_t AllocManager::find(S2EExecutionState *state, uint64_t addr) {
auto it = allocMap.lower_bound(addr); // it->first >= addr
if (it->first == addr) {
return addr;
} else if (it == allocMap.begin()) {
return 0;
}
--it;
if (it->second.tag == AllocObj::SYMBOLIC) {
concretize(state, it->second);
}
uint64_t width = it->second.width;
if (addr >= it->first) {
if (addr >= it->first + width) {
g_s2e->getDebugStream(state) << "Out of bound address found!!!\n";
}
return it->first;
}
return 0; // Fail to find
}
} // namespace plugins
} // namespace s2e
| 32.707646 | 94 | 0.537633 | [
"object",
"vector"
] |
efedcf3f36f96e97421bc60fee7c04bdcbad47bd | 4,756 | cpp | C++ | LostReality/LostCore-D3D11/Pipelines/ForwardPipeline.cpp | luma211/snowflake | 13438de4f0aca9ce75a763e74410059df5f3fc08 | [
"MIT"
] | null | null | null | LostReality/LostCore-D3D11/Pipelines/ForwardPipeline.cpp | luma211/snowflake | 13438de4f0aca9ce75a763e74410059df5f3fc08 | [
"MIT"
] | 1 | 2016-07-21T12:09:48.000Z | 2016-07-21T12:09:48.000Z | LostReality/LostCore-D3D11/Pipelines/ForwardPipeline.cpp | luma211/snowflake | 13438de4f0aca9ce75a763e74410059df5f3fc08 | [
"MIT"
] | 1 | 2020-04-24T17:43:28.000Z | 2020-04-24T17:43:28.000Z | /*
* file ForwardPipeline.cpp
*
* author luoxw
* date 2017/09/21
*
*
*/
#include "stdafx.h"
#include "ForwardPipeline.h"
#include "Implements/ConstantBuffer.h"
#include "Implements/PrimitiveGroup.h"
#include "Implements/Texture.h"
#include "States/DepthStencilStateDef.h"
#include "States/BlendStateDef.h"
#include "States/RasterizerStateDef.h"
#include "Src/ShaderManager.h"
using namespace LostCore;
D3D11::FForwardPipeline::FForwardPipeline()
: RenderObjects()
{
}
D3D11::FForwardPipeline::~FForwardPipeline()
{
}
void D3D11::FForwardPipeline::Initialize()
{
//uint32 val = 0;
//while (val != (uint32)ERenderOrder::End)
//{
// RenderObjects.Ref()[(ERenderOrder)val++] = vector<FRenderObject>();
//}
}
void D3D11::FForwardPipeline::Destroy()
{
//uint32 val = 0;
//while (val != (uint32)ERenderOrder::End)
//{
// assert(RenderObjects.Ref()[(ERenderOrder)val].size() == 0);
//}
}
EPipeline D3D11::FForwardPipeline::GetEnum() const
{
return EPipeline::Forward;
}
void D3D11::FForwardPipeline::CommitPrimitiveGroup(FPrimitiveGroup* pg)
{
static FStackCounterRequest SCounter("FForwardPipeline::CommitPrimitiveGroup");
FScopedStackCounterRequest scopedCounter(SCounter);
if (RenderObjects.empty())
{
uint32 val = 0;
while (val != (uint32)ERenderOrder::End)
{
RenderObjects[(ERenderOrder)val++] = vector<FRenderObject>();
}
}
assert(pg != nullptr);
Committing.PrimitiveGroup = pg;
auto& objs = RenderObjects.find(pg->GetRenderOrder());
objs->second.push_back(Committing);
Committing.Reset();
}
void D3D11::FForwardPipeline::CommitBuffer(FConstantBuffer* buf)
{
assert(buf != nullptr);
Committing.ConstantBuffers.push_back(buf);
}
void D3D11::FForwardPipeline::CommitShaderResource(FTexture2D* tex)
{
assert(tex != nullptr);
Committing.ShaderResources.push_back(tex);
}
void D3D11::FForwardPipeline::CommitInstancingData(FInstancingData* buf)
{
assert(buf != nullptr);
Committing.InstancingDatas.push_back(buf);
}
void D3D11::FForwardPipeline::BeginFrame()
{
Committing.Reset();
}
void D3D11::FForwardPipeline::EndFrame()
{
}
void D3D11::FForwardPipeline::RenderFrame()
{
static FStackCounterRequest SCounter("FForwardPipeline::Render");
FScopedStackCounterRequest scopedCounter(SCounter);
auto cxt = FRenderContext::GetDeviceContext("FForwardPipeline::Render");
for (auto& objs : RenderObjects)
{
if (objs.first == ERenderOrder::Opacity)
{
auto ds = FDepthStencilStateMap::Get()->GetState(DS_DEPTH_READ | DS_DEPTH_WRITE);
cxt->OMSetDepthStencilState(ds.GetReference(), 0);
auto blendMode = EBlendMode::None;
auto blendWrite = EBlendWrite::RGB;
uint32 blendFlags = (uint8(blendMode) << BLEND_MODE_OFFSET) | (uint8(blendWrite) << BLEND_WRITE_OFFSET);
auto blend = FBlendStateMap::Get()->GetState(blendFlags);
cxt->OMSetBlendState(blend.GetReference(), nullptr, ~0);
auto rs = FRasterizerStateMap::Get()->GetState(RAS_CULL_BACK);
cxt->RSSetState(rs.GetReference());
}
else if (objs.first == ERenderOrder::Translucent)
{
auto ds = FDepthStencilStateMap::Get()->GetState(DS_DEPTH_READ);
cxt->OMSetDepthStencilState(ds.GetReference(), 0);
auto blendMode = EBlendMode::AlphaBlend;
auto blendWrite = EBlendWrite::RGBA;
uint32 blendFlags = (uint8(blendMode) << BLEND_MODE_OFFSET) | (uint8(blendWrite) << BLEND_WRITE_OFFSET);
auto blend = FBlendStateMap::Get()->GetState(blendFlags);
cxt->OMSetBlendState(blend.GetReference(), nullptr, ~0);
auto rs = FRasterizerStateMap::Get()->GetState(RAS_CULL_BACK);
cxt->RSSetState(rs.GetReference());
}
else if (objs.first == ERenderOrder::UI)
{
auto ds = FDepthStencilStateMap::Get()->GetState(0);
cxt->OMSetDepthStencilState(ds.GetReference(), 0);
auto blendMode = EBlendMode::AlphaBlend;
auto blendWrite = EBlendWrite::RGBA;
uint32 blendFlags = (uint8(blendMode) << BLEND_MODE_OFFSET) | (uint8(blendWrite) << BLEND_WRITE_OFFSET);
auto blend = FBlendStateMap::Get()->GetState(blendFlags);
cxt->OMSetBlendState(blend.GetReference(), nullptr, ~0);
auto rs = FRasterizerStateMap::Get()->GetState(RAS_CULL_BACK);
cxt->RSSetState(rs.GetReference());
}
for (auto& obj : objs.second)
{
auto pg = obj.PrimitiveGroup;
FShaderKey key;
key.LitMode = ELightingMode::Phong;
key.VertexElement = obj.GetVertexFlags();
FShaderManager::Get()->Bind(key);
for (auto buf : obj.ConstantBuffers)
{
buf->Bind();
}
for (auto tex : obj.ShaderResources)
{
tex->BindShaderResource(cxt);
}
pg->Draw(obj.InstancingDatas);
}
objs.second.clear();
}
}
| 26.276243 | 108 | 0.693019 | [
"render",
"vector"
] |
5604127cc0ad25ee831cafa0c092f6449c5e419c | 3,071 | cpp | C++ | GameEngine/src/GameEngine/ImGui/ImGuiLayer.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GameEngine/ImGui/ImGuiLayer.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GameEngine/ImGui/ImGuiLayer.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | #include "gepch.h"
#include "GameEngine/ImGui/ImGuiLayer.h"
#include "GameEngine/Core/Application.h"
#include "GameEngine/Core/Input.h"
#include <imgui.h>
#include <backends/imgui_impl_glfw.h>
#include <backends/imgui_impl_opengl3.h>
// TODO: remove
#include <GLFW/glfw3.h>
namespace GameEngine {
ImGuiLayer::ImGuiLayer() :
Layer("ImGuiLayer")
{
}
ImGuiLayer::~ImGuiLayer()
{
}
void ImGuiLayer::OnAttach()
{
GE_PROFILE_FUNCTION();
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
//io.ConfigViewportsNoAutoMerge = true;
//io.ConfigViewportsNoTaskBarIcon = true;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
// Setup Platform/Renderer backends
Application& app = Application::Get();
ImGui_ImplGlfw_InitForOpenGL(static_cast<GLFWwindow*>(app.GetWindow().GetNativeWindow()), true);
ImGui_ImplOpenGL3_Init("#version 410");
}
void ImGuiLayer::OnDetach()
{
GE_PROFILE_FUNCTION();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void ImGuiLayer::BeginFrame()
{
GE_PROFILE_FUNCTION();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void ImGuiLayer::EndFrame()
{
GE_PROFILE_FUNCTION();
ImGuiIO& io = ImGui::GetIO(); (void)io;
Application& app = Application::Get();
// Set window size
io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(), (float)app.GetWindow().GetHeight());
// Render
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Update and Render additional Platform Windows
// (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere.
// For this specific demo app we could also call glfwMakeContextCurrent(window) directly)
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
}
bool ImGuiLayer::OnEvent(const Event& e)
{
bool handled = false;
ImGuiIO& io = ImGui::GetIO();
handled |= e.IsInCategory(EventCategoryMouse) & io.WantCaptureMouse;
handled |= e.IsInCategory(EventCategoryKeyboard) & io.WantCaptureKeyboard;
return handled;
}
}
| 28.174312 | 133 | 0.733963 | [
"render"
] |
560950af46b75df7fd4f5da857f0c58542c4efa4 | 2,928 | cpp | C++ | src/game/fsworld.cpp | nsweb/fracstar | 1ebb53ea8591189a1205fe656ecc7598b9b51ed6 | [
"MIT"
] | null | null | null | src/game/fsworld.cpp | nsweb/fracstar | 1ebb53ea8591189a1205fe656ecc7598b9b51ed6 | [
"MIT"
] | null | null | null | src/game/fsworld.cpp | nsweb/fracstar | 1ebb53ea8591189a1205fe656ecc7598b9b51ed6 | [
"MIT"
] | null | null | null |
#include "../fracstar.h"
#include "fsworld.h"
#include "colevel.h"
#include "levelshader.h"
#include "core/json.h"
#include "engine/controller.h"
#include "engine/camera.h"
#include "engine/entity.h"
#include "engine/entitymanager.h"
#include "gfx/gfxmanager.h"
#include "gfx/shader.h"
#include "gfx/rendercontext.h"
#include "system/profiler.h"
STATIC_MANAGER_CPP(FSWorld);
FSWorld::FSWorld() :
m_current_level_idx(INDEX_NONE),
m_levelshader(nullptr)
{
m_pStaticInstance = this;
}
FSWorld::~FSWorld()
{
m_pStaticInstance = nullptr;
}
void FSWorld::Create()
{
m_levelshader = new LevelShader();
}
void FSWorld::Destroy()
{
BB_DELETE(m_levelshader);
}
bool FSWorld::InitLevels( char const* json_path )
{
json::Object jsn_obj;
if( !jsn_obj.ParseFile( json_path ) )
{
BB_LOG( FSWorld, Log, "FSWorld::InitLevels : cannot open file <%s>", json_path );
return false;
}
json::TokenIdx wtok = jsn_obj.GetToken( "world", json::OBJECT );
json::TokenIdx ltok = jsn_obj.GetToken( "levels", json::ARRAY, wtok );
int level_count = jsn_obj.GetArraySize( ltok );
for( int level_idx = 0; level_idx < level_count; level_idx++ )
{
String level_name;
jsn_obj.GetArrayStringValue( ltok, level_idx, level_name );
String level_path = String::Printf("../data/level/%s/", level_name.c_str());
String level_json = level_path + "level.json";
Entity* plevel = EntityManager::GetStaticInstance()->CreateEntityFromJson( level_json.c_str(), level_name.c_str() );
if( plevel )
EntityManager::GetStaticInstance()->AddEntityToWorld( plevel );
}
if( m_levels.size() )
m_current_level_idx = 0;
return true;
}
CoLevel* FSWorld::GetCurrentLevel()
{
if( m_current_level_idx >= 0 )
return m_levels[m_current_level_idx];
return nullptr;
}
bool FSWorld::SetCurrentLevel( int level_idx )
{
if( level_idx >= 0 && level_idx < m_levels.size() )
{
m_current_level_idx = level_idx;
return true;
}
return false;
}
void FSWorld::AddComponentToWorld( Component* component )
{
if( component->IsA( CoLevel::StaticClass() ) )
{
m_levels.push_back( reinterpret_cast<CoLevel*>( component ) );
}
}
void FSWorld::RemoveComponentFromWorld( Component* component )
{
if( component->IsA( CoLevel::StaticClass() ) )
{
m_levels.remove( reinterpret_cast<CoLevel*>( component ) );
}
}
void FSWorld::Tick( TickContext& tick_ctxt )
{
// (REBIND)
//BGFX_PROFILER_SCOPE( __FUNCTION__, 0xffffffff );
for( int32 i = 0; i < m_levels.size(); ++i )
{
m_levels[i]->Tick( tick_ctxt );
}
}
void FSWorld::_Render( RenderContext& render_ctxt )
{
// (REBIND)
//BGFX_PROFILER_SCOPE( __FUNCTION__, 0xffffffff);
}
| 23.238095 | 125 | 0.634904 | [
"object"
] |
560b66819c7e3b4442a1d2f456f4882dc4d006aa | 1,200 | cpp | C++ | 2007-save_endo/test/test-templates.cpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | 2007-save_endo/test/test-templates.cpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | 2007-save_endo/test/test-templates.cpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
#include "execute.hpp"
int main()
{
int retval = EXIT_SUCCESS;
std::vector<std::pair<std::string, std::string>> tests;
tests.emplace_back(std::make_pair("CIIC", "I"));
tests.emplace_back(std::make_pair("FIIF", "C"));
tests.emplace_back(std::make_pair("PIIC", "F"));
tests.emplace_back(std::make_pair("ICIIF", "P"));
tests.emplace_back(std::make_pair("IFICPCCPIIC", R"(\3)"));
tests.emplace_back(std::make_pair("IIPCICPIIF", "|5|"));
std::cout << "1.." << tests.size() << '\n';
Arrow arrow;
Template output;
std::string actual;
for (size_t t = 0; t < tests.size(); ++t) {
auto const& test_case = tests[t].first;
arrow.dna = test_case;
auto const& expected = tests[t].second;
auto actual = Arrow::to_string(arrow.templates());
if (expected != actual) {
retval = EXIT_FAILURE;
}
std::cout
<< (expected != actual ? "not " : "") << "ok " << t + 1 << " - "
<< test_case << " expected " << expected << " actual " << actual << '\n';
}
return retval;
}
| 26.086957 | 85 | 0.5625 | [
"vector"
] |
560bdff66ab800e8008bab511909cc09891f44e1 | 42 | hpp | C++ | src/boost_mpl_vector_aux__size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_vector_aux__size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_vector_aux__size.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/vector/aux_/size.hpp>
| 21 | 41 | 0.761905 | [
"vector"
] |
560df9acfbe3c9017320e43aec15c29414f22653 | 6,376 | cpp | C++ | src/cfg.cpp | alephzero/alephzero | dfa36cb4ecd6010125b2f48c33014b491b8db5f2 | [
"Unlicense"
] | 28 | 2020-08-13T19:44:02.000Z | 2022-03-23T04:33:53.000Z | src/cfg.cpp | alephzero/alephzero | dfa36cb4ecd6010125b2f48c33014b491b8db5f2 | [
"Unlicense"
] | 104 | 2019-08-06T16:24:04.000Z | 2022-03-08T04:48:42.000Z | src/cfg.cpp | alephzero/alephzero | dfa36cb4ecd6010125b2f48c33014b491b8db5f2 | [
"Unlicense"
] | 11 | 2019-08-06T16:13:41.000Z | 2022-03-26T16:23:11.000Z | #include <a0/alloc.h>
#include <a0/buf.h>
#include <a0/cfg.h>
#include <a0/cfg.hpp>
#include <a0/err.h>
#include <a0/packet.h>
#include <a0/packet.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "c_wrap.hpp"
#include "file_opts.hpp"
#ifdef A0_EXT_NLOHMANN
#include <a0/middleware.h>
#include <a0/middleware.hpp>
#include <a0/string_view.hpp>
#include <a0/transport.h>
#include <a0/transport.hpp>
#include <a0/writer.hpp>
#include <nlohmann/json.hpp>
#include <initializer_list>
#include <type_traits>
#endif // A0_EXT_NLOHMANN
namespace a0 {
namespace {
struct CfgImpl {
#ifdef A0_EXT_NLOHMANN
std::vector<std::weak_ptr<std::function<void(const nlohmann::json&)>>> var_updaters;
#endif // A0_EXT_NLOHMANN
};
} // namespace
Cfg::Cfg(CfgTopic topic) {
set_c_impl<CfgImpl>(
&c,
[&](a0_cfg_t* c, CfgImpl*) {
auto cfo = c_fileopts(topic.file_opts);
a0_cfg_topic_t c_topic{topic.name.c_str(), &cfo};
return a0_cfg_init(c, c_topic);
},
[](a0_cfg_t* c, CfgImpl*) {
a0_cfg_close(c);
});
}
Packet Cfg::read(int flags) const {
auto data = std::make_shared<std::vector<uint8_t>>();
a0_alloc_t alloc = {
.user_data = data.get(),
.alloc = [](void* user_data, size_t size, a0_buf_t* out) {
auto* data = (std::vector<uint8_t>*)user_data;
data->resize(size);
*out = {data->data(), size};
return A0_OK;
},
.dealloc = nullptr,
};
a0_packet_t pkt;
check(a0_cfg_read(&*c, alloc, flags, &pkt));
return Packet(pkt, [data](a0_packet_t*) {});
}
void Cfg::write(Packet pkt) {
check(a0_cfg_write(&*c, *pkt.c));
}
#ifdef A0_EXT_NLOHMANN
void Cfg::mergepatch(nlohmann::json update) {
a0_middleware_t mergepatch_middleware = {
.user_data = &update,
.close = NULL,
.process = NULL,
.process_locked = [](
void* user_data,
a0_transport_locked_t tlk,
a0_packet_t* pkt,
a0_middleware_chain_t chain) mutable {
auto* update = (nlohmann::json*)user_data;
auto cpp_tlk = cpp_wrap<TransportLocked>(tlk);
std::string serial;
if (cpp_tlk.empty()) {
serial = update->dump();
} else {
cpp_tlk.jump_tail();
auto frame = cpp_tlk.frame();
auto flat_packet = cpp_wrap<FlatPacket>({frame.data, frame.hdr.data_size});
auto doc = nlohmann::json::parse(flat_packet.payload());
doc.merge_patch(*update);
serial = doc.dump();
}
pkt->payload = (a0_buf_t){(uint8_t*)serial.data(), serial.size()};
return a0_middleware_chain(chain, pkt);
},
};
cpp_wrap<Writer>(&c->_writer)
.wrap(cpp_wrap<Middleware>(mergepatch_middleware))
.write("");
}
void Cfg::register_var(std::weak_ptr<std::function<void(const nlohmann::json&)>> updater) {
c_impl<CfgImpl>(&c)->var_updaters.push_back(updater);
}
void Cfg::update_var() {
auto json_cfg = nlohmann::json::parse(read().payload());
auto* weak_updaters = &c_impl<CfgImpl>(&c)->var_updaters;
for (size_t i = 0; i < weak_updaters->size();) {
auto strong_updater = weak_updaters->at(i).lock();
if (!strong_updater) {
std::swap(weak_updaters->at(i), weak_updaters->back());
weak_updaters->pop_back();
continue;
}
(*strong_updater)(json_cfg);
i++;
}
}
#endif // A0_EXT_NLOHMANN
namespace {
struct CfgWatcherImpl {
std::vector<uint8_t> data;
std::function<void(Packet)> onpacket;
#ifdef A0_EXT_NLOHMANN
std::function<void(nlohmann::json)> onjson;
#endif // A0_EXT_NLOHMANN
};
} // namespace
CfgWatcher::CfgWatcher(
CfgTopic topic,
std::function<void(Packet)> onpacket) {
set_c_impl<CfgWatcherImpl>(
&c,
[&](a0_cfg_watcher_t* c, CfgWatcherImpl* impl) {
impl->onpacket = std::move(onpacket);
auto cfo = c_fileopts(topic.file_opts);
a0_cfg_topic_t c_topic{topic.name.c_str(), &cfo};
a0_alloc_t alloc = {
.user_data = impl,
.alloc = [](void* user_data, size_t size, a0_buf_t* out) {
auto* impl = (CfgWatcherImpl*)user_data;
impl->data.resize(size);
*out = {impl->data.data(), size};
return A0_OK;
},
.dealloc = nullptr,
};
a0_packet_callback_t c_onpacket = {
.user_data = impl,
.fn = [](void* user_data, a0_packet_t pkt) {
auto* impl = (CfgWatcherImpl*)user_data;
auto data = std::make_shared<std::vector<uint8_t>>();
std::swap(*data, impl->data);
impl->onpacket(Packet(pkt, [data](a0_packet_t*) {}));
}};
return a0_cfg_watcher_init(c, c_topic, alloc, c_onpacket);
},
[](a0_cfg_watcher_t* c, CfgWatcherImpl*) {
a0_cfg_watcher_close(c);
});
}
#ifdef A0_EXT_NLOHMANN
CfgWatcher::CfgWatcher(
CfgTopic topic,
std::function<void(const nlohmann::json&)> onjson) {
set_c_impl<CfgWatcherImpl>(
&c,
[&](a0_cfg_watcher_t* c, CfgWatcherImpl* impl) {
impl->onjson = std::move(onjson);
auto cfo = c_fileopts(topic.file_opts);
a0_cfg_topic_t c_topic{topic.name.c_str(), &cfo};
a0_alloc_t alloc = {
.user_data = impl,
.alloc = [](void* user_data, size_t size, a0_buf_t* out) {
auto* impl = (CfgWatcherImpl*)user_data;
impl->data.resize(size);
*out = {impl->data.data(), size};
return A0_OK;
},
.dealloc = nullptr,
};
a0_packet_callback_t c_onpacket = {
.user_data = impl,
.fn = [](void* user_data, a0_packet_t pkt) {
auto* impl = (CfgWatcherImpl*)user_data;
auto json = nlohmann::json::parse(
string_view((const char*)pkt.payload.data, pkt.payload.size));
impl->onjson(json);
}};
return a0_cfg_watcher_init(c, c_topic, alloc, c_onpacket);
},
[](a0_cfg_watcher_t* c, CfgWatcherImpl*) {
a0_cfg_watcher_close(c);
});
}
#endif // A0_EXT_NLOHMANN
} // namespace a0
| 26.347107 | 91 | 0.590025 | [
"vector"
] |
5617890cb86184ebb8f19a25ea5242f4fe600e5d | 3,346 | cc | C++ | flare/base/thread/thread_local_benchmark.cc | LiuYuHui/flare | f92cb6132e79ef2809fc0291a4923097ec84c248 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 2 | 2021-05-29T04:04:17.000Z | 2022-02-04T05:33:17.000Z | flare/base/thread/thread_local_benchmark.cc | LiuYuHui/flare | f92cb6132e79ef2809fc0291a4923097ec84c248 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | flare/base/thread/thread_local_benchmark.cc | LiuYuHui/flare | f92cb6132e79ef2809fc0291a4923097ec84c248 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2022-02-17T10:13:04.000Z | 2022-02-17T10:13:04.000Z | // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "flare/base/thread/thread_local.h"
#include "thirdparty/benchmark/benchmark.h"
// Run on (76 X 2494.14 MHz CPU s)
// CPU Caches:
// L1 Data 32K (x76)
// L1 Instruction 32K (x76)
// L2 Unified 4096K (x76)
// Load Average: 2.76, 3.56, 7.61
// -----------------------------------------------------------------------------
// Benchmark Time CPU Iterations
// -----------------------------------------------------------------------------
// Benchmark_TlsAlwaysInitializedGet 2.44 ns 2.44 ns 285683009
// Benchmark_TlsAlwaysInitializedSet 2.34 ns 2.34 ns 299918457
// Benchmark_TlsAlwaysInitializedSet/threads:12 0.201 ns 2.35 ns 299573472
// Benchmark_TlsGet 2.59 ns 2.59 ns 270215926
namespace flare {
volatile int v;
void Benchmark_TlsAlwaysInitializedGet(benchmark::State& state) {
static internal::ThreadLocalAlwaysInitialized<int> tls;
*tls.Get() = 0x12345678;
while (state.KeepRunning()) {
// <+84>: mov 0x13499d(%rip),%rdi # tls.offset_.
// <+94>: cmp %rdi,%fs:(%r12) # TLS object cache overrun?
// <+99>: jbe 0x40ff40 # Slow path, reload cache.
// <+101>: mov %fs:0x8(%r12),%rax # TLS object base.
// <+107>: add %rdi,%rax # rax: Object pointer.
// <+110>: mov (%rax),%edx # edx: Value
//
// <+112>: lea 0x134909(%rip),%rax # `v`.
// <+119>: mov %edx,(%rax)
v = *tls.Get();
}
}
BENCHMARK(Benchmark_TlsAlwaysInitializedGet);
static internal::ThreadLocalAlwaysInitialized<int> tls_mt;
void Benchmark_TlsAlwaysInitializedSet(benchmark::State& state) {
while (state.KeepRunning()) {
*tls_mt = 123;
}
}
BENCHMARK(Benchmark_TlsAlwaysInitializedSet);
BENCHMARK(Benchmark_TlsAlwaysInitializedSet)->Threads(12);
void Benchmark_TlsGet(benchmark::State& state) {
static ThreadLocal<int> tls;
*tls.Get() = 0x12345678;
while (state.KeepRunning()) {
// <+108>: mov 0x13470d(%rip),%rdi # Same as above.
// <+115>: mov %rax,(%rbx)
// <+118>: cmp %rdi,%fs:(%r12)
// <+123>: jbe 0x410190
// <+125>: mov %fs:0x8(%r12),%rax
// <+131>: add %rdi,%rax
// <+134>: mov (%rax),%rax # rax: `unique_ptr`.
// <+137>: test %rax,%rax # Initialized?
// <+140>: je 0x410180 # Slow path, initialize TLS.
// <+142>: mov (%rax),%edx # edx: Value loaded.
//
// <+144>: lea 0x1346c9(%rip),%rax # `v`.
// <+151>: mov %edx,(%rax)
v = *tls.Get();
}
}
BENCHMARK(Benchmark_TlsGet);
} // namespace flare
| 35.978495 | 80 | 0.570233 | [
"object"
] |
561c9caa98904e3b4f31db2e39cd8df87eff1638 | 2,061 | cpp | C++ | LuoguCodes/P1731.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1731.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1731.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | // luogu-judger-enable-o2
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define fn "testdata"
#define ll long long
#define int long long
#define pc(x) putchar(x)
#define endln putchar(';\n';)
#define fileIn freopen("testdata.in", "r", stdin)
#define fileOut freopen("testdata.out", "w", stdout)
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)
#ifdef yyfLocal
#define dbg(x) std::clog << #x" = " << (x) << std::endl
#define logs(x) std::clog << (x) << std::endl
#else
#define dbg(x) 42
#define logs(x) 42
#endif
int read() {
int res = 0, flag = 1; char ch = getchar();
while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); }
while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar();
return res * flag;
}
void print(int x) {
if (x < 0) putchar(';-';), x = -x;
if (x > 9) print(x / 10);
putchar(x % 10 + 48);
}
const int M = 15 + 5;
int n, m, ans = -1ull / 2, h[M], r[M];
void dfs(int x = 1, int y = n, int k = 0, int z = m) {
if (y < 0 || x > m + 1 || k >= ans) return;
if (!y && x == m + 1) { k += r[1] * r[1]; ans = std::min(ans, k); return; }
if (k + z + r[1] * r[1] > ans) return;
if (y - r[x - 1] * r[x - 1] * h[x - 1] * z > 0) return;
per(i, r[x - 1] - 1, z) per(j, h[x - 1] - 1, z) if (y - i * i * j >= 0 && x<= m) {
r[x] = i, h[x] = j;
dfs(x + 1, y - i * i * j, k + (i * 2 * j), z - 1);
r[x] = h[x] = 0;
}
}
void solution() {
n = read(), m = read();
h[0] = r[0] = sqrt(n);
dfs();
print(ans == (-1ull / 2) ? 0 : ans), endln;
}
signed main() {
#ifdef yyfLocal
fileIn;
// fileOut;
#else
#ifndef ONLINE_JUDGE
freopen(fn".in", "r", stdin);
freopen(fn".out", "w", stdout);
#endif
#endif
logs("main.exe");
solution();
// 为什么命令行方向上 + 回车出 6,是不是智障设计?
} | 25.444444 | 86 | 0.512858 | [
"vector"
] |
561cd39cfa4be86b356fb2b3ca1a43169fca2331 | 880 | hpp | C++ | meta/include/mgs/meta/concepts/forward_range.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | 24 | 2020-07-01T13:45:50.000Z | 2021-11-04T19:54:47.000Z | meta/include/mgs/meta/concepts/forward_range.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | meta/include/mgs/meta/concepts/forward_range.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <type_traits>
#include <mgs/meta/concepts/forward_iterator.hpp>
#include <mgs/meta/concepts/input_range.hpp>
#include <mgs/meta/detected.hpp>
#include <mgs/meta/iterator_t.hpp>
namespace mgs
{
namespace meta
{
template <typename T>
struct is_forward_range
{
private:
using Iterator = meta::detected_t<iterator_t, T>;
public:
using requirements =
std::tuple<is_input_range<T>, is_forward_iterator<Iterator>>;
static constexpr bool value =
is_input_range<T>::value && is_forward_iterator<Iterator>::value;
static constexpr int trigger_static_asserts()
{
static_assert(value, "T does not model meta::forward_range");
return 1;
}
};
template <typename T>
constexpr auto is_forward_range_v = is_forward_range<T>::value;
template <typename T, typename = std::enable_if_t<is_forward_range_v<T>>>
using forward_range = T;
}
}
| 21.463415 | 73 | 0.746591 | [
"model"
] |
56289931e5b995c5a4f34e5a490f725bbf416436 | 3,935 | cpp | C++ | src-qt5/core/lumina-theme-engine/src/lthemeengine/qsseditordialog.cpp | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 246 | 2018-04-13T20:07:34.000Z | 2022-03-29T01:33:37.000Z | src-qt5/core/lumina-theme-engine/src/lthemeengine/qsseditordialog.cpp | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 332 | 2016-06-21T13:37:10.000Z | 2018-04-06T13:06:41.000Z | src-qt5/core/lumina-theme-engine/src/lthemeengine/qsseditordialog.cpp | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 69 | 2018-04-12T15:46:09.000Z | 2022-03-20T21:21:45.000Z | #include <QFile>
#include <QSettings>
#include "lthemeengine.h"
#include "qsseditordialog.h"
#include "ui_qsseditordialog.h"
#include <QTemporaryFile>
#include <QTextStream>
#include <LuminaXDG.h>
#include <LUtils.h>
QSSEditorDialog::QSSEditorDialog(const QString &filePath, QWidget *parent) : QDialog(parent), m_ui(new Ui::QSSEditorDialog){
m_ui->setupUi(this);
m_filePath = filePath;
QFile file(filePath);
file.open(QIODevice::ReadOnly);
m_ui->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
setWindowTitle(tr("%1 - Style Sheet Editor").arg(file.fileName()));
QSettings settings(lthemeengine::configFile(), QSettings::IniFormat);
restoreGeometry(settings.value("QSSEditor/geometry").toByteArray());
//Generate the list of standard colors for the user to pick
QStringList colors;
colors << tr("base (alternate)")+"::::alternate-base"
<< tr("base")+"::::base"
<< tr("text (bright)")+"::::bright-text"
<< tr("button")+"::::button"
<< tr("text (button)")+"::::button-text"
<< tr("dark")+"::::dark"
<< tr("highlight")+"::::highlight"
<< tr("text (highlight)")+"::::highlighted-text"
<< tr("light")+"::::light"
<< tr("link")+"::::link"
<< tr("link (visited)")+"::::link-visited"
<< tr("mid")+"::::mid"
<< tr("midlight")+"::::midlight"
<< tr("shadow")+"::::shadow"
<< tr("text")+"::::text"
<< tr("window")+"::::window"
<< tr("text (window)")+"::::window-text";
colors.sort(); //sort by translated display name
colorMenu = new QMenu(m_ui->tool_color);
for(int i=0; i<colors.length(); i++){ colorMenu->addAction( colors[i].section("::::",0,0) )->setWhatsThis(colors[i].section("::::",1,1) ); }
m_ui->tool_color->setMenu(colorMenu);
connect(colorMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorPicked(QAction*)) );
validateTimer = new QTimer(this);
validateTimer->setInterval(500); //1/2 second after finish typing
validateTimer->setSingleShot(true);
connect(validateTimer, SIGNAL(timeout()), this, SLOT(validateStyleSheet()) );
connect(m_ui->textEdit, SIGNAL(textChanged()), validateTimer, SLOT(start()) );
}
QSSEditorDialog::~QSSEditorDialog(){
delete m_ui;
}
void QSSEditorDialog::save(){
QFile file(m_filePath);
file.open(QIODevice::WriteOnly);
file.write(m_ui->textEdit->toPlainText().toUtf8());
}
void QSSEditorDialog::hideEvent(QHideEvent *){
QSettings settings(lthemeengine::configFile(), QSettings::IniFormat);
settings.setValue("QSSEditor/geometry", saveGeometry());
}
void QSSEditorDialog::on_buttonBox_clicked(QAbstractButton *button){
QDialogButtonBox::StandardButton id = m_ui->buttonBox->standardButton(button);
if(id == QDialogButtonBox::Ok){
save();
accept();
}
else if(id == QDialogButtonBox::Save){ save(); }
else{ reject(); }
}
void QSSEditorDialog::colorPicked(QAction* act){
QString id = act->whatsThis();
if(id.isEmpty()){ return; }
m_ui->textEdit->insertPlainText( QString("palette(%1)").arg(id) );
}
bool QSSEditorDialog::isStyleSheetValid(const QString &styleSheet){
QTemporaryFile tempfile;
if(tempfile.open()){
QTextStream out(&tempfile);
out << styleSheet;
out.flush();
tempfile.close();
}
QStringList log = LUtils::getCmdOutput("lthemeengine-sstest", QStringList() << tempfile.fileName());
qDebug() << "Got Validation Log:" << log;
return log.join("").simplified().isEmpty();
}
void QSSEditorDialog::validateStyleSheet(){
qDebug() << "Validating StyleSheet:";
bool ok = isStyleSheetValid(m_ui->textEdit->toPlainText());
//Now update the button/label as needed
int sz = this->fontMetrics().height();
if(ok){
m_ui->label_status_icon->setPixmap(LXDG::findIcon("dialog-ok","").pixmap(sz,sz) );
m_ui->label_status_icon->setToolTip(tr("Valid StyleSheet"));
}else{
m_ui->label_status_icon->setPixmap(LXDG::findIcon("dialog-cancel","").pixmap(sz,sz) );
m_ui->label_status_icon->setToolTip(tr("Invalid StyleSheet"));
}
}
| 35.45045 | 142 | 0.678526 | [
"geometry"
] |
5636c1501bfd03e52d17877e8281cba3e470026e | 726 | cpp | C++ | solutions/0264.ugly-number-ii/0264.ugly-number-ii.1570801391.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 1 | 2021-01-14T06:01:02.000Z | 2021-01-14T06:01:02.000Z | solutions/0264.ugly-number-ii/0264.ugly-number-ii.1570801391.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 8 | 2018-03-27T11:47:19.000Z | 2018-11-12T06:02:12.000Z | solutions/0264.ugly-number-ii/0264.ugly-number-ii.1570801391.cpp | nettee/leetcode | 19aa8d54d64cce3679db5878ee0194fad95d8fa1 | [
"MIT"
] | 2 | 2020-04-30T09:47:01.000Z | 2020-12-03T09:34:08.000Z | class Solution {
public:
int nthUglyNumber(int n) {
if (n <= 0) {
return 0;
}
vector<int> uglies(n, 0);
uglies[0] = 1;
int j2 = 0;
int j3 = 0;
int j5 = 0;
for (int k = 1; k < n; k++) {
int u2 = 2 * uglies[j2];
int u3 = 3 * uglies[j3];
int u5 = 5 * uglies[j5];
int u = min(min(u2, u3), u5);
uglies[k] = u;
while (2 * uglies[j2] <= u) {
j2++;
}
while (3 * uglies[j3] <= u) {
j3++;
}
while (5 * uglies[j5] <= u) {
j5++;
}
}
return uglies[n-1];
}
};
| 23.419355 | 41 | 0.323691 | [
"vector"
] |
563926d898afb924d041acc832ed3a1461204a2b | 1,649 | cpp | C++ | test/finalize.cpp | robfors/mruby-finalize | 49eb93eb0b4a2d657b7c763eb2cbdf8fc3aa2d8e | [
"MIT"
] | null | null | null | test/finalize.cpp | robfors/mruby-finalize | 49eb93eb0b4a2d657b7c763eb2cbdf8fc3aa2d8e | [
"MIT"
] | null | null | null | test/finalize.cpp | robfors/mruby-finalize | 49eb93eb0b4a2d657b7c763eb2cbdf8fc3aa2d8e | [
"MIT"
] | null | null | null | #include <queue>
#include <functional>
#include <mruby.h>
#include "finalize.hpp"
using namespace std;
namespace FinalizeTest
{
queue<mrb_int> _finalizer_numbers;
mrb_value _define_finalizer(mrb_state* mrb, mrb_value self)
{
mrb_value object;
mrb_value num_value;
mrb_get_args(mrb, "oo", &object, &num_value);
mrb_int num = mrb_fixnum(num_value);
auto finalizer = [num] { _finalizer_numbers.push(num); };
Finalize::DefinitionAffiliation affiliation = Finalize::define_finalizer(mrb, object, finalizer);
switch(affiliation)
{
case Finalize::DefinitionAffiliation::direct:
return mrb_check_intern_cstr(mrb, "direct");
case Finalize::DefinitionAffiliation::indirect:
return mrb_check_intern_cstr(mrb, "indirect");
default:
return mrb_check_intern_cstr(mrb, "error");
}
}
mrb_value _next_executed_finalizer_value(mrb_state* mrb, mrb_value self)
{
if (_finalizer_numbers.empty())
return mrb_nil_value();
else
{
mrb_int num = _finalizer_numbers.front();
_finalizer_numbers.pop();
return mrb_fixnum_value(num);
}
}
void _setup(mrb_state* mrb)
{
_finalizer_numbers = queue<mrb_int>();
struct RClass* module;
module = mrb_define_module(mrb, "FinalizeTest");
mrb_define_class_method(mrb, module, "define_finalizer", _define_finalizer, MRB_ARGS_REQ(2));
mrb_define_class_method(mrb, module, "next_executed_finalizer_value", _next_executed_finalizer_value, MRB_ARGS_NONE());
}
}
extern "C"
void mrb_mruby_finalize_gem_test(mrb_state* mrb)
{
return FinalizeTest::_setup(mrb);
}
| 21.697368 | 123 | 0.707702 | [
"object"
] |
871e6fb39689116615c2c92e09ce94f7a845d780 | 317 | cpp | C++ | abc180/a.cpp | magurotuna/atcoder-submissions-cpp | afbf5df2f22bcd17d8ad580d3c143602d9af7398 | [
"CC0-1.0"
] | null | null | null | abc180/a.cpp | magurotuna/atcoder-submissions-cpp | afbf5df2f22bcd17d8ad580d3c143602d9af7398 | [
"CC0-1.0"
] | null | null | null | abc180/a.cpp | magurotuna/atcoder-submissions-cpp | afbf5df2f22bcd17d8ad580d3c143602d9af7398 | [
"CC0-1.0"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <map>
#include <stdint.h>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
using i64 = int64_t;
using u64 = uint64_t;
const i64 mod = 1e9 + 7;
int main() {
int n, a, b;
cin >> n >> a >> b;
cout << (n - a + b) << endl;
return 0;
}
| 14.409091 | 30 | 0.608833 | [
"vector"
] |
872219b1d4d884e1529170cb08dc95cd7856a9be | 5,386 | hpp | C++ | src/elliptic/amgSolver/parAlmond/vector.hpp | RonRahaman/nekRS | ffc02bca33ece6ba3330c4ee24565b1c6b5f7242 | [
"BSD-3-Clause"
] | 2 | 2021-09-07T03:00:53.000Z | 2021-12-06T18:08:27.000Z | src/elliptic/amgSolver/parAlmond/vector.hpp | neams-th-coe/nekRS | 5d2c8ab3d14b3fb16db35682336a1f96000698bb | [
"BSD-3-Clause"
] | 2 | 2021-06-27T02:07:27.000Z | 2021-08-24T04:47:42.000Z | src/elliptic/amgSolver/parAlmond/vector.hpp | neams-th-coe/nekRS | 5d2c8ab3d14b3fb16db35682336a1f96000698bb | [
"BSD-3-Clause"
] | 1 | 2019-09-10T20:12:48.000Z | 2019-09-10T20:12:48.000Z | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus, Rajesh Gandham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef PARALMOND_VECTOR_HPP
#define PARALMOND_VECTOR_HPP
namespace parAlmond {
//------------------------------------------------------------------------
//
// Host vector operations
//
//------------------------------------------------------------------------
void vectorSet(const dlong m, const dfloat alpha, dfloat *a);
void vectorRandomize(const dlong m, dfloat *a);
void vectorScale(const dlong m, const dfloat alpha, dfloat *a);
void vectorAddScalar(const dlong m, const dfloat alpha, dfloat *a);
// y = beta*y + alpha*x
void vectorAdd(const dlong n, const dfloat alpha, const dfloat *x,
const dfloat beta, dfloat *y);
// z = beta*y + alpha*x
void vectorAdd(const dlong n, const dfloat alpha, const dfloat *x,
const dfloat beta, const dfloat *y, dfloat *z);
// b = a*b
void vectorDotStar(const dlong m, const dfloat *a, dfloat *b);
// c = alpha*a*b + beta*c
void vectorDotStar(const dlong m, const dfloat alpha, const dfloat *a,
const dfloat *b, const dfloat beta, dfloat *c);
dfloat vectorNorm(const dlong n, const dfloat *a, MPI_Comm comm);
dfloat vectorInnerProd(const dlong n, const dfloat *a, const dfloat *b,
MPI_Comm comm);
dfloat vectorMaxAbs(const dlong n, const dfloat *a, MPI_Comm comm);
// returns aDotbc[0] = a\dot b, aDotbc[1] = a\dot c, aDotbc[2] = b\dot b,
void kcycleCombinedOp1(const dlong n, dfloat *aDotbc, const dfloat *a,
const dfloat *b, const dfloat *c, const dfloat* w,
const bool weighted, MPI_Comm comm);
// returns aDotbcd[0] = a\dot b, aDotbcd[1] = a\dot c, aDotbcd[2] = a\dot d,
void kcycleCombinedOp2(const dlong n, dfloat *aDotbcd, const dfloat *a,
const dfloat *b, const dfloat *c, const dfloat* d,
const dfloat *w, const bool weighted, MPI_Comm comm);
// y = beta*y + alpha*x, and return y\dot y
dfloat vectorAddInnerProd(const dlong n, const dfloat alpha, const dfloat *x,
const dfloat beta, dfloat *y,
const dfloat *w, const bool weighted, MPI_Comm comm);
//------------------------------------------------------------------------
//
// Device vector operations
//
//------------------------------------------------------------------------
void vectorSet(const dlong N, const dfloat alpha, occa::memory o_a);
void vectorRandomize(const dlong m, occa::memory o_a);
void vectorScale(const dlong N, const dfloat alpha, occa::memory o_a);
void vectorAddScalar(const dlong N, const dfloat alpha, occa::memory o_a);
void vectorAdd(const dlong N, const dfloat alpha, occa::memory o_x,
const dfloat beta, occa::memory o_y);
void vectorAdd(const dlong N, const dfloat alpha, occa::memory o_x,
const dfloat beta, occa::memory o_y, occa::memory o_z);
void vectorDotStar(const dlong N, occa::memory o_a, occa::memory o_b);
void vectorDotStar(const dlong N, const dfloat alpha, occa::memory o_a,
occa::memory o_b, const dfloat beta, occa::memory o_c);
dfloat vectorNorm(const dlong n, occa::memory o_a, MPI_Comm comm);
dfloat vectorInnerProd(const dlong N, occa::memory o_x, occa::memory o_y,
MPI_Comm comm);
dfloat vectorMaxAbs(const dlong n, occa::memory o_a, MPI_Comm comm);
// returns aDotbc[0] = a\dot b, aDotbc[1] = a\dot c, aDotbc[2] = b\dot b,
void kcycleCombinedOp1(const dlong N, dfloat *aDotbc, occa::memory o_a,
occa::memory o_b, occa::memory o_c, occa::memory o_w,
const bool weighted, MPI_Comm comm);
// returns aDotbcd[0] = a\dot b, aDotbcd[1] = a\dot c, aDotbcd[2] = a\dot d,
void kcycleCombinedOp2(const dlong N, dfloat *aDotbcd,
occa::memory o_a, occa::memory o_b,
occa::memory o_c, occa::memory o_d,
occa::memory o_w, const bool weighted, MPI_Comm comm);
// y = beta*y + alpha*x, and return y\dot y
dfloat vectorAddInnerProd(const dlong N, const dfloat alpha, occa::memory o_x,
const dfloat beta, occa::memory o_y,
occa::memory o_w, const bool weighted, MPI_Comm comm);
} //namespace parAlmond
#endif | 40.496241 | 88 | 0.643149 | [
"vector"
] |
872427b99e62f5bab75507eb66b44303547b866e | 14,355 | cc | C++ | aibench/benchmark/benchmark_main.cc | XiaoMi/mobile-ai-bench | a91bca47af319b4d88b87b58a6c879de9c910733 | [
"Apache-2.0"
] | 313 | 2018-07-19T08:59:29.000Z | 2022-03-29T04:25:22.000Z | aibench/benchmark/benchmark_main.cc | XiaoMi/mobile-ai-bench | a91bca47af319b4d88b87b58a6c879de9c910733 | [
"Apache-2.0"
] | 41 | 2018-07-20T11:03:03.000Z | 2021-11-19T22:44:24.000Z | aibench/benchmark/benchmark_main.cc | XiaoMi/mobile-ai-bench | a91bca47af319b4d88b87b58a6c879de9c910733 | [
"Apache-2.0"
] | 59 | 2018-07-20T04:02:05.000Z | 2022-02-25T03:45:09.000Z | // Copyright 2018 The MobileAIBench Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <fcntl.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include "gflags/gflags.h"
#include "google/protobuf/message_lite.h"
#include "aibench/port/file_system.h"
#include "aibench/utils/memory.h"
#include "aibench/benchmark/benchmark.h"
#include "aibench/proto/aibench.pb.h"
#include "aibench/proto/base.pb.h"
#ifdef AIBENCH_ENABLE_HIAI
#include "aibench/executors/hiai/hiai_executor.h"
#endif
#ifdef AIBENCH_ENABLE_MACE
#include "aibench/executors/mace/mace_executor.h"
#endif
#ifdef AIBENCH_ENABLE_MNN
#include "aibench/executors/mnn/mnn_executor.h"
#endif
#ifdef AIBENCH_ENABLE_NCNN
#include "aibench/executors/ncnn/ncnn_executor.h"
#endif
#ifdef AIBENCH_ENABLE_SNPE
#include "aibench/executors/snpe/snpe_executor.h"
#endif
#ifdef AIBENCH_ENABLE_TFLITE
#include "aibench/executors/tflite/tflite_executor.h"
#endif
#ifdef AIBENCH_ENABLE_TNN
#include "aibench/executors/tnn/tnn_executor.h"
#endif
#include "aibench/benchmark/imagenet/imagenet_preprocessor.h"
#include "aibench/benchmark/imagenet/imagenet_postprocessor.h"
namespace aibench {
namespace benchmark {
DEFINE_int32(benchmark_option,
Performance, "benchmark option");
DEFINE_int32(run_interval,
10, "run interval between benchmarks, seconds");
DEFINE_int32(num_threads,
4, "number of threads");
DEFINE_int32(executor,
MACE, "the executor to benchmark");
DEFINE_int32(model_name,
MobileNetV1, "the model to benchmark");
DEFINE_int32(device_type,
CPU, "the device_type to benchmark");
DEFINE_bool(quantize,
false, "quantized or float");
namespace {
std::string GetFileName(const std::string &path) {
auto index = path.find_last_of('/');
return index != std::string::npos ? path.substr(index + 1) : path;
}
Status GetBenchInfo(const std::string &filename,
std::vector<std::string> *input_names,
std::vector<std::string> *output_names,
std::vector<std::vector<int64_t>> *input_shapes,
std::vector<std::vector<int64_t>> *output_shapes,
std::vector<DataFormat> *data_formats,
std::string *model_file,
std::string *weight_file) {
std::unique_ptr<aibench::port::ReadOnlyMemoryRegion> file_buffer;
auto fs = GetFileSystem();
auto status = fs->NewReadOnlyMemoryRegionFromFile(filename.c_str(),
&file_buffer);
if (status != Status::SUCCESS) {
LOG(FATAL) << "Failed to read file: " << filename;
}
BenchFactory bench_factory;
bench_factory.ParseFromArray(
reinterpret_cast<const unsigned char *>(file_buffer->data()),
file_buffer->length());
for (const auto &benchmark : bench_factory.benchmarks()) {
if (benchmark.executor() != FLAGS_executor) continue;
for (const auto &model : benchmark.models()) {
if (model.model_name() != FLAGS_model_name) continue;
if (model.quantize() != FLAGS_quantize) continue;
for (const auto &device : model.devices()) {
if (device != FLAGS_device_type) continue;
model_file->assign(GetFileName(model.model_path()));
if (model.has_weight_path()) {
weight_file->assign(GetFileName(model.weight_path()));
}
input_names->assign(model.input_names().begin(),
model.input_names().end());
output_names->assign(model.output_names().begin(),
model.output_names().end());
if (model.input_shape_size() > 0) {
input_shapes->resize(model.input_shape_size());
for (int i = 0; i < model.input_shape_size(); ++i) {
(*input_shapes)[i].assign(model.input_shape(i).shape().begin(),
model.input_shape(i).shape().end());
}
}
if (model.output_shape_size() > 0) {
output_shapes->resize(model.output_shape_size());
for (int i = 0; i < model.output_shape_size(); ++i) {
(*output_shapes)[i].assign(model.output_shape(i).shape().begin(),
model.output_shape(i).shape().end());
}
}
if (model.data_format_size() > 0) {
data_formats->resize(model.data_format_size());
for (int i = 0; i < model.data_format_size(); ++i) {
(*data_formats)[i] = model.data_format(i);
}
}
return Status::SUCCESS;
}
}
}
return Status::UNSUPPORTED;
}
Status GetModelBaseInfo(
const std::string &filename,
ChannelOrder *channel_order,
std::vector<DataFormat> *data_formats,
std::vector<std::vector<int64_t>> *input_shapes,
std::vector<std::vector<int64_t>> *output_shapes,
std::vector<std::vector<float>> *input_means,
std::vector<float> *input_var,
PreProcessor_PreProcessorType *pre_type,
PostProcessor_PostProcessorType *post_type,
MetricEvaluator_MetricEvaluatorType *metric_type) {
std::unique_ptr<aibench::port::ReadOnlyMemoryRegion> file_buffer;
auto fs = GetFileSystem();
auto status = fs->NewReadOnlyMemoryRegionFromFile(filename.c_str(),
&file_buffer);
if (status != Status::SUCCESS) {
LOG(FATAL) << "Failed to read file: " << filename;
}
ModelFactory model_factory;
model_factory.ParseFromArray(
reinterpret_cast<const unsigned char *>(file_buffer->data()),
file_buffer->length());
for (const auto &model : model_factory.models()) {
if (model.model_name() != FLAGS_model_name) continue;
*channel_order = model.channel_order(0);
data_formats->resize(model.data_format_size());
for (int i = 0; i < model.data_format_size(); ++i) {
(*data_formats)[i] = model.data_format(i);
}
input_shapes->resize(model.input_shape_size());
for (int i = 0; i < model.input_shape_size(); ++i) {
(*input_shapes)[i].assign(model.input_shape(i).shape().begin(),
model.input_shape(i).shape().end());
}
output_shapes->resize(model.output_shape_size());
for (int i = 0; i < model.output_shape_size(); ++i) {
(*output_shapes)[i].assign(model.output_shape(i).shape().begin(),
model.output_shape(i).shape().end());
}
const aibench::PreProcessor &pre_processor = model.pre_processor();
*pre_type = pre_processor.type();
input_means->resize(pre_processor.input_mean_size());
for (int i = 0; i < pre_processor.input_mean_size(); ++i) {
(*input_means)[i].assign(pre_processor.input_mean(i).mean().begin(),
pre_processor.input_mean(i).mean().end());
}
input_var->assign(pre_processor.var().begin(), pre_processor.var().end());
*post_type = model.post_processor().type();
*metric_type = model.metric_evaluator().type();
return Status::SUCCESS;
}
return Status::UNSUPPORTED;
}
class PreProcessorFactory {
public:
static std::unique_ptr<PreProcessor> CreatePreProcessor(
PreProcessor_PreProcessorType type,
const std::vector<DataFormat> &data_formats,
const std::vector<std::vector<float>> &input_means,
const std::vector<float> &input_var,
const ChannelOrder channel_order) {
std::unique_ptr<PreProcessor> processor;
switch (type) {
case PreProcessor_PreProcessorType_DefaultProcessor:
processor.reset(new ImageNetPreProcessor(data_formats,
input_means,
input_var,
channel_order));
break;
default:
LOG(FATAL) << "Not supported PreProcessor type: " << type;
}
return std::move(processor);
}
};
class PostProcessorFactory {
public:
static std::unique_ptr<PostProcessor> CreatePostProcessor(
PostProcessor_PostProcessorType type) {
std::unique_ptr<PostProcessor> processor;
switch (type) {
case PostProcessor_PostProcessorType_ImageClassification:
processor.reset(new ImageNetPostProcessor());
break;
default:
LOG(FATAL) << "Not supported PostProcessor type: " << type;
}
return std::move(processor);
}
};
} // namespace
Status Main(int argc, char **argv) {
std::string usage = "run benchmark, e.g. " + std::string(argv[0]) +
" [flags]";
gflags::SetUsageMessage(usage);
gflags::ParseCommandLineFlags(&argc, &argv, true);
auto benchmark_option = static_cast<BenchmarkOption>(FLAGS_benchmark_option);
auto executor_type = static_cast<ExecutorType>(FLAGS_executor);
auto device_type = static_cast<DeviceType>(FLAGS_device_type);
auto model_name = static_cast<ModelName>(FLAGS_model_name);
ChannelOrder channel_order;
std::vector<DataFormat> data_formats;
std::vector<std::vector<int64_t>> input_shapes;
std::vector<std::vector<int64_t>> output_shapes;
std::vector<std::vector<float>> input_means;
std::vector<float> input_var;
PreProcessor_PreProcessorType pre_processor_type;
PostProcessor_PostProcessorType post_processor_type;
MetricEvaluator_MetricEvaluatorType metric_evaluator_type;
if (GetModelBaseInfo("model.pb",
&channel_order,
&data_formats,
&input_shapes,
&output_shapes,
&input_means,
&input_var,
&pre_processor_type,
&post_processor_type,
&metric_evaluator_type) != Status::SUCCESS) {
LOG(FATAL) << "Model info parse failed";
}
std::vector<std::string> input_names;
std::vector<std::string> output_names;
std::string model_file;
std::string weight_file;
if (GetBenchInfo("benchmark.pb",
&input_names,
&output_names,
&input_shapes,
&output_shapes,
&data_formats,
&model_file,
&weight_file) != Status::SUCCESS) {
LOG(FATAL) << "Bench info parse failed";
}
std::unique_ptr<aibench::BaseExecutor> executor;
#ifdef AIBENCH_ENABLE_MACE
if (executor_type == aibench::MACE) {
executor.reset(new aibench::MaceExecutor(device_type,
model_file,
weight_file,
input_names,
output_names));
}
#endif
#ifdef AIBENCH_ENABLE_SNPE
if (executor_type == aibench::SNPE) {
executor.reset(new aibench::SnpeExecutor(device_type, model_file));
}
#endif
#ifdef AIBENCH_ENABLE_NCNN
if (executor_type == aibench::NCNN) {
executor.reset(new aibench::NcnnExecutor(model_file));
}
#endif
#ifdef AIBENCH_ENABLE_TFLITE
if (executor_type == aibench::TFLITE) {
executor.reset(new aibench::TfLiteExecutor(device_type, model_file));
}
#endif
#ifdef AIBENCH_ENABLE_HIAI
if (executor_type == aibench::HIAI) {
std::ostringstream model_name_stream;
model_name_stream << model_name;
executor.reset(new aibench::HiAiExecutor(model_file,
model_name_stream.str()));
}
#endif
#ifdef AIBENCH_ENABLE_MNN
if (executor_type == aibench::MNN) {
executor.reset(new aibench::MnnExecutor(device_type, model_file));
}
#endif
#ifdef AIBENCH_ENABLE_TNN
if (executor_type == aibench::TNN) {
executor.reset(new aibench::TnnExecutor(device_type, model_file,
weight_file));
}
#endif
std::unique_ptr<Benchmark> benchmark;
if (benchmark_option == BenchmarkOption::Performance) {
benchmark.reset(new PerformanceBenchmark(executor.get(),
model_name,
FLAGS_quantize,
input_names,
input_shapes,
output_names,
output_shapes,
FLAGS_run_interval,
FLAGS_num_threads));
} else {
std::unique_ptr<PreProcessor> pre_processor =
PreProcessorFactory::CreatePreProcessor(pre_processor_type,
data_formats,
input_means,
input_var,
channel_order);
std::unique_ptr<PostProcessor> post_processor =
PostProcessorFactory::CreatePostProcessor(post_processor_type);
benchmark.reset(new PrecisionBenchmark(executor.get(),
model_name,
FLAGS_quantize,
input_names,
input_shapes,
output_names,
output_shapes,
FLAGS_run_interval,
FLAGS_num_threads,
std::move(pre_processor),
std::move(post_processor),
metric_evaluator_type));
}
Status status = benchmark->Run();
return status;
}
} // namespace benchmark
} // namespace aibench
int main(int argc, char **argv) { aibench::benchmark::Main(argc, argv); }
| 38.178191 | 79 | 0.600906 | [
"shape",
"vector",
"model"
] |
87312f27d20b0f9ad5ef7886b1c1e548d8a23d64 | 4,909 | cpp | C++ | src/lexer.cpp | zmeadows/guppy | 9b2f5bb2d8f867801b73ea4f2068ed8ee2f90f5c | [
"MIT"
] | 1 | 2015-12-27T18:53:51.000Z | 2015-12-27T18:53:51.000Z | src/lexer.cpp | zmeadows/guppy | 9b2f5bb2d8f867801b73ea4f2068ed8ee2f90f5c | [
"MIT"
] | null | null | null | src/lexer.cpp | zmeadows/guppy | 9b2f5bb2d8f867801b73ea4f2068ed8ee2f90f5c | [
"MIT"
] | null | null | null | #include "util.h"
#include "lexer.h"
bool operator ==(const Token &t1, const Token &t2) {
return std::tie(t1.type, t1.contents) == std::tie(t2.type, t2.contents);
}
bool operator !=(const Token &t1, const Token &t2) {
return !(t1 == t2);
}
std::vector<Token>
tokenize(const std::string &program)
{
std::vector<Token> tokens;
std::string::const_iterator it = program.begin();
unsigned linum = 1;
unsigned colnum = 1;
/* advance the iterator without accidentally stepping past
* the end of the program string */
auto safe_advance = [&it, &program, &linum, &colnum]() -> void {
if (it != program.end()) {
if (*it == '\n') {
linum++;
colnum = 1;
} else {
colnum++;
}
it++;
}
};
/* helper function to add line/column number to token constructor */
auto make_token = [&linum, &colnum]
(Token::Type tt, const std::string &s) -> Token {
return Token(tt, s, linum, colnum - s.size());
};
while (it != program.end())
{
/******************************/
/* WHITESPACE | TAB | NEWLINE */
/******************************/
while (isspace(*it)) safe_advance();
/*****************************/
/* IDENTIFIER | DEF | EXTERN */
/*****************************/
if (isalpha(*it)) { // first letter must be alphabetic
std::string identifier_str;
do {
identifier_str.push_back(*it);
safe_advance();
} while (isalnum(*it)); // the rest can be alphanumeric
auto rit = RESERVED_IDENTIFIERS.find(identifier_str);
if (rit != RESERVED_IDENTIFIERS.end()) {
tokens.push_back(make_token(rit->second, identifier_str));
} else {
tokens.push_back(make_token(Token::Type::IDENTIFIER, identifier_str));
}
/**********/
/* NUMBER */
/**********/
} else if (isdigit(*it)) {
std::string double_str;
do {
double_str.push_back(*it);
safe_advance();
} while (isdigit(*it) || *it == '.');
tokens.push_back(make_token(Token::Type::NUMERIC_LITERAL, double_str));
/***********/
/* COMMENT */
/***********/
} else if (*it == '#') {
do safe_advance(); while
(it != program.end() && *it != '\n' && *it != '\r');
/*******************************/
/* OPERATOR OR RESERVED SYMBOL */
/*******************************/
// TODO: check that length of operator <= 3
} else if (isopch(*it)) { // OPERATOR
std::string operator_str;
do {
operator_str.push_back(*it);
safe_advance();
} while (isopch(*it));
tokens.push_back(make_token(Token::Type::OPERATOR, operator_str));
/***************/
/* END OF FILE */
/***************/
} else if ( (int) *it == 0 ) { // null/eof
tokens.push_back(make_token(Token::Type::END_OF_FILE, ""));
/***************************/
/* RESERVED | UNRECOGNIZED */
/***************************/
} else {
std::string symbol;
bool is_reserved_symbol = false;
do {
symbol.push_back(*it);
is_reserved_symbol = contains(RESERVED_SYMBOLS, symbol);
safe_advance();
} while (!isspace(*it) && !is_reserved_symbol && symbol.size() <= 3);
if (is_reserved_symbol) {
tokens.push_back(make_token(Token::Type::RESERVED_SYMBOL, symbol));
} else {
std::ostringstream err_msg;
err_msg << "unrecognized character '";
err_msg << *it << "' encountered during lexing";
throw std::runtime_error(err_msg.str());
}
}
}
if (tokens.back().type != Token::Type::END_OF_FILE)
tokens.push_back(Token(Token::Type::END_OF_FILE,""));
return tokens;
}
void print_token(const Token &t) {
static const std::map<Token::Type, std::string> TOKEN_TYPE_STRING_MAP = {
{Token::Type::DEFN , "DEFN"},
{Token::Type::EXTERN , "EXTERN"},
{Token::Type::IDENTIFIER , "IDENTIFIER"},
{Token::Type::NUMERIC_LITERAL , "NUMERIC_LITERAL"},
{Token::Type::RESERVED_SYMBOL , "RESERVED_SYMBOL"},
{Token::Type::OPERATOR , "OPERATOR"},
{Token::Type::END_OF_FILE , "EOF"}
};
std::string type_str = TOKEN_TYPE_STRING_MAP.find(t.type)->second;
std::cout << type_str << " (" << t.linum << ":" << t.colnum <<
"):\t\t" << t.contents << std::endl;
}
| 32.509934 | 86 | 0.469138 | [
"vector"
] |
8732107bc04a8397d094ecc114307e6b7c19af63 | 1,694 | hpp | C++ | eval/LANE_evaluation/lane2d/include/spline.hpp | rqbrother/OpenLane | 25e76e2aef0041e809d4c2de52d2d13196e96426 | [
"Apache-2.0"
] | 104 | 2022-03-16T10:50:31.000Z | 2022-03-29T16:14:23.000Z | eval/LANE_evaluation/lane2d/include/spline.hpp | rqbrother/OpenLane | 25e76e2aef0041e809d4c2de52d2d13196e96426 | [
"Apache-2.0"
] | 5 | 2022-03-22T15:08:40.000Z | 2022-03-31T12:18:36.000Z | eval/LANE_evaluation/lane2d/include/spline.hpp | rqbrother/OpenLane | 25e76e2aef0041e809d4c2de52d2d13196e96426 | [
"Apache-2.0"
] | 6 | 2022-03-23T02:05:10.000Z | 2022-03-24T23:18:53.000Z | /* ==============================================================================
Binaries and/or source for the following packages or projects are presented under one or more of the following open
source licenses:
spline.hpp The OpenLane Dataset Authors Apache License, Version 2.0
See:
https://github.com/XingangPan/SCNN/blob/master/tools/lane_evaluation/include/spline.hpp
https://github.com/XingangPan/SCNN/blob/master/LICENSE
Copyright (c) 2022 The OpenLane Dataset Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
============================================================================== */
#ifndef SPLINE_HPP
#define SPLINE_HPP
#include <vector>
#include <cstdio>
#include <math.h>
#include <opencv2/core/core.hpp>
using namespace cv;
using namespace std;
struct Func {
double a_x;
double b_x;
double c_x;
double d_x;
double a_y;
double b_y;
double c_y;
double d_y;
double h;
};
class Spline {
public:
vector<Point2f> splineInterpTimes(const vector<Point2f> &tmp_line, int times);
vector<Point2f> splineInterpStep(vector<Point2f> tmp_line, double step);
vector<Func> cal_fun(const vector<Point2f> &point_v);
};
#endif
| 32.576923 | 115 | 0.687721 | [
"vector"
] |
8738fa504ea76ca77d8713fde0892b884be7861c | 2,596 | cc | C++ | vos/p2/sub/chdo_object/ChdoBase.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/p2/sub/chdo_object/ChdoBase.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/p2/sub/chdo_object/ChdoBase.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | // Copyright (c) 1999, California Institute of Technology
// U. S. Government sponsorship under NASA contract is acknowledged
//////////////////////////////////////////////////////////////////////////////
//
// ChdoBase.h
//
// ChdoBase is the class of an object that contains a generic CHDO
// header. It performs the primary CHDO header parsing/extraction, but does
// not obtain, dump, process, look at, or care about the actual data the CHDO
// contains. This class does not validate the correctness of the header.
// It just parses the header into its defined fields.
//
// Other CHDO headers that inherit from this class should only be capable
// of extracting or parsing CHDO specific values from a buffer suplied to
// the object.
//
//////////////////////////////////////////////////////////////////////////////
#include "ChdoBase.h"
#include "return_status.h"
//////////////////////////////////////////////////////////////////////////////
//
// parse
//
// Ingests a supplied buffer and parses the standard two CHDO fields
// type & length. By default, this routine allocates memory for an internal
// buffer. If the memory can not be allocated or the routine is instructed
// by setting the "pointTo" flag (second parameter), the object will point
// to the buffer passed in as the first parameter and return a non-zero
// status value.
// The option of "pointTo" is intended to be a quicker method of
// ingesting a packet, although more DANGEROUS since the data could
// disappear out from under the object.
//
//////////////////////////////////////////////////////////////////////////////
int ChdoBase::parse(
unsigned char *buffer,
int pointTo )
{ int Status = RTN_NORMAL;
/**
*** Extract CHDO header information
**/
_type = buffer[0] * 256 + buffer[1];
_length = buffer[2] * 256 + buffer[3];
/**
*** Allocate memory for entire CHDO if needed
**/
if (_pointToFlag || _bufferSize < (_length+CHDO_HEADER_LENGTH))
{ if (!_pointToFlag && _buffer != NULL) delete [] _buffer;
_bufferSize = ((_length+CHDO_HEADER_LENGTH) < DEFAULT_CHDO_SIZE) ?
DEFAULT_CHDO_SIZE : (_length+CHDO_HEADER_LENGTH);
_buffer = new unsigned char [_bufferSize];
}
/**
*** If memory could not be added, point to memory that was passed in
*** be parsed, set return status flag as failure.
**/
if ((_pointToFlag = (_buffer == NULL)))
{ _buffer = buffer;
_bufferSize = 0;
Status = RTN_ALLOCATE_ERROR;
} else memcpy(_buffer,buffer,(_length+CHDO_HEADER_LENGTH));
_data = _buffer + 4;
return Status;
}
| 34.157895 | 78 | 0.612866 | [
"object"
] |
873ca2ee3b903acd741b4eb18d0c335e76883fe4 | 3,693 | cpp | C++ | tests/test/wasm/test_snapshots.cpp | csegarragonz/faasm | 6596a6dec43b94adeebb4cb67033bb95a01e1bde | [
"Apache-2.0"
] | null | null | null | tests/test/wasm/test_snapshots.cpp | csegarragonz/faasm | 6596a6dec43b94adeebb4cb67033bb95a01e1bde | [
"Apache-2.0"
] | null | null | null | tests/test/wasm/test_snapshots.cpp | csegarragonz/faasm | 6596a6dec43b94adeebb4cb67033bb95a01e1bde | [
"Apache-2.0"
] | null | null | null | #include <catch2/catch.hpp>
#include "utils.h"
#include <boost/filesystem.hpp>
#include <faabric/util/func.h>
#include <wavm/WAVMWasmModule.h>
using namespace wasm;
namespace tests {
TEST_CASE("Test snapshot and restore for wasm module", "[wasm]")
{
cleanSystem();
std::string user = "demo";
std::string function = "zygote_check";
faabric::Message m = faabric::util::messageFactory(user, function);
std::string mode;
SECTION("In memory") { mode = "memory"; }
SECTION("In file") { mode = "file"; }
SECTION("In state") { mode = "state"; }
std::vector<uint8_t> memoryData;
std::string stateKey = "serialTest";
size_t stateSize;
// Prepare output file
std::string filePath = "/tmp/faasm_serialised";
if (boost::filesystem::exists(filePath.c_str())) {
boost::filesystem::remove(filePath.c_str());
}
// Create the full module
wasm::WAVMWasmModule moduleA;
moduleA.bindToFunction(m);
// Modify the memory of the module to check changes are propagated
uint32_t wasmPtr = moduleA.mmapMemory(1);
uint8_t* nativePtr = moduleA.wasmPointerToNative(wasmPtr);
nativePtr[0] = 0;
nativePtr[1] = 1;
nativePtr[2] = 2;
nativePtr[3] = 3;
nativePtr[4] = 4;
// Add some guard regions to make sure these can be propagated
moduleA.createMemoryGuardRegion();
moduleA.createMemoryGuardRegion();
size_t expectedSizeBytes = moduleA.getMemorySizeBytes();
if (mode == "memory") {
// Serialise to memory
memoryData = moduleA.snapshotToMemory();
} else if (mode == "file") {
// Serialise to file
moduleA.snapshotToFile(filePath);
} else {
// Serialise to state
stateSize = moduleA.snapshotToState(stateKey);
}
// Create the module to be restored but don't execute zygote
wasm::WAVMWasmModule moduleB;
moduleB.bindToFunctionNoZygote(m);
// Restore from snapshot
if (mode == "memory") {
moduleB.restoreFromMemory(memoryData);
} else if (mode == "file") {
moduleB.restoreFromFile(filePath);
} else {
moduleB.restoreFromState(stateKey, stateSize);
}
// Check size of restored memory is as expected
size_t actualSizeBytesB = moduleB.getMemorySizeBytes();
REQUIRE(actualSizeBytesB == expectedSizeBytes);
// Check writes to memory are visible in restored module
uint8_t* nativePtrB = moduleB.wasmPointerToNative(wasmPtr);
REQUIRE(nativePtrB[0] == 0);
REQUIRE(nativePtrB[1] == 1);
REQUIRE(nativePtrB[2] == 2);
REQUIRE(nativePtrB[3] == 3);
REQUIRE(nativePtrB[4] == 4);
// Create a third module from the second one
wasm::WAVMWasmModule moduleC;
moduleC.bindToFunctionNoZygote(m);
// Restore from snapshot
if (mode == "memory") {
moduleC.restoreFromMemory(memoryData);
} else if (mode == "file") {
moduleC.restoreFromFile(filePath);
} else {
moduleC.restoreFromState(stateKey, stateSize);
}
// Check size of restored memory is as expected
size_t actualSizeBytesC = moduleB.getMemorySizeBytes();
REQUIRE(actualSizeBytesC == expectedSizeBytes);
// Check writes to memory are visible in restored module
uint8_t* nativePtrC = moduleC.wasmPointerToNative(wasmPtr);
REQUIRE(nativePtrC[0] == 0);
REQUIRE(nativePtrC[1] == 1);
REQUIRE(nativePtrC[2] == 2);
REQUIRE(nativePtrC[3] == 3);
REQUIRE(nativePtrC[4] == 4);
// Execute all of them
bool successA = moduleA.execute(m);
REQUIRE(successA);
bool successB = moduleB.execute(m);
REQUIRE(successB);
bool successC = moduleC.execute(m);
REQUIRE(successC);
}
}
| 28.407692 | 71 | 0.657731 | [
"vector"
] |
873d65c4bb8fcd25fe5b00e363778630068c1f44 | 1,136 | cpp | C++ | src/AST/AssertAcyclic.cpp | cforall/cforall | 8fde92916a86f7a006b7af82846d5ec9ad0c1346 | [
"BSD-3-Clause"
] | 32 | 2018-11-30T17:37:27.000Z | 2022-02-27T10:57:07.000Z | src/AST/AssertAcyclic.cpp | cforall/cforall | 8fde92916a86f7a006b7af82846d5ec9ad0c1346 | [
"BSD-3-Clause"
] | null | null | null | src/AST/AssertAcyclic.cpp | cforall/cforall | 8fde92916a86f7a006b7af82846d5ec9ad0c1346 | [
"BSD-3-Clause"
] | null | null | null | //
// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// AssertAcyclic.cpp -- Check that ast::ptr does not form a cycle.
//
// Author : Andrew Beach
// Created On : Thu Jun 06 15:00:00 2019
// Last Modified By : Andrew Beach
// Last Modified On : Fri Jun 07 14:32:00 2019
// Update Count : 1
//
#include "AssertAcyclic.hpp"
#include "AST/Pass.hpp"
namespace {
class NoStrongCyclesCore {
std::vector<const ast::Node *> parents;
public:
void previsit( const ast::Node * node ) {
for (auto & parent : parents) {
assert(parent != node);
}
parents.push_back(node);
}
void postvisit( const ast::Node * ) {
parents.pop_back();
}
};
}
namespace ast {
void assertAcyclic( const std::list< ast::ptr< ast::Decl > > & translationUnit ) {
Pass<NoStrongCyclesCore> visitor;
for ( auto & decl : translationUnit ) {
decl->accept( visitor );
}
}
}
// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
| 21.037037 | 82 | 0.644366 | [
"vector"
] |
8740e19e0ad10d8dc9997442af5e33fc71ce4b4b | 1,786 | cpp | C++ | dnn_project/spikework/io_worker.cpp | alexeyche/dnn_old | 58305cf486187575312cef0a753c86a8c7792196 | [
"MIT"
] | null | null | null | dnn_project/spikework/io_worker.cpp | alexeyche/dnn_old | 58305cf486187575312cef0a753c86a8c7792196 | [
"MIT"
] | null | null | null | dnn_project/spikework/io_worker.cpp | alexeyche/dnn_old | 58305cf486187575312cef0a753c86a8c7792196 | [
"MIT"
] | null | null | null |
#include "io_worker.h"
#include <dnn/io/stream.h>
#include <dnn/util/spikes_list.h>
namespace dnn {
void IOWorker::usage() {
cout << "Workers has options:\n";
cout << " --input, -i FILENAME specifying input of worker (optional)\n";
cout << " --output, -o FILENAME specifying output of worker (optional)\n";
cout << " --tee, -t flag meaning to dump output to file without deleting from stack (optional)\n";
cout << " --dt, spike lists converted into time series with specified resolution (default: " << dt << ")\n";
cout << " --jobs, -j jobs for parallel works, default " << jobs << "\n";
cout << " --help, -h show this help message\n";
}
void IOWorker::processArgs(vector<string> &args) {
OptionParser op(args);
bool need_help = false;
op.option("--input", "-i", input_filename, false);
op.option("--output", "-o", output_filename, false);
op.option("-j", "--jobs", jobs, /* required */ false, /* as_flag */ false);
op.option("--help", "-h", need_help, false, true);
op.loption("--dt", dt, false);
if(need_help) {
usage();
std::exit(0);
}
args = op.getRawOptions();
}
void IOWorker::start(Spikework::Stack &s) {
if(!input_filename.empty()) {
ifstream ff(input_filename);
Stream str(ff, Stream::Binary);
Ptr<SerializableBase> o = str.readBase();
if(Ptr<SpikesList> sp = o.as<SpikesList>()) {
s.push(sp->convertToBinaryTimeSeries(dt));
} else {
s.push(o);
}
}
}
void IOWorker::end(Spikework::Stack &s) {
if(!output_filename.empty()) {
Ptr<SerializableBase> p;
if(tee) {
p = s.back();
} else {
p = s.pop();
}
ofstream ff(output_filename);
Stream str(ff, Stream::Binary);
str.writeObject(p.ptr());
}
}
} | 27.476923 | 127 | 0.597424 | [
"vector"
] |
87438633f6236bb7800bf522cd6117f085d85b02 | 1,814 | cpp | C++ | 01_Develop/libXMCocos2D-v3/Source/3d/Morph.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMCocos2D-v3/Source/3d/Morph.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMCocos2D-v3/Source/3d/Morph.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | #include "3d/Morph.h"
namespace cocos3d
{
Morph::Morph(void)
{
_morphTargets = new std::vector<MorphTarget*>();
_curTargets = new std::vector<unsigned int>();
}
Morph::~Morph(void)
{
for( std::vector<MorphTarget*>::iterator iter=_morphTargets->begin(); iter!=_morphTargets->end(); iter++ )
{
delete *iter;
}
delete _morphTargets;
delete _curTargets;
}
MorphTarget* Morph::getMorphTarget(std::string name)
{
std::vector<MorphTarget*>::iterator iter;
for(iter = _morphTargets->begin(); iter!= _morphTargets->end(); ++iter )
{
if((*iter)->name==name)
return *iter;
}
return NULL;
}
MorphTarget* Morph::getMorphTarget(int index)
{
std::vector<MorphTarget*>::iterator iter;
for(iter = _morphTargets->begin(); iter!= _morphTargets->end(); ++iter )
{
if((*iter)->index==index)
return *iter;
}
return NULL;
}
void Morph::addMorphTarget(MorphTarget* target)
{
std::vector<MorphTarget*>::iterator iter;
for(iter = _morphTargets->begin(); iter!= _morphTargets->end(); ++iter )
{
if((*iter)==target)
{
_morphTargets->erase(iter);
break;
}
}
_morphTargets->push_back(target);
}
void Morph::clearCurTarget()
{
_curTargets->clear();
}
bool Morph::pushTarget(unsigned int targetIndex)
{
std::vector<unsigned int>::iterator iter;
for(iter = _curTargets->begin(); iter!= _curTargets->end(); ++iter )
{
if((*iter)==targetIndex)
return false;
}
_curTargets->push_back(targetIndex);
return true;
}
bool Morph::popTarget(unsigned int targetIndex)
{
std::vector<unsigned int>::iterator iter;
for(iter = _curTargets->begin(); iter!= _curTargets->end(); ++iter )
{
if((*iter)==targetIndex)
{
_curTargets->erase(iter);
return true;
}
}
return false;
}
std::vector<unsigned int>* Morph::getCurTargets()
{
return _curTargets;
}
}
| 16.642202 | 107 | 0.666483 | [
"vector",
"3d"
] |
8749c4b9d477599de8f17a508870724cbe17c911 | 1,992 | cc | C++ | tests/atomic_int_vector.cc | tsnorri/libbio | 6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761 | [
"MIT"
] | 2 | 2021-05-21T08:44:53.000Z | 2021-12-24T16:22:56.000Z | tests/atomic_int_vector.cc | tsnorri/libbio | 6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761 | [
"MIT"
] | null | null | null | tests/atomic_int_vector.cc | tsnorri/libbio | 6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018–2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <catch2/catch.hpp>
#include <cstdint>
#include <libbio/int_vector.hh>
namespace gen = Catch::Generators;
namespace lb = libbio;
SCENARIO("An atomic_int_vector may be created", "[atomic_int_vector]")
{
GIVEN("an atomic_int_vector <4, std::uint16_t>")
{
lb::atomic_int_vector <4, std::uint16_t> vec(8);
WHEN("queried for size")
{
THEN("it returns the correct values")
{
REQUIRE(16 == vec.word_bits());
REQUIRE(4 == vec.element_bits());
REQUIRE(4 == vec.element_count_in_word());
REQUIRE(8 == vec.size());
REQUIRE(2 == vec.word_size());
}
}
}
}
SCENARIO("Values may be stored in a atomic_int_vector", "[atomic_int_vector]")
{
GIVEN("an atomic_int_vector <4, std::uint16_t>")
{
lb::atomic_int_vector <4, std::uint16_t> vec(8);
REQUIRE(8 == vec.size());
REQUIRE(2 == vec.word_size());
WHEN("values are stored in the vector with fetch_or()")
{
std::size_t idx(0);
for (auto proxy : vec)
proxy.fetch_or(idx++);
REQUIRE(8 == idx);
THEN("the vector reports the correct values with a range-based for loop")
{
idx = 0;
for (auto proxy : vec)
{
REQUIRE(idx == proxy.load());
++idx;
}
}
THEN("the vector reports the correct values with load()")
{
idx = 0;
while (idx < 8)
{
REQUIRE(idx == vec.load(idx));
++idx;
}
}
THEN("the vector reports the correct values with word iterators")
{
REQUIRE(0x3210 == vec.word_begin()->load());
REQUIRE(0x7654 == (vec.word_begin() + 1)->load());
}
}
}
}
SCENARIO("The vector returns the previous stored value correctly", "[atomic_int_vector]")
{
lb::atomic_int_vector <4, std::uint16_t> vec(8);
REQUIRE(8 == vec.size());
REQUIRE(2 == vec.word_size());
REQUIRE(0x0 == vec(1).fetch_or(0x2));
REQUIRE(0x2 == vec(1).fetch_or(0x1));
REQUIRE(0x3 == vec.load(1));
}
| 22.382022 | 89 | 0.621988 | [
"vector"
] |
8755f86f3c5d42b15e6b9c3cb1dcae0b1c3192bb | 15,338 | cpp | C++ | record/src/agora_node_ext/AgoraSdk.cpp | DGldy/agora-recording | 51913410be475a644174dccca24e73678601c358 | [
"MIT"
] | null | null | null | record/src/agora_node_ext/AgoraSdk.cpp | DGldy/agora-recording | 51913410be475a644174dccca24e73678601c358 | [
"MIT"
] | null | null | null | record/src/agora_node_ext/AgoraSdk.cpp | DGldy/agora-recording | 51913410be475a644174dccca24e73678601c358 | [
"MIT"
] | null | null | null | #include <csignal>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include "IAgoraLinuxSdkCommon.h"
#include "IAgoraRecordingEngine.h"
#include "AgoraSdk.h"
#include "node_async_queue.h"
#include "base/atomic.h"
#include "base/log.h"
#include "opt_parser.h"
namespace agora {
#define MAKE_JS_CALL_0(ev) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 0, nullptr);\
}
#define MAKE_JS_CALL_1(ev, type, param) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
Local<Value> argv[1]{ napi_create_##type##_(isolate, param)\
};\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 1, argv);\
}
#define MAKE_JS_CALL_2(ev, type1, param1, type2, param2) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
Local<Value> argv[2]{ napi_create_##type1##_(isolate, param1),\
napi_create_##type2##_(isolate, param2)\
};\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 2, argv);\
}
#define MAKE_JS_CALL_3(ev, type1, param1, type2, param2, type3, param3) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
Local<Value> argv[3]{ napi_create_##type1##_(isolate, param1),\
napi_create_##type2##_(isolate, param2),\
napi_create_##type3##_(isolate, param3) \
};\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 3, argv);\
}
#define MAKE_JS_CALL_4(ev, type1, param1, type2, param2, type3, param3, type4, param4) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
Local<Value> argv[4]{ napi_create_##type1##_(isolate, param1),\
napi_create_##type2##_(isolate, param2),\
napi_create_##type3##_(isolate, param3), \
napi_create_##type4##_(isolate, param4), \
};\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 4, argv);\
}
#define MAKE_JS_CALL_5(ev, type1, param1, type2, param2, type3, param3, type4, param4, type5, param5) \
auto it = m_callbacks.find(ev); \
if (it != m_callbacks.end()) {\
Isolate *isolate = Isolate::GetCurrent();\
HandleScope scope(isolate);\
Local<Value> argv[5]{ napi_create_##type1##_(isolate, param1),\
napi_create_##type2##_(isolate, param2),\
napi_create_##type3##_(isolate, param3), \
napi_create_##type4##_(isolate, param4), \
napi_create_##type5##_(isolate, param5), \
};\
NodeEventCallback& cb = *it->second;\
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 5, argv);\
}
AgoraSdk::AgoraSdk(): IRecordingEngineEventHandler() {
m_engine = NULL;
m_stopped.store(false);
m_storage_dir = "./";
}
AgoraSdk::~AgoraSdk() {
if (m_engine) {
m_engine->leaveChannel();
m_engine->release();
}
}
bool AgoraSdk::stopped() const {
return m_stopped;
}
bool AgoraSdk::release() {
if (m_engine) {
m_engine->release();
m_engine = NULL;
}
return true;
}
bool AgoraSdk::createChannel(const string &appid, const string &channelKey, const string &name,
uint32_t uid,
agora::recording::RecordingConfig &config)
{
if ((m_engine = agora::recording::IRecordingEngine::createAgoraRecordingEngine(appid.c_str(), this)) == NULL)
return false;
if(linuxsdk::ERR_OK != m_engine->joinChannel(channelKey.c_str(), name.c_str(), uid, config))
return false;
m_config = config;
return true;
}
bool AgoraSdk::leaveChannel() {
if (m_engine) {
m_engine->leaveChannel();
m_stopped = true;
}
return true;
}
int AgoraSdk::startService() {
if (m_engine)
return m_engine->startService();
return 1;
}
int AgoraSdk::stopService() {
if (m_engine)
return m_engine->stopService();
return 1;
}
void AgoraSdk::updateMixLayout(agora::linuxsdk::VideoMixingLayout &layout) {
m_layout = layout;
setVideoMixLayout();
}
agora::linuxsdk::VideoMixingLayout AgoraSdk::getMixLayout() {
return m_layout;
}
//Customize the layout of video under video mixing model
int AgoraSdk::setVideoMixLayout()
{
// recording::RecordingConfig *pConfig = getConfigInfo();
// size_t max_peers = pConfig->channelProfile == linuxsdk::CHANNEL_PROFILE_COMMUNICATION ? 7:17;
if(m_layout.regionCount == 0) return 0;
cout << "color: " << m_layout.backgroundColor << endl;
return setVideoMixingLayout(m_layout);
}
int AgoraSdk::setVideoMixingLayout(const agora::linuxsdk::VideoMixingLayout &layout)
{
int result = -agora::linuxsdk::ERR_INTERNAL_FAILED;
if(m_engine)
result = m_engine->setVideoMixingLayout(layout);
return result;
}
const agora::recording::RecordingEngineProperties* AgoraSdk::getRecorderProperties(){
return m_engine->getProperties();
}
void AgoraSdk::onErrorImpl(int error, agora::linuxsdk::STAT_CODE_TYPE stat_code) {
cerr << "Error: " << error <<",with stat_code:"<< stat_code << endl;
m_engine->stoppedOnError();
agora::recording::node_async_call::async_call([this, error, stat_code]() {
MAKE_JS_CALL_2(REC_EVENT_ERROR, int32, error, int32, stat_code);
});
}
void AgoraSdk::onWarningImpl(int warn) {
cerr << "warn: " << warn << endl;
// leaveChannel();
}
void AgoraSdk::onJoinChannelSuccessImpl(const char * channelId, agora::linuxsdk::uid_t uid) {
cout << "join channel Id: " << channelId << ", with uid: " << uid << endl;
string channelName = channelId;
agora::recording::node_async_call::async_call([this, channelName, uid]() {
MAKE_JS_CALL_2(REC_EVENT_JOIN_CHANNEL, string, channelName.c_str(), uid, uid);
});
}
void AgoraSdk::onLeaveChannelImpl(agora::linuxsdk::LEAVE_PATH_CODE code) {
cout << "leave channel with code:" << code << endl;
agora::recording::node_async_call::async_call([this]() {
MAKE_JS_CALL_0(REC_EVENT_LEAVE_CHANNEL);
});
}
void AgoraSdk::onUserJoinedImpl(unsigned uid, agora::linuxsdk::UserJoinInfos &infos) {
cout << "User " << uid << " joined, RecordingDir:" << (infos.storageDir? infos.storageDir:"NULL") <<endl;
if(infos.storageDir)
{
m_storage_dir = std::string(infos.storageDir);
m_logdir = m_storage_dir;
}
m_peers.push_back(uid);
//When the user joined, we can re-layout the canvas
setVideoMixLayout();
agora::recording::node_async_call::async_call([this, uid]() {
MAKE_JS_CALL_1(REC_EVENT_USER_JOIN, uid, uid);
});
}
void AgoraSdk::onUserOfflineImpl(unsigned uid, agora::linuxsdk::USER_OFFLINE_REASON_TYPE reason) {
cout << "User " << uid << " offline, reason: " << reason << endl;
m_peers.erase(std::remove(m_peers.begin(), m_peers.end(), uid), m_peers.end());
//When the user is offline, we can re-layout the canvas
setVideoMixLayout();
agora::recording::node_async_call::async_call([this, uid]() {
MAKE_JS_CALL_1(REC_EVENT_USER_LEAVE, uid, uid);
});
}
void AgoraSdk::onActiveSpeaker(uid_t uid) {
agora::recording::node_async_call::async_call([this, uid]() {
MAKE_JS_CALL_1(REC_EVENT_ACTIVE_SPEAKER, uid, uid);
});
}
void AgoraSdk::audioFrameReceivedImpl(unsigned int uid, const agora::linuxsdk::AudioFrame *pframe) const
{
char uidbuf[65];
snprintf(uidbuf, sizeof(uidbuf),"%u", uid);
std::string info_name = m_storage_dir + std::string(uidbuf) /*+ timestamp_per_join_*/;
const uint8_t* data = NULL;
uint32_t size = 0;
if (pframe->type == agora::linuxsdk::AUDIO_FRAME_RAW_PCM) {
info_name += ".pcm";
agora::linuxsdk::AudioPcmFrame *f = pframe->frame.pcm;
data = f->pcmBuf_;
size = f->pcmBufSize_;
cout << "User " << uid << ", received a raw PCM frame ,channels:" << f->channels_ <<endl;
} else if (pframe->type == agora::linuxsdk::AUDIO_FRAME_AAC) {
info_name += ".aac";
cout << "User " << uid << ", received an AAC frame" << endl;
agora::linuxsdk::AudioAacFrame *f = pframe->frame.aac;
data = f->aacBuf_;
size = f->aacBufSize_;
}
FILE *fp = fopen(info_name.c_str(), "a+b");
if(fp == NULL) {
cout << "failed to open: " << info_name;
cout<< " ";
cout << "errno: " << errno;
cout<< endl;
return;
}
::fwrite(data, 1, size, fp);
::fclose(fp);
}
void AgoraSdk::videoFrameReceivedImpl(unsigned int uid, const agora::linuxsdk::VideoFrame *pframe) const {
char uidbuf[65];
snprintf(uidbuf, sizeof(uidbuf),"%u", uid);
const char * suffix=".vtmp";
if (pframe->type == agora::linuxsdk::VIDEO_FRAME_RAW_YUV) {
agora::linuxsdk::VideoYuvFrame *f = pframe->frame.yuv;
suffix=".yuv";
cout << "User " << uid << ", received a yuv frame, width: "
<< f->width_ << ", height: " << f->height_ ;
cout<<",ystride:"<<f->ystride_<< ",ustride:"<<f->ustride_<<",vstride:"<<f->vstride_;
cout<< endl;
} else if(pframe->type == agora::linuxsdk::VIDEO_FRAME_JPG) {
suffix=".jpg";
agora::linuxsdk::VideoJpgFrame *f = pframe->frame.jpg;
cout << "User " << uid << ", received an jpg frame, timestamp: "
<< f->frame_ms_ << endl;
struct tm date;
time_t t = time(NULL);
localtime_r(&t, &date);
char timebuf[128];
sprintf(timebuf, "%04d%02d%02d%02d%02d%02d", date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, date.tm_hour, date.tm_min, date.tm_sec);
std::string file_name = m_storage_dir + std::string(uidbuf) + "_" + std::string(timebuf) + suffix;
FILE *fp = fopen(file_name.c_str(), "w");
if(fp == NULL) {
cout << "failed to open: " << file_name;
cout<< " ";
cout << "errno: " << errno;
cout<< endl;
return;
}
::fwrite(f->buf_, 1, f->bufSize_, fp);
::fclose(fp);
return;
} else {
suffix=".h264";
agora::linuxsdk::VideoH264Frame *f = pframe->frame.h264;
cout << "User " << uid << ", received an h264 frame, timestamp: "
<< f->frame_ms_ << ", frame no: " << f->frame_num_ << endl;
}
std::string info_name = m_storage_dir + std::string(uidbuf) /*+ timestamp_per_join_ */+ std::string(suffix);
FILE *fp = fopen(info_name.c_str(), "a+b");
if(fp == NULL) {
cout << "failed to open: " << info_name;
cout<< " ";
cout << "errno: " << errno;
cout<< endl;
return;
}
//store it as file
if (pframe->type == agora::linuxsdk::VIDEO_FRAME_RAW_YUV) {
agora::linuxsdk::VideoYuvFrame *f = pframe->frame.yuv;
::fwrite(f->buf_, 1, f->bufSize_, fp);
}
else {
agora::linuxsdk::VideoH264Frame *f = pframe->frame.h264;
::fwrite(f->buf_, 1, f->bufSize_, fp);
}
::fclose(fp);
}
void AgoraSdk::addEventHandler(const std::string& eventName, Persistent<Object>& obj, Persistent<Function>& callback)
{
NodeEventCallback *cb = new NodeEventCallback();;
cb->js_this.Reset(Isolate::GetCurrent(), obj);
cb->callback.Reset(Isolate::GetCurrent(), callback);
m_callbacks.emplace(eventName, cb);
}
void AgoraSdk::emitError(int err, int stat_code) {
agora::recording::node_async_call::async_call([this, err, stat_code]() {
MAKE_JS_CALL_2(REC_EVENT_ERROR, int32, err, int32, stat_code);
});
}
//added 2.3.3
void AgoraSdk::onAudioVolumeIndication_node(const agora::linuxsdk::AudioVolumeInfo* speakers, unsigned int speakerNumber) {
auto it = m_callbacks.find(RTC_EVENT_AUDIO_VOLUME_INDICATION);
if (it != m_callbacks.end()) {
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<v8::Array> arrSpeakers = v8::Array::New(isolate, speakerNumber);
for(int i = 0; i < speakerNumber; i++) {
Local<Object> obj = Object::New(isolate);
obj->Set(napi_create_string_(isolate, "uid"), napi_create_uid_(isolate, speakers[i].uid));
obj->Set(napi_create_string_(isolate, "volume"), napi_create_uint32_(isolate, speakers[i].volume));
arrSpeakers->Set(i, obj);
}
Local<Value> argv[2]{ arrSpeakers,
napi_create_uint32_(isolate, speakerNumber)
};
NodeEventCallback& cb = *it->second;
cb.callback.Get(isolate)->Call(cb.js_this.Get(isolate), 2, argv);
}
}
void AgoraSdk::onAudioVolumeIndication(const agora::linuxsdk::AudioVolumeInfo* speakers, unsigned int speakerNum){
if (speakers) {
agora::linuxsdk::AudioVolumeInfo* localSpeakers = new agora::linuxsdk::AudioVolumeInfo[speakerNum];
for(int i = 0; i < speakerNum; i++) {
agora::linuxsdk::AudioVolumeInfo tmp = speakers[i];
localSpeakers[i].uid = tmp.uid;
localSpeakers[i].volume = tmp.volume;
}
agora::recording::node_async_call::async_call([this, localSpeakers, speakerNum] {
this->onAudioVolumeIndication_node(localSpeakers, speakerNum);
delete []localSpeakers;
});
}
}
void AgoraSdk::onFirstRemoteVideoDecoded(uid_t uid, int width, int height, int elapsed) {
agora::recording::node_async_call::async_call([this, uid, width, height, elapsed]() {
MAKE_JS_CALL_4(REC_EVENT_FIRST_VIDEO_FRAME, uid, uid, int32, width, int32, height, int32, elapsed);
});
}
void AgoraSdk::onFirstRemoteAudioFrame(uid_t uid, int elapsed) {
agora::recording::node_async_call::async_call([this, uid, elapsed]() {
MAKE_JS_CALL_2(REC_EVENT_FIRST_AUDIO_FRAME, uid, uid, int32, elapsed);
});
}
void AgoraSdk::onReceivingStreamStatusChanged(bool receivingAudio, bool receivingVideo) {
agora::recording::node_async_call::async_call([this, receivingAudio, receivingVideo]() {
MAKE_JS_CALL_2(REC_EVENT_STREAM_CHANGED, bool, receivingAudio, bool, receivingVideo);
});
}
void AgoraSdk::onConnectionLost() {
agora::recording::node_async_call::async_call([this]() {
MAKE_JS_CALL_0(REC_EVENT_CONN_LOST);
});
}
void AgoraSdk::onConnectionInterrupted() {
agora::recording::node_async_call::async_call([this]() {
MAKE_JS_CALL_0(REC_EVENT_CONN_INTER);
});
}
}
| 34.467416 | 141 | 0.619703 | [
"object",
"vector",
"model"
] |
875a0eac6898d9341018a6a3e044d625c45348e1 | 1,116 | hh | C++ | graphs/ConstrainedSWGraph.hh | aalto-speech/wdecoder | 096225714558d1f97a5d3f4814408ad4efaa3788 | [
"BSD-2-Clause"
] | null | null | null | graphs/ConstrainedSWGraph.hh | aalto-speech/wdecoder | 096225714558d1f97a5d3f4814408ad4efaa3788 | [
"BSD-2-Clause"
] | null | null | null | graphs/ConstrainedSWGraph.hh | aalto-speech/wdecoder | 096225714558d1f97a5d3f4814408ad4efaa3788 | [
"BSD-2-Clause"
] | null | null | null | #ifndef SWW_GRAPH_HH
#define SWW_GRAPH_HH
#include <string>
#include <vector>
#include <map>
#include <set>
#include "DecoderGraph.hh"
class SWWGraph : public DecoderGraph {
public:
SWWGraph();
SWWGraph(const std::map<std::string, std::vector<std::string> > &word_segs,
bool wb_symbol=true,
bool connect_cw_network=true,
bool verbose=false);
void create_graph(const std::map<std::string, std::vector<std::string> > &word_segs,
bool wb_symbol=true,
bool connect_cw_network=true,
bool verbose=false);
void create_crossword_network(const std::map<std::string, std::vector<std::string> > &word_segs,
std::vector<DecoderGraph::Node> &nodes,
std::map<std::string, int> &fanout,
std::map<std::string, int> &fanin,
bool wb_symbol_in_middle=false);
void tie_graph(bool no_push=false,
bool verbose=false);
};
#endif /* SWW_GRAPH_HH */
| 28.615385 | 100 | 0.560932 | [
"vector"
] |
875cf5b6636f324089b4729aa8b99bcd53b40a0c | 29,213 | cpp | C++ | ManagedScripts/MPhysClass.cpp | mpforums/RenSharp | 5b3fb8bff2a1772a82a4148bcf3e1265a11aa097 | [
"Apache-2.0"
] | 1 | 2021-10-04T02:34:33.000Z | 2021-10-04T02:34:33.000Z | ManagedScripts/MPhysClass.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 9 | 2019-07-03T19:19:59.000Z | 2020-03-02T22:00:21.000Z | ManagedScripts/MPhysClass.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 2 | 2019-08-14T08:37:36.000Z | 2020-09-29T06:44:26.000Z | /*
Copyright 2020 Neijwiert
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 "stdafx.h"
#include "MPhysClass.h"
#include "MMatrix3D.h"
#include "Mphyscoltest.h"
#include "Mphysinttest.h"
#include "MRenderObjClass.h"
#include "MPhysObserverClass.h"
#include "MDynamicPhysClass.h"
#include "MMoveablePhysClass.h"
#include "MStaticPhysClass.h"
#include "MStaticAnimPhysClass.h"
#include "MDecorationPhysClass.h"
#include "MLightPhysClass.h"
#include "MMaterialEffectClassRefMultiListClass.h"
#include "MVector3.h"
#include "MAABoxClass.h"
#include "MBuildingAggregateClass.h"
#include "MBuildingAggregateDefClass.h"
namespace RenSharp
{
PhysClass::PhysClass(IntPtr pointer)
: CullableClass(pointer)
{
persistClass = gcnew PersistClass(IntPtr(InternalPersistClassPointer));
multiListObjectClass = gcnew MultiListObjectClass(IntPtr(InternalMultiListObjectClassPointer));
}
IPhysClass^ PhysClass::CreatePhysClassWrapper(IntPtr physClassPtr)
{
return CreatePhysClassWrapper(reinterpret_cast<::PhysClass*>(physClassPtr.ToPointer()));
}
bool PhysClass::Equals(Object ^other)
{
if (RefCountClass::Equals(other))
{
return true;
}
if (ReferenceEquals(other, nullptr))
{
return false;
}
auto otherUnmanagedObj = dynamic_cast<IUnmanagedObject ^>(other);
if (otherUnmanagedObj == nullptr || otherUnmanagedObj->Pointer.Equals(IntPtr::Zero))
{
return false;
}
auto otherPostLoadableClass = dynamic_cast<IPostLoadableClass^>(other);
if (otherPostLoadableClass != nullptr)
{
if (persistClass->Equals(otherPostLoadableClass))
{
return true;
}
}
auto otherMultiListObjectClass = dynamic_cast<IMultiListObjectClass ^>(other);
if (otherMultiListObjectClass != nullptr)
{
if (multiListObjectClass->Equals(otherMultiListObjectClass))
{
return true;
}
}
auto otherPhysClass = dynamic_cast<IPhysClass ^>(other);
if (otherPhysClass != nullptr)
{
if (PhysClassPointer.Equals(otherPhysClass->PhysClassPointer))
{
return true;
}
}
return false;
}
void PhysClass::OnPostLoad()
{
persistClass->OnPostLoad();
}
bool PhysClass::Save(IChunkSaveClass ^csave)
{
return persistClass->Save(csave);
}
bool PhysClass::Load(IChunkLoadClass ^cload)
{
return persistClass->Load(cload);
}
void PhysClass::DefinitionChanged()
{
InternalPhysClassPointer->Definition_Changed();
}
bool PhysClass::NeedsTimestep()
{
return InternalPhysClassPointer->Needs_Timestep();
}
void PhysClass::Timestep(float dt)
{
InternalPhysClassPointer->Timestep(dt);
}
void PhysClass::PostTimestepProcess()
{
InternalPhysClassPointer->Post_Timestep_Process();
}
bool PhysClass::CastRay(IPhysRayCollisionTestClass ^rayTest)
{
if (rayTest == nullptr || rayTest->PhysRayCollisionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rayTest");
}
return InternalPhysClassPointer->Cast_Ray(
*reinterpret_cast<::PhysRayCollisionTestClass *>(rayTest->PhysRayCollisionTestClassPointer.ToPointer()));
}
bool PhysClass::CastRay(PhysRayCollisionTestClass ^rayTest)
{
if (rayTest == nullptr)
{
throw gcnew ArgumentNullException("rayTest");
}
IUnmanagedContainer<IPhysRayCollisionTestClass ^> ^tmpRayTest = RenSharpPhysRayCollisionTestClass::CreateRenSharpPhysRayCollisionTestClass(rayTest);
try
{
bool result = InternalPhysClassPointer->Cast_Ray(
*reinterpret_cast<::PhysRayCollisionTestClass *>(tmpRayTest->UnmanagedObject->PhysRayCollisionTestClassPointer.ToPointer()));
rayTest->CopyFrom(tmpRayTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpRayTest;
tmpRayTest = nullptr;
#pragma pop_macro("delete")
}
}
bool PhysClass::CastAABox(IPhysAABoxCollisionTestClass ^boxTest)
{
if (boxTest == nullptr || boxTest->PhysAABoxCollisionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("boxTest");
}
return InternalPhysClassPointer->Cast_AABox(
*reinterpret_cast<::PhysAABoxCollisionTestClass *>(boxTest->PhysAABoxCollisionTestClassPointer.ToPointer()));
}
bool PhysClass::CastAABox(PhysAABoxCollisionTestClass ^boxTest)
{
if (boxTest == nullptr)
{
throw gcnew ArgumentNullException("boxTest");
}
IUnmanagedContainer<IPhysAABoxCollisionTestClass ^> ^tmpBoxTest = RenSharpPhysAABoxCollisionTestClass::CreateRenSharpPhysAABoxCollisionTestClass(boxTest);
try
{
bool result = InternalPhysClassPointer->Cast_AABox(
*reinterpret_cast<::PhysAABoxCollisionTestClass *>(tmpBoxTest->UnmanagedObject->PhysAABoxCollisionTestClassPointer.ToPointer()));
boxTest->CopyFrom(tmpBoxTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpBoxTest;
tmpBoxTest = nullptr;
#pragma pop_macro("delete")
}
}
bool PhysClass::CastOBBox(IPhysOBBoxCollisionTestClass ^boxTest)
{
if (boxTest == nullptr || boxTest->PhysOBBoxCollisionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("boxTest");
}
return InternalPhysClassPointer->Cast_OBBox(
*reinterpret_cast<::PhysOBBoxCollisionTestClass *>(boxTest->PhysOBBoxCollisionTestClassPointer.ToPointer()));
}
bool PhysClass::CastOBBox(PhysOBBoxCollisionTestClass ^boxTest)
{
if (boxTest == nullptr)
{
throw gcnew ArgumentNullException("boxTest");
}
IUnmanagedContainer<IPhysOBBoxCollisionTestClass ^> ^tmpBoxTest = RenSharpPhysOBBoxCollisionTestClass::CreateRenSharpPhysOBBoxCollisionTestClass(boxTest);
try
{
bool result = InternalPhysClassPointer->Cast_OBBox(
*reinterpret_cast<::PhysOBBoxCollisionTestClass *>(tmpBoxTest->UnmanagedObject->PhysOBBoxCollisionTestClassPointer.ToPointer()));
boxTest->CopyFrom(tmpBoxTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpBoxTest;
tmpBoxTest = nullptr;
#pragma pop_macro("delete")
}
}
bool PhysClass::IntersectionTest(IPhysAABoxIntersectionTestClass ^test)
{
if (test == nullptr || test->PhysAABoxIntersectionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("test");
}
return InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysAABoxIntersectionTestClass *>(test->PhysAABoxIntersectionTestClassPointer.ToPointer()));
}
bool PhysClass::IntersectionTest(PhysAABoxIntersectionTestClass ^test)
{
if (test == nullptr)
{
throw gcnew ArgumentNullException("test");
}
IUnmanagedContainer<IPhysAABoxIntersectionTestClass ^> ^tmpTest = RenSharpPhysAABoxIntersectionTestClass::CreateRenSharpPhysAABoxIntersectionTestClass(test);
try
{
bool result = InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysAABoxIntersectionTestClass *>(tmpTest->UnmanagedObject->PhysAABoxIntersectionTestClassPointer.ToPointer()));
test->CopyFrom(tmpTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpTest;
tmpTest = nullptr;
#pragma pop_macro("delete")
}
}
bool PhysClass::IntersectionTest(IPhysOBBoxIntersectionTestClass ^test)
{
if (test == nullptr || test->PhysOBBoxIntersectionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("test");
}
return InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysOBBoxIntersectionTestClass *>(test->PhysOBBoxIntersectionTestClassPointer.ToPointer()));
}
bool PhysClass::IntersectionTest(PhysOBBoxIntersectionTestClass ^test)
{
if (test == nullptr)
{
throw gcnew ArgumentNullException("test");
}
IUnmanagedContainer<IPhysOBBoxIntersectionTestClass ^> ^tmpTest = RenSharpPhysOBBoxIntersectionTestClass::CreateRenSharpPhysOBBoxIntersectionTestClass(test);
try
{
bool result = InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysOBBoxIntersectionTestClass *>(tmpTest->UnmanagedObject->PhysOBBoxIntersectionTestClassPointer.ToPointer()));
test->CopyFrom(tmpTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpTest;
tmpTest = nullptr;
#pragma pop_macro("delete")
}
}
bool PhysClass::IntersectionTest(IPhysMeshIntersectionTestClass ^test)
{
if (test == nullptr || test->PhysMeshIntersectionTestClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("test");
}
return InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysMeshIntersectionTestClass *>(test->PhysMeshIntersectionTestClassPointer.ToPointer()));
}
bool PhysClass::IntersectionTest(PhysMeshIntersectionTestClass ^test)
{
if (test == nullptr)
{
throw gcnew ArgumentNullException("test");
}
IUnmanagedContainer<IPhysMeshIntersectionTestClass ^> ^tmpTest = RenSharpPhysMeshIntersectionTestClass::CreateRenSharpPhysMeshIntersectionTestClass(test);
try
{
bool result = InternalPhysClassPointer->Intersection_Test(
*reinterpret_cast<::PhysMeshIntersectionTestClass *>(tmpTest->UnmanagedObject->PhysMeshIntersectionTestClassPointer.ToPointer()));
test->CopyFrom(tmpTest->UnmanagedObject);
return result;
}
finally
{
#pragma push_macro("delete")
#undef delete
delete tmpTest;
tmpTest = nullptr;
#pragma pop_macro("delete")
}
}
void PhysClass::LinkToCarrier(IPhysClass ^carrier, IRenderObjClass ^carrierSubObj)
{
::PhysClass *carrierPtr;
::RenderObjClass *carrierSubObjPtr;
if (carrier == nullptr || carrier->PhysClassPointer.ToPointer() == nullptr)
{
carrierPtr = nullptr;
}
else
{
carrierPtr = reinterpret_cast<::PhysClass *>(carrier->PhysClassPointer.ToPointer());
}
if (carrierSubObj == nullptr || carrierSubObj->RenderObjClassPointer.ToPointer() == nullptr)
{
carrierSubObjPtr = nullptr;
}
else
{
carrierSubObjPtr = reinterpret_cast<::RenderObjClass *>(carrierSubObj->RenderObjClassPointer.ToPointer());
}
InternalPhysClassPointer->Link_To_Carrier(carrierPtr, carrierSubObjPtr);
}
void PhysClass::LinkToCarrier(IPhysClass ^carrier)
{
if (carrier == nullptr || carrier->PhysClassPointer.ToPointer() == nullptr)
{
InternalPhysClassPointer->Link_To_Carrier(nullptr);
}
else
{
InternalPhysClassPointer->Link_To_Carrier(reinterpret_cast<::PhysClass *>(carrier->PhysClassPointer.ToPointer()));
}
}
IRenderObjClass ^PhysClass::PeekCarrierSubObject()
{
auto result = InternalPhysClassPointer->Peek_Carrier_Sub_Object();
if (result == nullptr)
{
return nullptr;
}
else
{
return gcnew RenderObjClass(IntPtr(result));
}
}
bool PhysClass::Push(Vector3 move)
{
::Vector3 moveVec;
Vector3::ManagedToUnmanagedVector3(move, moveVec);
return InternalPhysClassPointer->Push(moveVec);
}
bool PhysClass::InternalLinkRider(IPhysClass ^rider)
{
if (rider == nullptr || rider->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rider");
}
return InternalPhysClassPointer->Internal_Link_Rider(reinterpret_cast<::PhysClass *>(rider->PhysClassPointer.ToPointer()));
}
bool PhysClass::InternalUnlinkRider(IPhysClass ^rider)
{
if (rider == nullptr || rider->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rider");
}
return InternalPhysClassPointer->Internal_Unlink_Rider(reinterpret_cast<::PhysClass *>(rider->PhysClassPointer.ToPointer()));
}
void PhysClass::SetModel(IRenderObjClass ^model)
{
if (model == nullptr || model->RenderObjClassPointer.ToPointer() == nullptr)
{
InternalPhysClassPointer->Set_Model(nullptr);
}
else
{
InternalPhysClassPointer->Set_Model(reinterpret_cast<::RenderObjClass *>(model->RenderObjClassPointer.ToPointer()));
}
}
IRenderObjClass ^PhysClass::PeekModel()
{
auto result = InternalPhysClassPointer->Peek_Model();
if (result == nullptr)
{
return nullptr;
}
else
{
return gcnew RenderObjClass(IntPtr(result));
}
}
void PhysClass::Render(IntPtr rInfo)
{
if (rInfo.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rInfo");
}
InternalPhysClassPointer->Render(*reinterpret_cast<::RenderInfoClass *>(rInfo.ToPointer()));
}
void PhysClass::VisRender(IntPtr rInfo)
{
if (rInfo.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rInfo");
}
InternalPhysClassPointer->Vis_Render(*reinterpret_cast<::SpecialRenderInfoClass *>(rInfo.ToPointer()));
}
void PhysClass::RenderVisMeshes(IntPtr rInfo)
{
if (rInfo.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("rInfo");
}
InternalPhysClassPointer->Render_Vis_Meshes(*reinterpret_cast<::RenderInfoClass *>(rInfo.ToPointer()));
}
void PhysClass::AddEffectToMe(IMaterialEffectClass ^effect)
{
if (effect == nullptr || effect->MaterialEffectClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("effect");
}
InternalPhysClassPointer->Add_Effect_To_Me(reinterpret_cast<::MaterialEffectClass *>(effect->MaterialEffectClassPointer.ToPointer()));
}
void PhysClass::RemoveEffectFromMe(IMaterialEffectClass ^effect)
{
if (effect == nullptr || effect->MaterialEffectClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("effect");
}
InternalPhysClassPointer->Remove_Effect_From_Me(reinterpret_cast<::MaterialEffectClass *>(effect->MaterialEffectClassPointer.ToPointer()));
}
void PhysClass::IncIgnoreCounter()
{
InternalPhysClassPointer->Inc_Ignore_Counter();
}
void PhysClass::DecIgnoreCounter()
{
InternalPhysClassPointer->Dec_Ignore_Counter();
}
void PhysClass::EnableDebugDisplay(bool onoff)
{
InternalPhysClassPointer->Enable_Debug_Display(onoff);
}
void PhysClass::ForceAwake()
{
InternalPhysClassPointer->Force_Awake();
}
IntPtr PhysClass::AsPhys3Class()
{
return IntPtr(InternalPhysClassPointer->As_Phys3Class());
}
IntPtr PhysClass::AsHumanPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_HumanPhysClass());
}
IntPtr PhysClass::AsRigidBodyClass()
{
return IntPtr(InternalPhysClassPointer->As_RigidBodyClass());
}
IntPtr PhysClass::AsVehiclePhysClass()
{
return IntPtr(InternalPhysClassPointer->As_VehiclePhysClass());
}
IntPtr PhysClass::AsMotorVehicleClass()
{
return IntPtr(InternalPhysClassPointer->As_MotorVehicleClass());
}
IntPtr PhysClass::AsWheeledVehicleClass()
{
return IntPtr(InternalPhysClassPointer->As_WheeledVehicleClass());
}
IntPtr PhysClass::AsMotorcycleClass()
{
return IntPtr(InternalPhysClassPointer->As_MotorcycleClass());
}
IntPtr PhysClass::AsTrackedVehicleClass()
{
return IntPtr(InternalPhysClassPointer->As_TrackedVehicleClass());
}
IntPtr PhysClass::AsVTOLVehicleClass()
{
return IntPtr(InternalPhysClassPointer->As_VTOLVehicleClass());
}
IntPtr PhysClass::AsElevatorPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_ElevatorPhysClass());
}
IntPtr PhysClass::AsDamageableStaticPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_DamageableStaticPhysClass());
}
IntPtr PhysClass::AsDoorPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_DoorPhysClass());
}
IntPtr PhysClass::AsTimedDecorationPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_TimedDecorationPhysClass());
}
IntPtr PhysClass::AsDynamicAnimPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_DynamicAnimPhysClass());
}
IntPtr PhysClass::AsRenderObjPhysClass()
{
return IntPtr(InternalPhysClassPointer->As_RenderObjPhysClass());
}
IntPtr PhysClass::AsProjectileClass()
{
return IntPtr(InternalPhysClassPointer->As_ProjectileClass());
}
IntPtr PhysClass::AsAccessiblePhysClass()
{
return IntPtr(InternalPhysClassPointer->As_AccessiblePhysClass());
}
IntPtr PhysClass::Pointer::get()
{
return AbstractUnmanagedObject::Pointer::get();
}
void PhysClass::Pointer::set(IntPtr value)
{
AbstractUnmanagedObject::Pointer::set(value);
if (Pointer == IntPtr::Zero)
{
persistClass = nullptr;
multiListObjectClass = nullptr;
}
else
{
persistClass = gcnew PersistClass(IntPtr(InternalPersistClassPointer));
multiListObjectClass = gcnew MultiListObjectClass(IntPtr(InternalMultiListObjectClassPointer));
}
}
IntPtr PhysClass::PostLoadableClassPointer::get()
{
return IntPtr(InternalPostLoadableClassPointer);
}
IntPtr PhysClass::PersistClassPointer::get()
{
return IntPtr(InternalPersistClassPointer);
}
IntPtr PhysClass::MultiListObjectClassPointer::get()
{
return IntPtr(InternalMultiListObjectClassPointer);
}
IntPtr PhysClass::PhysClassPointer::get()
{
return IntPtr(InternalPhysClassPointer);
}
bool PhysClass::IsPostLoadRegistered::get()
{
return persistClass->IsPostLoadRegistered;
}
void PhysClass::IsPostLoadRegistered::set(bool value)
{
persistClass->IsPostLoadRegistered = value;
}
IPersistFactoryClass ^PhysClass::Factory::get()
{
return persistClass->Factory;
}
IMultiListNodeClass ^PhysClass::ListNode::get()
{
return multiListObjectClass->ListNode;
}
void PhysClass::ListNode::set(IMultiListNodeClass ^value)
{
multiListObjectClass->ListNode = value;
}
Matrix3D PhysClass::Transform::get()
{
Matrix3D result;
Matrix3D::UnmanagedToManagedMatrix3D(InternalPhysClassPointer->Get_Transform(), result);
return result;
}
void PhysClass::Transform::set(Matrix3D value)
{
::Matrix3D tmp;
Matrix3D::ManagedToUnmanagedMatrix3D(value, tmp);
InternalPhysClassPointer->Set_Transform(tmp);
}
Vector3 PhysClass::Position::get()
{
::Vector3 tmp;
InternalPhysClassPointer->Get_Position(&tmp);
Vector3 result;
Vector3::UnmanagedToManagedVector3(tmp, result);
return result;
}
void PhysClass::Position::set(Vector3 value)
{
::Vector3 tmp;
Vector3::ManagedToUnmanagedVector3(value, tmp);
InternalPhysClassPointer->Set_Position(tmp);
}
float PhysClass::Facing::get()
{
return InternalPhysClassPointer->Get_Facing();
}
uint32 PhysClass::InstanceID::get()
{
return InternalPhysClassPointer->Get_ID();
}
void PhysClass::InstanceID::set(uint32 value)
{
InternalPhysClassPointer->Set_ID(value);
}
int PhysClass::VisObjectID::get()
{
return InternalPhysClassPointer->Get_Vis_Object_ID();
}
void PhysClass::VisObjectID::set(int value)
{
InternalPhysClassPointer->Set_Vis_Object_ID(value);
}
AABoxClass PhysClass::ShadowBlobBox::get()
{
::AABoxClass tmp;
InternalPhysClassPointer->Get_Shadow_Blob_Box(&tmp);
AABoxClass result;
AABoxClass::UnmanagedToManagedAABoxClass(tmp, result);
return result;
}
bool PhysClass::IsCastingShadow::get()
{
return InternalPhysClassPointer->Is_Casting_Shadow();
}
VisibilityModeType PhysClass::VisibilityMode::get()
{
return static_cast<VisibilityModeType>(InternalPhysClassPointer->Get_Visibility_Mode());
}
void PhysClass::VisibilityMode::set(VisibilityModeType value)
{
InternalPhysClassPointer->Set_Visibility_Mode(static_cast<::Visibility_Mode_Type>(value));
}
CollisionGroupType PhysClass::CollisionGroup::get()
{
return static_cast<CollisionGroupType>(InternalPhysClassPointer->Get_Collision_Group());
}
void PhysClass::CollisionGroup::set(CollisionGroupType value)
{
InternalPhysClassPointer->Set_Collision_Group(static_cast<::Collision_Group_Type>(value));
}
bool PhysClass::IsIgnoreMe::get()
{
return InternalPhysClassPointer->Is_Ignore_Me();
}
bool PhysClass::IsImmovable::get()
{
return InternalPhysClassPointer->Is_Immovable();
}
void PhysClass::IsImmovable::set(bool value)
{
InternalPhysClassPointer->Set_Immovable(value);
}
bool PhysClass::IsDisabled::get()
{
return InternalPhysClassPointer->Is_Disabled();
}
void PhysClass::IsDisabled::set(bool value)
{
InternalPhysClassPointer->Set_Disabled(value);
}
bool PhysClass::IsUserControlEnabled::get()
{
return InternalPhysClassPointer->Is_User_Control_Enabled();
}
void PhysClass::IsUserControlEnabled::set(bool value)
{
InternalPhysClassPointer->Enable_User_Control(value);
}
bool PhysClass::IsShadowGenerationEnabled::get()
{
return InternalPhysClassPointer->Is_Shadow_Generation_Enabled();
}
void PhysClass::IsShadowGenerationEnabled::set(bool value)
{
InternalPhysClassPointer->Enable_Shadow_Generation(value);
}
bool PhysClass::IsForceProjectionShadowEnabled::get()
{
return InternalPhysClassPointer->Is_Force_Projection_Shadow_Enabled();
}
void PhysClass::IsForceProjectionShadowEnabled::set(bool value)
{
InternalPhysClassPointer->Enable_Force_Projection_Shadow(value);
}
bool PhysClass::IsDontSaveEnabled::get()
{
return InternalPhysClassPointer->Is_Dont_Save_Enabled();
}
void PhysClass::IsDontSaveEnabled::set(bool value)
{
InternalPhysClassPointer->Enable_Dont_Save(value);
}
bool PhysClass::IsAsleep::get()
{
return InternalPhysClassPointer->Is_Asleep();
}
bool PhysClass::IsWorldSpaceMesh::get()
{
return InternalPhysClassPointer->Is_World_Space_Mesh();
}
void PhysClass::IsWorldSpaceMesh::set(bool value)
{
InternalPhysClassPointer->Enable_Is_World_Space_Mesh(value);
}
bool PhysClass::IsPreLit::get()
{
return InternalPhysClassPointer->Is_Pre_Lit();
}
void PhysClass::IsPreLit::set(bool value)
{
InternalPhysClassPointer->Enable_Is_Pre_Lit(value);
}
bool PhysClass::IsInTheSun::get()
{
return InternalPhysClassPointer->Is_In_The_Sun();
}
void PhysClass::IsInTheSun::set(bool value)
{
InternalPhysClassPointer->Enable_Is_In_The_Sun(value);
}
bool PhysClass::IsStateDirty::get()
{
return InternalPhysClassPointer->Is_State_Dirty();
}
void PhysClass::IsStateDirty::set(bool value)
{
InternalPhysClassPointer->Enable_Is_State_Dirty(value);
}
bool PhysClass::IsHidden::get()
{
return InternalPhysClassPointer->Is_Hidden();
}
void PhysClass::IsHidden::set(bool value)
{
InternalPhysClassPointer->Hide(value);
}
bool PhysClass::IsObjectsSimulationEnabled::get()
{
return InternalPhysClassPointer->Is_Objects_Simulation_Enabled();
}
void PhysClass::IsObjectsSimulationEnabled::set(bool value)
{
InternalPhysClassPointer->Enable_Objects_Simulation(value);
}
IPhysObserverClass ^PhysClass::Observer::get()
{
auto result = InternalPhysClassPointer->Get_Observer();
if (result == nullptr)
{
return nullptr;
}
else
{
return gcnew PhysObserverClass(IntPtr(result));
}
}
void PhysClass::Observer::set(IPhysObserverClass ^value)
{
if (value == nullptr || value->PhysObserverClassPointer.ToPointer() == nullptr)
{
InternalPhysClassPointer->Set_Observer(nullptr);
}
else
{
InternalPhysClassPointer->Set_Observer(reinterpret_cast<::PhysObserverClass *>(value->PhysObserverClassPointer.ToPointer()));
}
}
IPhysDefClass ^PhysClass::Definition::get()
{
auto defPtr = InternalPhysClassPointer->Get_Definition();
if (defPtr == nullptr)
{
return nullptr;
}
else
{
return safe_cast<IPhysDefClass^>(DefinitionClass::CreateDefinitionClassWrapper(defPtr));
}
}
bool PhysClass::IsSimulationDisabled::get()
{
return InternalPhysClassPointer->Is_Simulation_Disabled();
}
unsigned int PhysClass::LastVisibleFrame::get()
{
return InternalPhysClassPointer->Get_Last_Visible_Frame();
}
void PhysClass::LastVisibleFrame::set(unsigned int value)
{
InternalPhysClassPointer->Set_Last_Visible_Frame(value);
}
IPhysClass^ PhysClass::CreatePhysClassWrapper(::PhysClass* physClassPtr)
{
if (physClassPtr == nullptr)
{
throw gcnew ArgumentNullException("physClassPtr");
}
auto lightPhysClassPtr = physClassPtr->As_LightPhysClass();
if (lightPhysClassPtr != nullptr)
{
return gcnew LightPhysClass(IntPtr(lightPhysClassPtr));
}
auto decorationPhysClassPtr = physClassPtr->As_DecorationPhysClass();
if (decorationPhysClassPtr != nullptr)
{
return gcnew DecorationPhysClass(IntPtr(decorationPhysClassPtr));
}
auto moveablePhysClassPtr = physClassPtr->As_MoveablePhysClass();
if (moveablePhysClassPtr != nullptr)
{
return gcnew MoveablePhysClass(IntPtr(moveablePhysClassPtr));
}
auto dynamicPhysClassPtr = physClassPtr->As_DynamicPhysClass();
if (dynamicPhysClassPtr != nullptr)
{
return gcnew DynamicPhysClass(IntPtr(dynamicPhysClassPtr));
}
auto staticAnimPhysClassPtr = physClassPtr->As_StaticAnimPhysClass();
if (staticAnimPhysClassPtr != nullptr)
{
if (physClassPtr->Get_Definition()->Get_Class_ID() == IBuildingAggregateDefClass::BuildingAggregateDefClassClassID)
{
return gcnew BuildingAggregateClass(IntPtr(staticAnimPhysClassPtr));
}
return gcnew StaticAnimPhysClass(IntPtr(staticAnimPhysClassPtr));
}
auto staticPhysClassPtr = physClassPtr->As_StaticPhysClass();
if (staticPhysClassPtr != nullptr)
{
return gcnew StaticPhysClass(IntPtr(staticPhysClassPtr));
}
return gcnew PhysClass(IntPtr(physClassPtr));
}
bool PhysClass::GetFlag(unsigned int flag)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
return helper->GetFlag(flag);
}
void PhysClass::SetFlag(unsigned int flag, bool onoff)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
helper->SetFlag(flag, onoff);
}
::CullableClass *PhysClass::InternalCullableClassPointer::get()
{
return InternalPhysClassPointer;
}
::PostLoadableClass *PhysClass::InternalPostLoadableClassPointer::get()
{
return InternalPhysClassPointer;
}
::PersistClass *PhysClass::InternalPersistClassPointer::get()
{
return InternalPhysClassPointer;
}
::MultiListObjectClass *PhysClass::InternalMultiListObjectClassPointer::get()
{
return InternalPhysClassPointer;
}
::PhysClass *PhysClass::InternalPhysClassPointer::get()
{
return reinterpret_cast<::PhysClass *>(Pointer.ToPointer());
}
unsigned int PhysClass::Flags::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &flags = helper->GetFlags();
return flags;
}
void PhysClass::Flags::set(unsigned int value)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &flags = helper->GetFlags();
flags = value;
}
IRenderObjClass ^PhysClass::Model::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &model = helper->GetModel();
if (model == nullptr)
{
return nullptr;
}
else
{
return gcnew RenderObjClass(IntPtr(model));
}
}
void PhysClass::Model::set(IRenderObjClass ^value)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &model = helper->GetModel();
if (value == nullptr || value->RenderObjClassPointer.ToPointer() == nullptr)
{
model = nullptr;
}
else
{
model = reinterpret_cast<::RenderObjClass *>(value->RenderObjClassPointer.ToPointer());
}
}
String ^PhysClass::Name::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &name = helper->GetName();
return gcnew String(name.Peek_Buffer());
}
void PhysClass::Name::set(String ^value)
{
if (value == nullptr)
{
throw gcnew ArgumentNullException("value");
}
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &name = helper->GetName();
IntPtr valueHandle = Marshal::StringToHGlobalAnsi(value);
try
{
name = reinterpret_cast<char *>(valueHandle.ToPointer());
}
finally
{
Marshal::FreeHGlobal(valueHandle);
}
}
IRefMultiListClass<IMaterialEffectClass ^> ^PhysClass::MaterialEffectsOnMe::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &materialEffectsOnMe = helper->GetMaterialEffectsOnMe();
return gcnew MaterialEffectClassRefMultiListClass(IntPtr(&materialEffectsOnMe));
}
IntPtr PhysClass::StaticLightingCache::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &staticLightingCache = helper->GetStaticLightingCache();
return IntPtr(staticLightingCache);
}
void PhysClass::StaticLightingCache::set(IntPtr value)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &staticLightingCache = helper->GetStaticLightingCache();
staticLightingCache = reinterpret_cast<::LightEnvironmentClass *>(value.ToPointer());
}
unsigned int PhysClass::SunStatusLastUpdated::get()
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &sunStatusLastUpdated = helper->GetSunStatusLastUpdated();
return sunStatusLastUpdated;
}
void PhysClass::SunStatusLastUpdated::set(unsigned int value)
{
auto helper = reinterpret_cast<PhysClassHelper *>(InternalPhysClassPointer);
auto &sunStatusLastUpdated = helper->GetSunStatusLastUpdated();
sunStatusLastUpdated = value;
}
} | 24.323897 | 159 | 0.756786 | [
"render",
"object",
"model",
"transform"
] |
875d1bee7c56276b18a5a27e8b565d7e32e3a2fc | 2,800 | cpp | C++ | ext/include/osgEarthUtil/DataScanner.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthUtil/DataScanner.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthUtil/DataScanner.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/DataScanner>
#include <osgEarthDrivers/gdal/GDALOptions>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#define LC "[DataScanner] "
using namespace osgEarth;
using namespace osgEarth::Util;
using namespace osgEarth::Drivers;
namespace
{
void traverse(const std::string& path,
const std::vector<std::string>& extensions,
ImageLayerVector& out_imageLayers)
{
if ( osgDB::fileType(path) == osgDB::DIRECTORY )
{
osgDB::DirectoryContents files = osgDB::getDirectoryContents(path);
for( osgDB::DirectoryContents::const_iterator f = files.begin(); f != files.end(); ++f )
{
if ( f->compare(".") == 0 || f->compare("..") == 0 )
continue;
std::string filepath = osgDB::concatPaths( path, *f );
traverse( filepath, extensions, out_imageLayers );
}
}
else if ( osgDB::fileType(path) == osgDB::REGULAR_FILE )
{
const std::string ext = osgDB::getLowerCaseFileExtension(path);
if ( std::find(extensions.begin(), extensions.end(), ext) != extensions.end() )
{
GDALOptions gdal;
gdal.url() = path;
//gdal.interpolation() = INTERP_NEAREST;
ImageLayerOptions options( path, gdal );
options.cachePolicy() = CachePolicy::NO_CACHE;
ImageLayer* layer = new ImageLayer(options);
out_imageLayers.push_back( layer );
OE_INFO << LC << "Found " << path << std::endl;
}
}
}
}
void
DataScanner::findImageLayers(const std::string& absRootPath,
const std::vector<std::string>& extensions,
ImageLayerVector& out_imageLayers) const
{
traverse( absRootPath, extensions, out_imageLayers );
}
| 35.897436 | 100 | 0.605357 | [
"vector"
] |
875d5c82d30306248056a92295e57f28afb0754c | 15,675 | cpp | C++ | src/filters/archive/curt/adns_curt.cpp | AuraUAS/aura-core | 4711521074db72ba9089213e14455d89dc5306c0 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 8 | 2016-08-03T19:35:03.000Z | 2019-12-15T06:25:05.000Z | src/filters/archive/curt/adns_curt.cpp | jarilq/aura-core | 7880ed265396bf8c89b783835853328e6d7d1589 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 4 | 2018-09-27T15:48:56.000Z | 2018-11-05T12:38:10.000Z | src/filters/archive/curt/adns_curt.cpp | jarilq/aura-core | 7880ed265396bf8c89b783835853328e6d7d1589 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 5 | 2017-06-28T19:15:36.000Z | 2020-02-19T19:31:24.000Z | /**
* \file: curt_adns.cpp
*
* Test bed for ADNS experimentation
*
* Copyright (C) 2009 - Curtis L. Olson
*
* $Id: umn_interface.cpp,v 1.1 2009/05/15 17:04:56 curt Exp $
*/
#include <pyprops.hxx>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h> // temp: exit()
#include "include/globaldefs.h"
#include "sensors/gps_mgr.hxx"
#include "math/SGMath.hxx"
#include "glocal.hxx"
#include "adns_curt.hxx"
// property nodes
static pyPropertyNode imu_node;
static pyPropertyNode gps_node;
static pyPropertyNode filter_node;
//
static bool init_pos = false;
//
static SGGeod pos_geod; // Geodetic position
static SGVec3d pos_ecef; // Position in the ECEF frame
static SGVec3d vel_ned; // Velocity in the NED frame
static SGVec3d glocal_ned; // Local Gravity Vector in the NED frame
static SGVec3d total_accel_sum_body;
static SGVec3d total_accel_sum_ned;
static SGVec3d accel_sum_ned;
//
static SGQuatd ned2body;
static SGQuatd ecef2ned;
static SGVec3d gyro_bias;
// bind to property tree
static bool bind_properties( string output_path ) {
// initialize property nodes
imu_node = pyGetNode("/sensors/imu", true);
gps_node = pyGetNode("/sensors/gps", true);
filter_node = pyGetNode(output_path, true);
return true;
}
int curt_adns_init( string output_path, pyPropertyNode *config ) {
bind_properties( output_path );
filter_node.setString( "navigation", "invalid" );
init_pos = false;
return 1;
}
static int set_initial_conditions( SGGeod pos, SGVec3d vel ) {
pos_geod = pos;
pos_ecef = SGVec3d::fromGeod(pos_geod);
ecef2ned = SGQuatd::fromLonLat(pos_geod);
vel_ned = vel;
SGVec3d euler_ned( 0.0, 0.0, 0.0 );
ned2body = SGQuatd::fromYawPitchRollDeg( euler_ned[2],
euler_ned[1],
euler_ned[0] );
glocal_ned = local_gravity( pos_geod.getLatitudeRad(),
pos_geod.getElevationM() );
total_accel_sum_body = SGVec3d(0.0, 0.0, 0.0);
total_accel_sum_ned = SGVec3d(0.0, 0.0, 0.0);
accel_sum_ned = SGVec3d(0.0, 0.0, 0.0);
gyro_bias = SGVec3d(0.0, 0.0, 0.0);
return true;
}
/* +X axis = forward out the nose
* +Y axis = out right wing
* +Z axis = down
*
* +roll = right (right wing down, left wing up)
* +pitch = nose up
* +yaw = nose right
*
* +x accel = forward out the nose
* +y accel = out right wing
* +z accel = down
*/
static int propagate_ins( double dt,
SGVec3d gyro,
SGVec3d accel_body,
SGVec3d mag )
{
static SGVec3d xaxis = SGVec3d(1.0, 0.0, 0.0);
static SGVec3d yaxis = SGVec3d(0.0, 1.0, 0.0);
static SGVec3d zaxis = SGVec3d(0.0, 0.0, 1.0);
// compute a quaternion representing the sensed rotation of all
// three combined axes
SGQuatd xrot = SGQuatd::fromAngleAxis( (gyro[0] + gyro_bias[0])*dt, xaxis );
SGQuatd yrot = SGQuatd::fromAngleAxis( (gyro[1] + gyro_bias[1])*dt, yaxis );
SGQuatd zrot = SGQuatd::fromAngleAxis( gyro[2]*dt, zaxis );
SGQuatd rot_body = zrot * yrot * xrot;
// update the ned2body transform (body orientation estimate)
ned2body = ned2body * rot_body;
// transform the body acceleration vector into the ned frame
SGVec3d accel_ned = ned2body.backTransform(accel_body);
/* printf("accel body=%.8f %.8f %.8f ned=%.8f %.8f %.8f\n",
accel_body[0], accel_body[1], accel_body[2],
accel_ned[0], accel_ned[1], accel_ned[2] ); */
// sum the total raw inertial accelerations before gravity is added in
// (because if our attitude estimate is off, the gravity vector
// correction will skew everything.)
total_accel_sum_body += accel_body * dt;
total_accel_sum_ned += accel_ned * dt;
// FIXME: Add correction for Corriolis forces here (maybe? somewhere?!
// add in the local gravity vector (danger, this could introduce a
// big error if the attitude estimate is off) (FIXME: THINK HERE)
accel_ned += glocal_ned;
// sum the gravity corrected raw inertial accelerations, note that
// if there is an attitude estimate error, this can be detected in
// the correction phase by comparing against gps derived data
accel_sum_ned += accel_ned * dt;
// update the inertial velocity in the ned frame
vel_ned += accel_ned * dt;
// transform the ned velocity vector into the ecef frame
SGVec3d vel_ecef = ecef2ned.backTransform(vel_ned);
// update the position in the ecef frame
pos_ecef += vel_ecef * dt;
// compute new geodetic position
pos_geod = SGGeod::fromCart(pos_ecef);
// compute new ecef2ned transform
ecef2ned = SGQuatd::fromLonLat(pos_geod);
// compute new local gravity vector
glocal_ned = local_gravity( pos_geod.getLatitudeRad(),
pos_geod.getElevationM() );
return 1;
}
// compute an estimate of roll and pitch based on our local
// "percieved" gravity vector in body coordinates
static int g_correction( double dt, SGVec3d gps_vel_ned ) {
static bool inited = false;
static SGVec3d last_gps_vel_ned;
static double the_sum = 0.0;
static double phi_sum = 0.0;
if ( !inited ) {
inited = true;
last_gps_vel_ned = gps_vel_ned;
}
if ( dt <= 0 ) {
return 0;
}
// this will be close to zero if the velocity vector hasn't
// changed much
// double time_factor = 1.0 / dt;
// SGVec3d gps_accel = (gps_vel_ned - last_gps_vel_ned) * time_factor;
// evaluate the length of the total acceleration vector relative
// to gravity
double glen = glocal_ned[2] * dt;
double accel_len = length(total_accel_sum_body);
// double gps_accel_len = length(gps_accel);
// double dlen = fabs(1.0 - accel_len/glen);
double y1 = sqrt( total_accel_sum_body[1] * total_accel_sum_body[1] +
total_accel_sum_body[2] * total_accel_sum_body[2] );
double x1 = total_accel_sum_body[0];
double y2 = sqrt( total_accel_sum_body[0] * total_accel_sum_body[0] +
total_accel_sum_body[2] * total_accel_sum_body[2] );
double x2 = total_accel_sum_body[1];
if ( total_accel_sum_body[2] < 0.0 ) {
y1 *= -1.0;
y2 *= -1.0;
}
double the_gest = SGD_PI_2 + atan2( y1, x1 );
double phi_gest = -SGD_PI_2 - atan2( y2, x2 );
printf("correction dt=%.2f\n", dt);
printf(" total_accel_sum_body=%.3f %.3f %.3f (%.3f) (%.3f g)\n",
total_accel_sum_body[0],
total_accel_sum_body[1],
total_accel_sum_body[2],
length(total_accel_sum_body),
accel_len/glen );
printf( "pitch est = %.2f\n", the_gest * SGD_RADIANS_TO_DEGREES);
printf( "roll est = %.2f\n", phi_gest * SGD_RADIANS_TO_DEGREES);
// avoid any correction work unless the total accel vector is very
// close to 'g'
if ( fabs( 1.0 - accel_len / glen ) < 0.01 ) {
// retrieve our current roll and pitch estimates
double psi_rad, the_rad, phi_rad;
ned2body.getEulerRad( psi_rad, the_rad, phi_rad );
double phi_err = phi_gest - phi_rad;
double the_err = the_gest - the_rad;
phi_sum += phi_err;
the_sum += the_err;
static SGVec3d xaxis = SGVec3d(1.0, 0.0, 0.0);
static SGVec3d yaxis = SGVec3d(0.0, 1.0, 0.0);
printf("(the) gest = %.2f curr = %.2f diff = %.2f\n",
the_gest, the_rad, the_err);
printf("(phi) gest = %.2f curr = %.2f diff = %.2f\n",
phi_gest, phi_rad, phi_err);
// scale gain according to how close the total accel vector is
// to gravity.
double pgain = 0.5;
double igain = 0.000;
double phi_correction = ( phi_err * pgain + phi_sum * igain ) * dt;
double the_correction = ( the_err * pgain + the_sum * igain ) * dt;
SGQuatd xrot = SGQuatd::fromAngleAxis( phi_correction, xaxis );
SGQuatd yrot = SGQuatd::fromAngleAxis( the_correction, yaxis );
SGQuatd rot_body = yrot * xrot;
// update the ned2body transform (body orientation estimate)
ned2body = ned2body * rot_body;
double phi_bias = phi_err * pgain * dt /*phi_correction*/;
double the_bias = the_err * pgain * dt /*the_correction*/;
gyro_bias[0] = 0.999 * gyro_bias[0] + 0.001 * phi_bias;
gyro_bias[1] = 0.999 * gyro_bias[1] + 0.001 * the_bias;
printf("bias\t%.4f\t%.6f\t%.6f\t%.6f\t%.6f\n",
dt, phi_bias, the_bias, gyro_bias[0], gyro_bias[1]);
}
last_gps_vel_ned = gps_vel_ned;
return 1;
}
// compute an estimate of yaw based on our local "percieved" gravity
// vector in body coordinates transformed to ned coordinates (using
// our attitude estimate) and then compared against the total gps
// acceleration vector. These two acceleration vectors should align
// if our attitude estimate is correct, however, there's no way to
// know which combinations of roll, pitch, and yaw transforms we
// should use to correct the situation. We are already correcting
// roll/pitch when our sensed acceleration vector is close to g, so we
// only adjust yaw here.
static int v_correction( double dt, SGVec3d gps_vel_ned ) {
static bool inited = false;
static SGVec3d last_gps_vel_ned;
static SGVec3d last_vel_ned;
if ( !inited ) {
inited = true;
last_gps_vel_ned = gps_vel_ned;
last_vel_ned = vel_ned;
}
if ( dt <= 0 ) {
return 0;
}
double time_factor = 1.0 / dt;
SGVec3d gps_accel = (gps_vel_ned - last_gps_vel_ned) * time_factor;
// subtract gravity
SGVec3d total_gps_accel = gps_accel - glocal_ned * dt;
// compute our gravity estimate (subject to attitude estimate error)
SGVec3d g_est = accel_sum_ned - total_accel_sum_ned;
printf("correction dt=%.2f\n", dt);
printf(" gps_accel=%.3f %.3f %.3f (%.3f)\n",
gps_accel[0], gps_accel[1], gps_accel[2], length(gps_accel));
printf(" total_gps_accel=%.3f %.3f %.3f (%.3f)\n",
total_gps_accel[0], total_gps_accel[1], total_gps_accel[2],
length(total_gps_accel));
printf(" accel_sum_ned=%.3f %.3f %.3f (%.3f)\n",
accel_sum_ned[0], accel_sum_ned[1], accel_sum_ned[2],
length(accel_sum_ned));
printf(" total_accel_sum_ned=%.3f %.3f %.3f (%.3f)\n",
total_accel_sum_ned[0],
total_accel_sum_ned[1],
total_accel_sum_ned[2],
length(total_accel_sum_ned));
printf(" g_est=%.3f %.3f %.3f (%.3f)\n",
g_est[0], g_est[1], g_est[2], length(g_est) );
// FIXME: ins_angle computation?
double gps_angle = atan2( total_gps_accel[0], total_gps_accel[1] );
double ins_angle = atan2( total_accel_sum_ned[0], total_accel_sum_ned[1] );
double angle = gps_angle - ins_angle;
while ( angle < -SGD_PI ) { angle += SGD_2PI; }
while ( angle > SGD_PI ) { angle -= SGD_2PI; }
printf("hdg:\t%.4f\t%.4f\t%.4f\t", gps_angle, ins_angle, angle);
double max_angle = 8.0 * 0.0174; // radians
if ( angle > max_angle ) { angle = max_angle; }
if ( angle < -max_angle ) { angle = -max_angle; }
#ifdef OLD_STUFF
// SGQuatd correction = SGQuatd::fromRotateTo( accel_sum_ned, gps_accel );
SGQuatd direct_to = SGQuatd::fromRotateTo( total_gps_accel,
total_accel_sum_ned );
double angle;
SGVec3d axis;
direct_to.getAngleAxis( angle, axis );
printf("estimate off by %.2f degrees\n",
angle * SGD_RADIANS_TO_DEGREES );
#endif
// scale gain according to how far different the total accel
// vector length is to gravity vector length.
double glen = glocal_ned[2] * dt;
double accel_len = length(total_accel_sum_body);
double dlen = accel_len/glen - 1.0;
double gain = 0.0;
if ( dlen > 0.0 ) {
gain = 10.0 * dlen;
}
printf("%.3f %.3f ", accel_len/glen, gain);
angle *= gain * dt;
printf("%.3f\n", angle);
SGVec3d zaxis;
zaxis = SGVec3d(0.0, 0.0, -1.0);
SGQuatd correction = SGQuatd::fromAngleAxis( angle, zaxis );
// correction * ned2body means do rotation in ned space (not body space)
ned2body = correction * ned2body;
last_gps_vel_ned = gps_vel_ned;
last_vel_ned = vel_ned;
return 1;
}
static int update_ins( double gps_dt, SGGeod gps_pos, SGVec3d gps_vel_ned )
{
// converge towards the gravity vector
g_correction( gps_dt, gps_vel_ned );
// converge towards correct yaw
v_correction( gps_dt, gps_vel_ned );
pos_ecef = SGVec3d::fromGeod(gps_pos);
ecef2ned = SGQuatd::fromLonLat(gps_pos);
vel_ned = gps_vel_ned;
total_accel_sum_body = SGVec3d(0.0, 0.0, 0.0);
total_accel_sum_ned = SGVec3d(0.0, 0.0, 0.0);
accel_sum_ned = SGVec3d(0.0, 0.0, 0.0);
return 1;
}
int curt_adns_update( double imu_dt ) {
// printf("imu dt = %.12f\n", imu_dt);
static double last_gps_time = 0.0;
if ( GPS_age() < 1 && !init_pos ) {
last_gps_time = gps_node.getDouble("timestamp");
SGGeod pos = SGGeod::fromDegM( gps_node.getDouble("longitude_deg"),
gps_node.getDouble("latitude_deg"),
gps_node.getDouble("altitude_m") );
SGVec3d vel = SGVec3d( gps_node.getDouble("vn_ms"),
gps_node.getDouble("ve_ms"),
gps_node.getDouble("vd_ms") );
// vel[0] = 0.0; vel[1] = 0.0; vel[2] = 0.0; // test values
set_initial_conditions( pos, vel );
init_pos = true;
}
if ( init_pos ) {
// double imu_time = imu_node.getDouble("timestamp");
SGVec3d gyro = SGVec3d( imu_node.getDouble("p_rad_sec"),
imu_node.getDouble("q_rad_sec"),
imu_node.getDouble("r_rad_sec") );
SGVec3d accel = SGVec3d( imu_node.getDouble("ax_mps_sec"),
imu_node.getDouble("ay_mps_sec"),
imu_node.getDouble("az_mps_sec") );
SGVec3d mag = SGVec3d( imu_node.getDouble("hx"),
imu_node.getDouble("hy"),
imu_node.getDouble("hz") );
// imu_dt = 0.02;
// gyro = SGVec3d(0.0, 0.0, 0.01745); // 0.01745 = 1 deg/sec
// accel = SGVec3d(1.0, 0.0, 0.0); // m/s
propagate_ins( imu_dt, gyro, accel, mag );
double gps_time = gps_node.getDouble("timestamp");
if ( gps_time > last_gps_time ) {
double gps_dt = gps_time - last_gps_time;
last_gps_time = gps_time;
SGGeod gps_pos = SGGeod::fromDegM( gps_node.getDouble("longitude_deg"),
gps_node.getDouble("latitude_deg"),
gps_node.getDouble("altitude_m") );
SGVec3d gps_vel = SGVec3d( gps_node.getDouble("vn_ms"),
gps_node.getDouble("ve_ms"),
gps_node.getDouble("vd_ms") );
update_ins( gps_dt, gps_pos, gps_vel );
}
double phi_deg, theta_deg, psi_deg;
// SGQuatd ned2body_est = ned2body * ned2body_correction;
// ned2body_est.getEulerDeg( psi_deg, theta_deg, phi_deg );
ned2body.getEulerDeg( psi_deg, theta_deg, phi_deg );
/*
printf( "CF: t=%.2f roll=%.2f pitch=%.2f yaw=%.2f vel=%.2f %.2f %.2f\n",
imu_time, phi_deg, theta_deg, psi_deg,
vel_ned[0], vel_ned[1], vel_ned[2] );
printf( " pos=%.12f %.12f %.3f\n",
pos_geod.getLongitudeDeg(), pos_geod.getLatitudeDeg(),
pos_geod.getElevationM() );
*/
// publish values to property tree
filter_node.setDouble( "roll_deg", phi_deg );
filter_node.setDouble( "pitch_deg", theta_deg );
filter_node.setDouble( "heading_deg", psi_deg );
filter_node.setDouble( "latitude_deg", pos_geod.getLatitudeDeg() );
filter_node.setDouble( "longitude_deg", pos_geod.getLongitudeDeg() );
filter_node.setDouble( "altitude_m", pos_geod.getElevationM() );
filter_node.setDouble( "vn_ms", vel_ned[0] );
filter_node.setDouble( "ve_ms", vel_ned[1] );
filter_node.setDouble( "vd_ms", vel_ned[2] );
filter_node.setString( "navigation", "valid" );
filter_node.setDouble( "altitude_ft", pos_geod.getElevationFt() );
filter_node.setDouble( "groundtrack_deg",
90 - atan2(vel_ned[0], vel_ned[1])
* SG_RADIANS_TO_DEGREES );
filter_node.setDouble( "groundspeed_ms",
sqrt( vel_ned[0] * vel_ned[0]
+ vel_ned[1] * vel_ned[1] ) );
filter_node.setDouble( "vertical_speed_fps",
-vel_ned[2] * SG_METER_TO_FEET );
}
return 1;
}
int curt_adns_close() {
return true;
}
| 31.795132 | 80 | 0.670175 | [
"vector",
"transform"
] |
8771f79f5a2cb3cc5d9cbc00b2deee268306f5c9 | 1,618 | cpp | C++ | src/Game/CGameOverScreen.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | 1 | 2016-07-22T17:32:38.000Z | 2016-07-22T17:32:38.000Z | src/Game/CGameOverScreen.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | null | null | null | src/Game/CGameOverScreen.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | null | null | null | // =============================
// SDL Programming
// Name: ODOH KENNETH EMEKA
// Student id: 0902024
// Task 18
// =============================
#include "CGameOverScreen.h"
#include "CSpaceAttacker.h"
////////////////////////////////////////////////////////////////////////////////
CGameOverScreen::CGameOverScreen()
{
m_GameOver.Load("pics/death.png");
m_GameOver.SetAlpha(128);
pfontImg = new CImageAlpha ();
CFont f;
f.Load("fonts/arial.ttf",18);
pfontImg = f.CreateImageFromTextAL("Space Attackers : alpha build, not for distribution!");
}
////////////////////////////////////////////////////////////////////////////////
void CGameOverScreen::OnKeyDown( SDL_KeyboardEvent & event )
{
if ( event.keysym.sym == SDLK_SPACE )
{
dynamic_cast<CSpaceAttacker *>(GetGame())->SetCurrentScene("splash");
}
}
////////////////////////////////////////////////////////////////////////////////
void CGameOverScreen::OnEnter()
{
dynamic_cast<CSpaceAttacker *>(GetGame())->GetSoundServer()->PlayMusic("gameover");
}
////////////////////////////////////////////////////////////////////////////////
void CGameOverScreen::PreRender( CRenderer & r)
{
r.Begin();
r.ClearScreen();
}
////////////////////////////////////////////////////////////////////////////////
void CGameOverScreen::Render( CRenderer & r)
{
r.Render( &m_GameOver, 0,0);
}
////////////////////////////////////////////////////////////////////////////////
void CGameOverScreen::PostRender( CRenderer & r )
{
r.Render( pfontImg, 0, 0);
r.End();
}
////////////////////////////////////////////////////////////////////////////////
| 28.892857 | 93 | 0.425216 | [
"render"
] |
8779b867eaff6aba6018d840a544ffe619c30853 | 288 | hpp | C++ | include/caffe/util/hash.hpp | naibaf7/caffe | 29960153c828820b1abb55a5792283742f57caa2 | [
"Intel",
"BSD-2-Clause"
] | 89 | 2015-04-20T01:25:01.000Z | 2021-12-07T17:03:28.000Z | include/caffe/util/hash.hpp | Miaomz/caffe-opencl | 505693d54298b89cf83b54778479087cff2f3bd6 | [
"Intel",
"BSD-2-Clause"
] | 62 | 2015-06-18T13:11:20.000Z | 2019-02-19T05:00:10.000Z | include/caffe/util/hash.hpp | Miaomz/caffe-opencl | 505693d54298b89cf83b54778479087cff2f3bd6 | [
"Intel",
"BSD-2-Clause"
] | 30 | 2015-07-05T17:08:09.000Z | 2022-02-10T13:16:02.000Z | #ifndef CAFFE_UTIL_HASH_HPP_
#define CAFFE_UTIL_HASH_HPP_
#include "caffe/definitions.hpp"
namespace caffe {
size_t generate_hash(string text);
size_t generate_hash(vector<string> text);
string hash_hex_string(size_t hash);
} // namespace caffe
#endif /* CAFFE_UTIL_HASH_HPP_ */
| 16 | 42 | 0.784722 | [
"vector"
] |
877f9ab4464e9629df11769616796f53eb7e1c48 | 2,296 | cpp | C++ | source/direct3d9/VCache.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/direct3d9/VCache.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/direct3d9/VCache.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* 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 <d3d9.h>
#include <d3dx9.h>
#include "VCache.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D9
{
bool VCache::operator == ( VCache left, VCache right )
{
return VCache::Equals( left, right );
}
bool VCache::operator != ( VCache left, VCache right )
{
return !VCache::Equals( left, right );
}
int VCache::GetHashCode()
{
return Pattern.GetHashCode() + OptMethod.GetHashCode() + CacheSize.GetHashCode()
+ MagicNumber.GetHashCode();
}
bool VCache::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<VCache>( value ) );
}
bool VCache::Equals( VCache value )
{
return ( Pattern == value.Pattern && OptMethod == value.OptMethod && CacheSize == value.CacheSize
&& MagicNumber == value.MagicNumber );
}
bool VCache::Equals( VCache% value1, VCache% value2 )
{
return ( value1.Pattern == value2.Pattern && value1.OptMethod == value2.OptMethod && value1.CacheSize == value2.CacheSize
&& value1.MagicNumber == value2.MagicNumber );
}
}
} | 31.452055 | 124 | 0.699477 | [
"object"
] |
87810ce9ae6a3a8b56ee9a3fecd713c0f00eb25a | 29,285 | cc | C++ | nlp-automl/src/Nlp-automlClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | nlp-automl/src/Nlp-automlClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | nlp-automl/src/Nlp-automlClient.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/nlp-automl/Nlp_automlClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using namespace AlibabaCloud::Nlp_automl;
using namespace AlibabaCloud::Nlp_automl::Model;
namespace
{
const std::string SERVICE_NAME = "nlp-automl";
}
Nlp_automlClient::Nlp_automlClient(const Credentials &credentials, const ClientConfiguration &configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentials, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "nlpautoml");
}
Nlp_automlClient::Nlp_automlClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration)
{
auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "nlpautoml");
}
Nlp_automlClient::Nlp_automlClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) :
RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration)
{
auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration);
endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "nlpautoml");
}
Nlp_automlClient::~Nlp_automlClient()
{}
Nlp_automlClient::AddMTInterveneWordOutcome Nlp_automlClient::addMTInterveneWord(const AddMTInterveneWordRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AddMTInterveneWordOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AddMTInterveneWordOutcome(AddMTInterveneWordResult(outcome.result()));
else
return AddMTInterveneWordOutcome(outcome.error());
}
void Nlp_automlClient::addMTInterveneWordAsync(const AddMTInterveneWordRequest& request, const AddMTInterveneWordAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, addMTInterveneWord(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::AddMTInterveneWordOutcomeCallable Nlp_automlClient::addMTInterveneWordCallable(const AddMTInterveneWordRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AddMTInterveneWordOutcome()>>(
[this, request]()
{
return this->addMTInterveneWord(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::AddMtIntervenePackageOutcome Nlp_automlClient::addMtIntervenePackage(const AddMtIntervenePackageRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return AddMtIntervenePackageOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return AddMtIntervenePackageOutcome(AddMtIntervenePackageResult(outcome.result()));
else
return AddMtIntervenePackageOutcome(outcome.error());
}
void Nlp_automlClient::addMtIntervenePackageAsync(const AddMtIntervenePackageRequest& request, const AddMtIntervenePackageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, addMtIntervenePackage(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::AddMtIntervenePackageOutcomeCallable Nlp_automlClient::addMtIntervenePackageCallable(const AddMtIntervenePackageRequest &request) const
{
auto task = std::make_shared<std::packaged_task<AddMtIntervenePackageOutcome()>>(
[this, request]()
{
return this->addMtIntervenePackage(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::BindIntervenePackageAndModelOutcome Nlp_automlClient::bindIntervenePackageAndModel(const BindIntervenePackageAndModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return BindIntervenePackageAndModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return BindIntervenePackageAndModelOutcome(BindIntervenePackageAndModelResult(outcome.result()));
else
return BindIntervenePackageAndModelOutcome(outcome.error());
}
void Nlp_automlClient::bindIntervenePackageAndModelAsync(const BindIntervenePackageAndModelRequest& request, const BindIntervenePackageAndModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, bindIntervenePackageAndModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::BindIntervenePackageAndModelOutcomeCallable Nlp_automlClient::bindIntervenePackageAndModelCallable(const BindIntervenePackageAndModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<BindIntervenePackageAndModelOutcome()>>(
[this, request]()
{
return this->bindIntervenePackageAndModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::CreateAsyncPredictOutcome Nlp_automlClient::createAsyncPredict(const CreateAsyncPredictRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateAsyncPredictOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateAsyncPredictOutcome(CreateAsyncPredictResult(outcome.result()));
else
return CreateAsyncPredictOutcome(outcome.error());
}
void Nlp_automlClient::createAsyncPredictAsync(const CreateAsyncPredictRequest& request, const CreateAsyncPredictAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createAsyncPredict(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::CreateAsyncPredictOutcomeCallable Nlp_automlClient::createAsyncPredictCallable(const CreateAsyncPredictRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateAsyncPredictOutcome()>>(
[this, request]()
{
return this->createAsyncPredict(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::CreateDatasetOutcome Nlp_automlClient::createDataset(const CreateDatasetRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateDatasetOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateDatasetOutcome(CreateDatasetResult(outcome.result()));
else
return CreateDatasetOutcome(outcome.error());
}
void Nlp_automlClient::createDatasetAsync(const CreateDatasetRequest& request, const CreateDatasetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createDataset(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::CreateDatasetOutcomeCallable Nlp_automlClient::createDatasetCallable(const CreateDatasetRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateDatasetOutcome()>>(
[this, request]()
{
return this->createDataset(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::CreateDatasetRecordOutcome Nlp_automlClient::createDatasetRecord(const CreateDatasetRecordRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateDatasetRecordOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateDatasetRecordOutcome(CreateDatasetRecordResult(outcome.result()));
else
return CreateDatasetRecordOutcome(outcome.error());
}
void Nlp_automlClient::createDatasetRecordAsync(const CreateDatasetRecordRequest& request, const CreateDatasetRecordAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createDatasetRecord(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::CreateDatasetRecordOutcomeCallable Nlp_automlClient::createDatasetRecordCallable(const CreateDatasetRecordRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateDatasetRecordOutcome()>>(
[this, request]()
{
return this->createDatasetRecord(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::CreateModelOutcome Nlp_automlClient::createModel(const CreateModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateModelOutcome(CreateModelResult(outcome.result()));
else
return CreateModelOutcome(outcome.error());
}
void Nlp_automlClient::createModelAsync(const CreateModelRequest& request, const CreateModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::CreateModelOutcomeCallable Nlp_automlClient::createModelCallable(const CreateModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateModelOutcome()>>(
[this, request]()
{
return this->createModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::CreateProjectOutcome Nlp_automlClient::createProject(const CreateProjectRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return CreateProjectOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return CreateProjectOutcome(CreateProjectResult(outcome.result()));
else
return CreateProjectOutcome(outcome.error());
}
void Nlp_automlClient::createProjectAsync(const CreateProjectRequest& request, const CreateProjectAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, createProject(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::CreateProjectOutcomeCallable Nlp_automlClient::createProjectCallable(const CreateProjectRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CreateProjectOutcome()>>(
[this, request]()
{
return this->createProject(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::DeleteModelOutcome Nlp_automlClient::deleteModel(const DeleteModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeleteModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeleteModelOutcome(DeleteModelResult(outcome.result()));
else
return DeleteModelOutcome(outcome.error());
}
void Nlp_automlClient::deleteModelAsync(const DeleteModelRequest& request, const DeleteModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deleteModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::DeleteModelOutcomeCallable Nlp_automlClient::deleteModelCallable(const DeleteModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeleteModelOutcome()>>(
[this, request]()
{
return this->deleteModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::DeployModelOutcome Nlp_automlClient::deployModel(const DeployModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return DeployModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return DeployModelOutcome(DeployModelResult(outcome.result()));
else
return DeployModelOutcome(outcome.error());
}
void Nlp_automlClient::deployModelAsync(const DeployModelRequest& request, const DeployModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, deployModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::DeployModelOutcomeCallable Nlp_automlClient::deployModelCallable(const DeployModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<DeployModelOutcome()>>(
[this, request]()
{
return this->deployModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::GetAsyncPredictOutcome Nlp_automlClient::getAsyncPredict(const GetAsyncPredictRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetAsyncPredictOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetAsyncPredictOutcome(GetAsyncPredictResult(outcome.result()));
else
return GetAsyncPredictOutcome(outcome.error());
}
void Nlp_automlClient::getAsyncPredictAsync(const GetAsyncPredictRequest& request, const GetAsyncPredictAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getAsyncPredict(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::GetAsyncPredictOutcomeCallable Nlp_automlClient::getAsyncPredictCallable(const GetAsyncPredictRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetAsyncPredictOutcome()>>(
[this, request]()
{
return this->getAsyncPredict(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::GetModelOutcome Nlp_automlClient::getModel(const GetModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetModelOutcome(GetModelResult(outcome.result()));
else
return GetModelOutcome(outcome.error());
}
void Nlp_automlClient::getModelAsync(const GetModelRequest& request, const GetModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::GetModelOutcomeCallable Nlp_automlClient::getModelCallable(const GetModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetModelOutcome()>>(
[this, request]()
{
return this->getModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::GetPredictDocOutcome Nlp_automlClient::getPredictDoc(const GetPredictDocRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetPredictDocOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetPredictDocOutcome(GetPredictDocResult(outcome.result()));
else
return GetPredictDocOutcome(outcome.error());
}
void Nlp_automlClient::getPredictDocAsync(const GetPredictDocRequest& request, const GetPredictDocAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getPredictDoc(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::GetPredictDocOutcomeCallable Nlp_automlClient::getPredictDocCallable(const GetPredictDocRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetPredictDocOutcome()>>(
[this, request]()
{
return this->getPredictDoc(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::GetPredictResultOutcome Nlp_automlClient::getPredictResult(const GetPredictResultRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return GetPredictResultOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return GetPredictResultOutcome(GetPredictResultResult(outcome.result()));
else
return GetPredictResultOutcome(outcome.error());
}
void Nlp_automlClient::getPredictResultAsync(const GetPredictResultRequest& request, const GetPredictResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, getPredictResult(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::GetPredictResultOutcomeCallable Nlp_automlClient::getPredictResultCallable(const GetPredictResultRequest &request) const
{
auto task = std::make_shared<std::packaged_task<GetPredictResultOutcome()>>(
[this, request]()
{
return this->getPredictResult(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::InvokeActionOutcome Nlp_automlClient::invokeAction(const InvokeActionRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return InvokeActionOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return InvokeActionOutcome(InvokeActionResult(outcome.result()));
else
return InvokeActionOutcome(outcome.error());
}
void Nlp_automlClient::invokeActionAsync(const InvokeActionRequest& request, const InvokeActionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, invokeAction(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::InvokeActionOutcomeCallable Nlp_automlClient::invokeActionCallable(const InvokeActionRequest &request) const
{
auto task = std::make_shared<std::packaged_task<InvokeActionOutcome()>>(
[this, request]()
{
return this->invokeAction(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::ListDatasetOutcome Nlp_automlClient::listDataset(const ListDatasetRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListDatasetOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListDatasetOutcome(ListDatasetResult(outcome.result()));
else
return ListDatasetOutcome(outcome.error());
}
void Nlp_automlClient::listDatasetAsync(const ListDatasetRequest& request, const ListDatasetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listDataset(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::ListDatasetOutcomeCallable Nlp_automlClient::listDatasetCallable(const ListDatasetRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListDatasetOutcome()>>(
[this, request]()
{
return this->listDataset(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::ListModelsOutcome Nlp_automlClient::listModels(const ListModelsRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return ListModelsOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return ListModelsOutcome(ListModelsResult(outcome.result()));
else
return ListModelsOutcome(outcome.error());
}
void Nlp_automlClient::listModelsAsync(const ListModelsRequest& request, const ListModelsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, listModels(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::ListModelsOutcomeCallable Nlp_automlClient::listModelsCallable(const ListModelsRequest &request) const
{
auto task = std::make_shared<std::packaged_task<ListModelsOutcome()>>(
[this, request]()
{
return this->listModels(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::PredictMTModelOutcome Nlp_automlClient::predictMTModel(const PredictMTModelRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return PredictMTModelOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return PredictMTModelOutcome(PredictMTModelResult(outcome.result()));
else
return PredictMTModelOutcome(outcome.error());
}
void Nlp_automlClient::predictMTModelAsync(const PredictMTModelRequest& request, const PredictMTModelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, predictMTModel(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::PredictMTModelOutcomeCallable Nlp_automlClient::predictMTModelCallable(const PredictMTModelRequest &request) const
{
auto task = std::make_shared<std::packaged_task<PredictMTModelOutcome()>>(
[this, request]()
{
return this->predictMTModel(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::PredictMTModelByDocOutcome Nlp_automlClient::predictMTModelByDoc(const PredictMTModelByDocRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return PredictMTModelByDocOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return PredictMTModelByDocOutcome(PredictMTModelByDocResult(outcome.result()));
else
return PredictMTModelByDocOutcome(outcome.error());
}
void Nlp_automlClient::predictMTModelByDocAsync(const PredictMTModelByDocRequest& request, const PredictMTModelByDocAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, predictMTModelByDoc(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::PredictMTModelByDocOutcomeCallable Nlp_automlClient::predictMTModelByDocCallable(const PredictMTModelByDocRequest &request) const
{
auto task = std::make_shared<std::packaged_task<PredictMTModelByDocOutcome()>>(
[this, request]()
{
return this->predictMTModelByDoc(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::RunContactReviewOutcome Nlp_automlClient::runContactReview(const RunContactReviewRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RunContactReviewOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RunContactReviewOutcome(RunContactReviewResult(outcome.result()));
else
return RunContactReviewOutcome(outcome.error());
}
void Nlp_automlClient::runContactReviewAsync(const RunContactReviewRequest& request, const RunContactReviewAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, runContactReview(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::RunContactReviewOutcomeCallable Nlp_automlClient::runContactReviewCallable(const RunContactReviewRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RunContactReviewOutcome()>>(
[this, request]()
{
return this->runContactReview(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::RunPreTrainServiceOutcome Nlp_automlClient::runPreTrainService(const RunPreTrainServiceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RunPreTrainServiceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RunPreTrainServiceOutcome(RunPreTrainServiceResult(outcome.result()));
else
return RunPreTrainServiceOutcome(outcome.error());
}
void Nlp_automlClient::runPreTrainServiceAsync(const RunPreTrainServiceRequest& request, const RunPreTrainServiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, runPreTrainService(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::RunPreTrainServiceOutcomeCallable Nlp_automlClient::runPreTrainServiceCallable(const RunPreTrainServiceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RunPreTrainServiceOutcome()>>(
[this, request]()
{
return this->runPreTrainService(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
Nlp_automlClient::RunSmartCallServiceOutcome Nlp_automlClient::runSmartCallService(const RunSmartCallServiceRequest &request) const
{
auto endpointOutcome = endpointProvider_->getEndpoint();
if (!endpointOutcome.isSuccess())
return RunSmartCallServiceOutcome(endpointOutcome.error());
auto outcome = makeRequest(endpointOutcome.result(), request);
if (outcome.isSuccess())
return RunSmartCallServiceOutcome(RunSmartCallServiceResult(outcome.result()));
else
return RunSmartCallServiceOutcome(outcome.error());
}
void Nlp_automlClient::runSmartCallServiceAsync(const RunSmartCallServiceRequest& request, const RunSmartCallServiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const
{
auto fn = [this, request, handler, context]()
{
handler(this, request, runSmartCallService(request), context);
};
asyncExecute(new Runnable(fn));
}
Nlp_automlClient::RunSmartCallServiceOutcomeCallable Nlp_automlClient::runSmartCallServiceCallable(const RunSmartCallServiceRequest &request) const
{
auto task = std::make_shared<std::packaged_task<RunSmartCallServiceOutcome()>>(
[this, request]()
{
return this->runSmartCallService(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 34.615839 | 229 | 0.781151 | [
"model"
] |
87816fb62cb918edda0e9f14bf8d498811ac6ecd | 847 | cpp | C++ | clic/src/tier1/cleGreaterConstantKernel.cpp | StRigaud/CLIc_prototype | 83fe15b3f8406c4e5a1f415fcba29dc30b12cad3 | [
"BSD-3-Clause"
] | 1 | 2021-01-04T14:34:45.000Z | 2021-01-04T14:34:45.000Z | clic/src/tier1/cleGreaterConstantKernel.cpp | StRigaud/CLIc_prototype | 83fe15b3f8406c4e5a1f415fcba29dc30b12cad3 | [
"BSD-3-Clause"
] | null | null | null | clic/src/tier1/cleGreaterConstantKernel.cpp | StRigaud/CLIc_prototype | 83fe15b3f8406c4e5a1f415fcba29dc30b12cad3 | [
"BSD-3-Clause"
] | 1 | 2021-01-02T17:27:35.000Z | 2021-01-02T17:27:35.000Z |
#include "cleGreaterConstantKernel.hpp"
namespace cle
{
GreaterConstantKernel::GreaterConstantKernel(std::shared_ptr<GPU> t_gpu) :
Kernel( t_gpu,
"greater_constant",
{"src1", "scalar", "dst"}
)
{
this->m_Sources.insert({this->m_KernelName + "_2d", this->m_OclHeader2d});
this->m_Sources.insert({this->m_KernelName + "_3d", this->m_OclHeader3d});
}
void GreaterConstantKernel::SetInput(Object& t_x)
{
this->AddObject(t_x, "src1");
}
void GreaterConstantKernel::SetOutput(Object& t_x)
{
this->AddObject(t_x, "dst");
}
void GreaterConstantKernel::SetScalar(float t_x)
{
this->AddObject(t_x, "scalar");
}
void GreaterConstantKernel::Execute()
{
this->ManageDimensions("dst");
this->BuildProgramKernel();
this->SetArguments();
this->EnqueueKernel();
}
} // namespace cle
| 20.658537 | 78 | 0.671783 | [
"object"
] |
878877b1226332c9bf6133142d5b7aa4845cb500 | 27,505 | cpp | C++ | src/Cello/test_ItNode.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Cello/test_ItNode.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Cello/test_ItNode.cpp | brittonsmith/enzo-e | 56d8417f2bdfc60f38326ba7208b633bfcea3175 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | // See LICENSE_CELLO file for license and copyright information
/// @file test_ItNode.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2012-01-12
/// @brief Test program for the ItNode class
#include "main.hpp"
#include "test.hpp"
#include "mesh.hpp"
#include "mesh_functions.hpp"
PARALLEL_MAIN_BEGIN
{
PARALLEL_INIT;
unit_init(0,1);
unit_class("ItNode");
//--------------------------------------------------
// Tree (2,2)
//--------------------------------------------------
{
Tree * tree = test_tree_22();
tree_to_png (tree, "test_ItNode.png",512,512);
// Test ItNode depth-first Morton ordering
ItNode it_node(tree);
Node * root = tree->root_node();
for (int count = 0; count < 2; count ++) {
unit_assert (it_node.next_leaf() == root->child(0)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(1)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(1)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(1)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(1)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(2)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(2)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(2)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(2)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(0)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(1)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(1)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(1)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(1)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(0)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(0)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(0)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(0)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(3)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(3)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(3)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == root->child(3)->child(3)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_leaf() == 0);
unit_assert (it_node.done()==true);
}
for (int count = 0; count < 2; count ++) {
unit_assert (it_node.next_node() == root);
printf ("%p\n",it_node.node_trace()->node());
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0));
printf ("%p\n",it_node.node_trace()->node());
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(0));
printf ("%p\n",it_node.node_trace()->node());
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(1)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(1)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(1)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(1)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(2)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(2)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(2)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(2)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(0)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(1)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(1)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(1)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(1)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(0)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(0)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(0)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(0)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(3)->child(0));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(3)->child(1));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(3)->child(2));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == root->child(3)->child(3)->child(3));
unit_assert (it_node.done()==false);
unit_assert (it_node.next_node() == 0);
unit_assert (it_node.done()==true);
}
}
//--------------------------------------------------
// Tree (3,2)
//--------------------------------------------------
{
Tree * tree = test_tree_32();
// Test ItNode depth-first Morton ordering
ItNode it_node(tree);
Node * root = tree->root_node();
for (int count = 0; count < 2; count ++) {
unit_assert (it_node.next_leaf() == root->child(0)->child(0));
unit_assert (it_node.next_leaf() == root->child(0)->child(1));
unit_assert (it_node.next_leaf() == root->child(0)->child(2));
unit_assert (it_node.next_leaf() == root->child(0)->child(3));
unit_assert (it_node.next_leaf() == root->child(0)->child(4));
unit_assert (it_node.next_leaf() == root->child(0)->child(5));
unit_assert (it_node.next_leaf() == root->child(0)->child(6));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(0));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(1));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(2));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(3));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(4));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(5));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(6));
unit_assert (it_node.next_leaf() == root->child(0)->child(7)->child(7));
unit_assert (it_node.next_leaf() == root->child(1)->child(0));
unit_assert (it_node.next_leaf() == root->child(1)->child(1));
unit_assert (it_node.next_leaf() == root->child(1)->child(2));
unit_assert (it_node.next_leaf() == root->child(1)->child(3));
unit_assert (it_node.next_leaf() == root->child(1)->child(4));
unit_assert (it_node.next_leaf() == root->child(1)->child(5));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(0));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(1));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(2));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(3));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(4));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(5));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(6));
unit_assert (it_node.next_leaf() == root->child(1)->child(6)->child(7));
unit_assert (it_node.next_leaf() == root->child(1)->child(7));
unit_assert (it_node.next_leaf() == root->child(2)->child(0));
unit_assert (it_node.next_leaf() == root->child(2)->child(1));
unit_assert (it_node.next_leaf() == root->child(2)->child(2));
unit_assert (it_node.next_leaf() == root->child(2)->child(3));
unit_assert (it_node.next_leaf() == root->child(2)->child(4));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(0));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(1));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(2));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(3));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(4));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(5));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(6));
unit_assert (it_node.next_leaf() == root->child(2)->child(5)->child(7));
unit_assert (it_node.next_leaf() == root->child(2)->child(6));
unit_assert (it_node.next_leaf() == root->child(2)->child(7));
unit_assert (it_node.next_leaf() == root->child(3)->child(0));
unit_assert (it_node.next_leaf() == root->child(3)->child(1));
unit_assert (it_node.next_leaf() == root->child(3)->child(2));
unit_assert (it_node.next_leaf() == root->child(3)->child(3));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(0));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(1));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(2));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(3));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(4));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(5));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(6));
unit_assert (it_node.next_leaf() == root->child(3)->child(4)->child(7));
unit_assert (it_node.next_leaf() == root->child(3)->child(5));
unit_assert (it_node.next_leaf() == root->child(3)->child(6));
unit_assert (it_node.next_leaf() == root->child(3)->child(7));
unit_assert (it_node.next_leaf() == root->child(4)->child(0));
unit_assert (it_node.next_leaf() == root->child(4)->child(1));
unit_assert (it_node.next_leaf() == root->child(4)->child(2));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(0));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(1));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(2));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(3));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(4));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(5));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(6));
unit_assert (it_node.next_leaf() == root->child(4)->child(3)->child(7));
unit_assert (it_node.next_leaf() == root->child(4)->child(4));
unit_assert (it_node.next_leaf() == root->child(4)->child(5));
unit_assert (it_node.next_leaf() == root->child(4)->child(6));
unit_assert (it_node.next_leaf() == root->child(4)->child(7));
unit_assert (it_node.next_leaf() == root->child(5)->child(0));
unit_assert (it_node.next_leaf() == root->child(5)->child(1));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(0));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(1));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(2));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(3));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(4));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(5));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(6));
unit_assert (it_node.next_leaf() == root->child(5)->child(2)->child(7));
unit_assert (it_node.next_leaf() == root->child(5)->child(3));
unit_assert (it_node.next_leaf() == root->child(5)->child(4));
unit_assert (it_node.next_leaf() == root->child(5)->child(5));
unit_assert (it_node.next_leaf() == root->child(5)->child(6));
unit_assert (it_node.next_leaf() == root->child(5)->child(7));
unit_assert (it_node.next_leaf() == root->child(6)->child(0));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(0));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(1));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(2));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(3));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(4));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(5));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(6));
unit_assert (it_node.next_leaf() == root->child(6)->child(1)->child(7));
unit_assert (it_node.next_leaf() == root->child(6)->child(2));
unit_assert (it_node.next_leaf() == root->child(6)->child(3));
unit_assert (it_node.next_leaf() == root->child(6)->child(4));
unit_assert (it_node.next_leaf() == root->child(6)->child(5));
unit_assert (it_node.next_leaf() == root->child(6)->child(6));
unit_assert (it_node.next_leaf() == root->child(6)->child(7));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(0));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(1));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(2));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(3));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(4));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(5));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(6));
unit_assert (it_node.next_leaf() == root->child(7)->child(0)->child(7));
unit_assert (it_node.next_leaf() == root->child(7)->child(1));
unit_assert (it_node.next_leaf() == root->child(7)->child(2));
unit_assert (it_node.next_leaf() == root->child(7)->child(3));
unit_assert (it_node.next_leaf() == root->child(7)->child(4));
unit_assert (it_node.next_leaf() == root->child(7)->child(5));
unit_assert (it_node.next_leaf() == root->child(7)->child(6));
unit_assert (it_node.next_leaf() == root->child(7)->child(7));
unit_assert (it_node.next_leaf() == 0);
unit_assert (it_node.done()==true);
}
for (int count = 0; count < 2; count ++) {
unit_assert (it_node.next_node() == root);
unit_assert (it_node.next_node() == root->child(0));
unit_assert (it_node.next_node() == root->child(0)->child(0));
unit_assert (it_node.next_node() == root->child(0)->child(1));
unit_assert (it_node.next_node() == root->child(0)->child(2));
unit_assert (it_node.next_node() == root->child(0)->child(3));
unit_assert (it_node.next_node() == root->child(0)->child(4));
unit_assert (it_node.next_node() == root->child(0)->child(5));
unit_assert (it_node.next_node() == root->child(0)->child(6));
unit_assert (it_node.next_node() == root->child(0)->child(7));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(0));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(1));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(2));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(3));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(4));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(5));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(6));
unit_assert (it_node.next_node() == root->child(0)->child(7)->child(7));
unit_assert (it_node.next_node() == root->child(1));
unit_assert (it_node.next_node() == root->child(1)->child(0));
unit_assert (it_node.next_node() == root->child(1)->child(1));
unit_assert (it_node.next_node() == root->child(1)->child(2));
unit_assert (it_node.next_node() == root->child(1)->child(3));
unit_assert (it_node.next_node() == root->child(1)->child(4));
unit_assert (it_node.next_node() == root->child(1)->child(5));
unit_assert (it_node.next_node() == root->child(1)->child(6));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(0));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(1));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(2));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(3));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(4));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(5));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(6));
unit_assert (it_node.next_node() == root->child(1)->child(6)->child(7));
unit_assert (it_node.next_node() == root->child(1)->child(7));
unit_assert (it_node.next_node() == root->child(2));
unit_assert (it_node.next_node() == root->child(2)->child(0));
unit_assert (it_node.next_node() == root->child(2)->child(1));
unit_assert (it_node.next_node() == root->child(2)->child(2));
unit_assert (it_node.next_node() == root->child(2)->child(3));
unit_assert (it_node.next_node() == root->child(2)->child(4));
unit_assert (it_node.next_node() == root->child(2)->child(5));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(0));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(1));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(2));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(3));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(4));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(5));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(6));
unit_assert (it_node.next_node() == root->child(2)->child(5)->child(7));
unit_assert (it_node.next_node() == root->child(2)->child(6));
unit_assert (it_node.next_node() == root->child(2)->child(7));
unit_assert (it_node.next_node() == root->child(3));
unit_assert (it_node.next_node() == root->child(3)->child(0));
unit_assert (it_node.next_node() == root->child(3)->child(1));
unit_assert (it_node.next_node() == root->child(3)->child(2));
unit_assert (it_node.next_node() == root->child(3)->child(3));
unit_assert (it_node.next_node() == root->child(3)->child(4));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(0));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(1));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(2));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(3));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(4));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(5));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(6));
unit_assert (it_node.next_node() == root->child(3)->child(4)->child(7));
unit_assert (it_node.next_node() == root->child(3)->child(5));
unit_assert (it_node.next_node() == root->child(3)->child(6));
unit_assert (it_node.next_node() == root->child(3)->child(7));
unit_assert (it_node.next_node() == root->child(4));
unit_assert (it_node.next_node() == root->child(4)->child(0));
unit_assert (it_node.next_node() == root->child(4)->child(1));
unit_assert (it_node.next_node() == root->child(4)->child(2));
unit_assert (it_node.next_node() == root->child(4)->child(3));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(0));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(1));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(2));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(3));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(4));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(5));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(6));
unit_assert (it_node.next_node() == root->child(4)->child(3)->child(7));
unit_assert (it_node.next_node() == root->child(4)->child(4));
unit_assert (it_node.next_node() == root->child(4)->child(5));
unit_assert (it_node.next_node() == root->child(4)->child(6));
unit_assert (it_node.next_node() == root->child(4)->child(7));
unit_assert (it_node.next_node() == root->child(5));
unit_assert (it_node.next_node() == root->child(5)->child(0));
unit_assert (it_node.next_node() == root->child(5)->child(1));
unit_assert (it_node.next_node() == root->child(5)->child(2));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(0));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(1));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(2));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(3));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(4));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(5));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(6));
unit_assert (it_node.next_node() == root->child(5)->child(2)->child(7));
unit_assert (it_node.next_node() == root->child(5)->child(3));
unit_assert (it_node.next_node() == root->child(5)->child(4));
unit_assert (it_node.next_node() == root->child(5)->child(5));
unit_assert (it_node.next_node() == root->child(5)->child(6));
unit_assert (it_node.next_node() == root->child(5)->child(7));
unit_assert (it_node.next_node() == root->child(6));
unit_assert (it_node.next_node() == root->child(6)->child(0));
unit_assert (it_node.next_node() == root->child(6)->child(1));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(0));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(1));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(2));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(3));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(4));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(5));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(6));
unit_assert (it_node.next_node() == root->child(6)->child(1)->child(7));
unit_assert (it_node.next_node() == root->child(6)->child(2));
unit_assert (it_node.next_node() == root->child(6)->child(3));
unit_assert (it_node.next_node() == root->child(6)->child(4));
unit_assert (it_node.next_node() == root->child(6)->child(5));
unit_assert (it_node.next_node() == root->child(6)->child(6));
unit_assert (it_node.next_node() == root->child(6)->child(7));
unit_assert (it_node.next_node() == root->child(7));
unit_assert (it_node.next_node() == root->child(7)->child(0));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(0));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(1));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(2));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(3));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(4));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(5));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(6));
unit_assert (it_node.next_node() == root->child(7)->child(0)->child(7));
unit_assert (it_node.next_node() == root->child(7)->child(1));
unit_assert (it_node.next_node() == root->child(7)->child(2));
unit_assert (it_node.next_node() == root->child(7)->child(3));
unit_assert (it_node.next_node() == root->child(7)->child(4));
unit_assert (it_node.next_node() == root->child(7)->child(5));
unit_assert (it_node.next_node() == root->child(7)->child(6));
unit_assert (it_node.next_node() == root->child(7)->child(7));
unit_assert (it_node.next_node() == 0);
unit_assert (it_node.done()==true);
}
}
//--------------------------------------------------
unit_finalize();
exit_();
}
PARALLEL_MAIN_END
| 60.054585 | 78 | 0.614616 | [
"mesh"
] |
87923335a9ec2d5dea1c6078754795022196bf32 | 5,291 | cpp | C++ | cpp/client/com.spoonacular.client.model/OAIInline_response_200_52.cpp | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | 21 | 2019-08-09T18:53:26.000Z | 2022-03-14T22:10:10.000Z | cpp/client/com.spoonacular.client.model/OAIInline_response_200_52.cpp | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | null | null | null | cpp/client/com.spoonacular.client.model/OAIInline_response_200_52.cpp | ddsky/spoonacular-api-clients | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | [
"MIT"
] | 55 | 2019-08-13T17:52:47.000Z | 2022-03-27T04:29:34.000Z | /**
* spoonacular API
* The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal.
*
* The version of the OpenAPI document: 1.0
* Contact: mail@spoonacular.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIInline_response_200_52.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAIInline_response_200_52::OAIInline_response_200_52(QString json) {
this->init();
this->fromJson(json);
}
OAIInline_response_200_52::OAIInline_response_200_52() {
this->init();
}
OAIInline_response_200_52::~OAIInline_response_200_52() {
}
void
OAIInline_response_200_52::init() {
m_articles_isSet = false;
m_articles_isValid = false;
m_grocery_products_isSet = false;
m_grocery_products_isValid = false;
m_menu_items_isSet = false;
m_menu_items_isValid = false;
m_recipes_isSet = false;
m_recipes_isValid = false;
}
void
OAIInline_response_200_52::fromJson(QString jsonString) {
QByteArray array (jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void
OAIInline_response_200_52::fromJsonObject(QJsonObject json) {
m_articles_isValid = ::OpenAPI::fromJsonValue(articles, json[QString("Articles")]);
m_grocery_products_isValid = ::OpenAPI::fromJsonValue(grocery_products, json[QString("Grocery Products")]);
m_menu_items_isValid = ::OpenAPI::fromJsonValue(menu_items, json[QString("Menu Items")]);
m_recipes_isValid = ::OpenAPI::fromJsonValue(recipes, json[QString("Recipes")]);
}
QString
OAIInline_response_200_52::asJson () const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAIInline_response_200_52::asJsonObject() const {
QJsonObject obj;
if(articles.size() > 0){
obj.insert(QString("Articles"), ::OpenAPI::toJsonValue(articles));
}
if(grocery_products.size() > 0){
obj.insert(QString("Grocery Products"), ::OpenAPI::toJsonValue(grocery_products));
}
if(menu_items.size() > 0){
obj.insert(QString("Menu Items"), ::OpenAPI::toJsonValue(menu_items));
}
if(recipes.size() > 0){
obj.insert(QString("Recipes"), ::OpenAPI::toJsonValue(recipes));
}
return obj;
}
QList<OAIObject>
OAIInline_response_200_52::getArticles() const {
return articles;
}
void
OAIInline_response_200_52::setArticles(const QList<OAIObject> &articles) {
this->articles = articles;
this->m_articles_isSet = true;
}
QList<OAIObject>
OAIInline_response_200_52::getGroceryProducts() const {
return grocery_products;
}
void
OAIInline_response_200_52::setGroceryProducts(const QList<OAIObject> &grocery_products) {
this->grocery_products = grocery_products;
this->m_grocery_products_isSet = true;
}
QList<OAIObject>
OAIInline_response_200_52::getMenuItems() const {
return menu_items;
}
void
OAIInline_response_200_52::setMenuItems(const QList<OAIObject> &menu_items) {
this->menu_items = menu_items;
this->m_menu_items_isSet = true;
}
QList<OAIObject>
OAIInline_response_200_52::getRecipes() const {
return recipes;
}
void
OAIInline_response_200_52::setRecipes(const QList<OAIObject> &recipes) {
this->recipes = recipes;
this->m_recipes_isSet = true;
}
bool
OAIInline_response_200_52::isSet() const {
bool isObjectUpdated = false;
do{
if(articles.size() > 0){ isObjectUpdated = true; break;}
if(grocery_products.size() > 0){ isObjectUpdated = true; break;}
if(menu_items.size() > 0){ isObjectUpdated = true; break;}
if(recipes.size() > 0){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
bool
OAIInline_response_200_52::isValid() const {
// only required properties are required for the object to be considered valid
return m_articles_isValid && m_grocery_products_isValid && m_menu_items_isValid && m_recipes_isValid && true;
}
}
| 30.0625 | 1,035 | 0.727273 | [
"object"
] |
87a204de4f59d5ae9e3f98ac6a954b8035d37c8f | 5,320 | cpp | C++ | OOInteraction/src/expression_editor/OOExpressionBuilder.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | OOInteraction/src/expression_editor/OOExpressionBuilder.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | OOInteraction/src/expression_editor/OOExpressionBuilder.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "expression_editor/OOExpressionBuilder.h"
#include "expression_editor/OOOperatorDescriptorList.h"
#include "expression_editor/OOOperatorDescriptor.h"
#include "OOInteractionException.h"
#include "OOModel/src/allOOModelNodes.h"
#include "InteractionBase/src/expression_editor/Value.h"
#include "InteractionBase/src/expression_editor/Operator.h"
#include "InteractionBase/src/expression_editor/UnfinishedOperator.h"
#include "InteractionBase/src/expression_editor/OperatorDescriptor.h"
#include "InteractionBase/src/expression_editor/ErrorDescriptor.h"
#include "InteractionBase/src/expression_editor/ExpressionEditor.h"
namespace OOInteraction {
OOModel::Expression* OOExpressionBuilder::getOOExpression(const QString& exprText)
{
static Interaction::ExpressionEditor editor;
editor.setOperatorDescriptors(OOOperatorDescriptorList::instance());
OOExpressionBuilder builder;
return builder.getOOExpression( editor.parse(exprText) );
}
OOModel::Expression* OOExpressionBuilder::getOOExpression(Interaction::Expression* expression)
{
expression->accept(this);
OOModel::Expression* e = this->expression;
this->expression = nullptr;
return e;
}
void OOExpressionBuilder::visit(Interaction::Empty*)
{
expression = new OOModel::EmptyExpression();
}
void OOExpressionBuilder::visit(Interaction::Value* val)
{
if (val->text().isEmpty()) throw OOInteractionException("Trying to create an expression from an empty Value");
bool isInt = false;
int value = val->text().toInt(&isInt);
if (isInt)
expression = new OOModel::IntegerLiteral(value);
else if (val->text().startsWith('"'))
expression = new OOModel::StringLiteral(val->text().mid(1, val->text().size()-2));
else
expression = new OOModel::ReferenceExpression(val->text());
}
void OOExpressionBuilder::visit(Interaction::Operator* op)
{
if (dynamic_cast<Interaction::ErrorDescriptor*>(op->descriptor()))
createErrorExpression(op);
else
{
QList<OOModel::Expression*> operands;
for(auto e : op->operands())
{
e->accept(this);
operands.append(expression);
}
OOOperatorDescriptor* desc = static_cast<OOOperatorDescriptor*>(op->descriptor());
expression = desc->create(operands);
}
}
void OOExpressionBuilder::visit(Interaction::UnfinishedOperator* unfinished)
{
if (dynamic_cast<Interaction::ErrorDescriptor*>(unfinished->descriptor()))
createErrorExpression(unfinished);
else
{
QString lastDelimiter;
OOModel::UnfinishedOperator* unf = new OOModel::UnfinishedOperator();
int operand_index = 0;
for(int i = 0; i <unfinished->numComplete(); ++i)
{
QString current = unfinished->descriptor()->signature().at(i);
if (!Interaction::OperatorDescriptor::isDelimiter(current))
{
unf->delimiters()->append(new Model::Text(lastDelimiter));
lastDelimiter.clear();
unfinished->at(operand_index)->accept(this);
++operand_index;
unf->operands()->append(expression);
}
else
lastDelimiter += current;
}
unf->delimiters()->append(new Model::Text(lastDelimiter)); // append the postfix, even if empty
expression = unf;
}
}
void OOExpressionBuilder::createErrorExpression(Interaction::Operator* op)
{
OOModel::ErrorExpression* error = new OOModel::ErrorExpression();
auto desc = dynamic_cast<Interaction::ErrorDescriptor*>(op->descriptor());
error->setPrefix(desc->errorPrefix());
error->setPostfix(desc->errorPostfix());
op->at(0)->accept(this);
error->setArg(expression);
expression = error;
}
} /* namespace InteractionBase */
| 38.273381 | 120 | 0.721429 | [
"model"
] |
87af7bc5328aa2bec2ed77c50a3f71c2ca1257dc | 11,673 | cpp | C++ | src/json_parser.cpp | SausageTaste/DalbaragiTools | d07e82ecdb9117cffa886e50b89808e2dbf245c6 | [
"MIT"
] | null | null | null | src/json_parser.cpp | SausageTaste/DalbaragiTools | d07e82ecdb9117cffa886e50b89808e2dbf245c6 | [
"MIT"
] | null | null | null | src/json_parser.cpp | SausageTaste/DalbaragiTools | d07e82ecdb9117cffa886e50b89808e2dbf245c6 | [
"MIT"
] | null | null | null | #include "daltools/model_parser.h"
#include <optional>
#include <nlohmann/json.hpp>
#include <libbase64.h>
#include "daltools/byte_tool.h"
#include "daltools/konst.h"
#include "daltools/compression.h"
namespace {
namespace dalp = dal::parser;
using json_t = nlohmann::json;
using scene_t = dal::parser::SceneIntermediate;
std::vector<uint8_t> decode_base64(const std::string& base64_data) {
std::vector<uint8_t> output(base64_data.size());
size_t output_size = output.size();
const auto result = base64_decode(
base64_data.c_str(),
base64_data.size(),
reinterpret_cast<char*>(output.data()),
&output_size,
0
);
if (1 != result) {
output.clear();
}
else {
output.resize(output_size);
}
return output;
}
class BinaryData {
std::vector<uint8_t> m_data;
public:
auto ptr_at(const size_t index) const {
return this->m_data.data() + index;
}
bool parse_from_json(const json_t& json_data) {
const size_t raw_size = json_data["raw size"];
auto base64_decoded = ::decode_base64(json_data["base64"]);
if (base64_decoded.empty()) {
return false;
}
if (json_data.contains("compressed size")) {
this->m_data.resize(raw_size);
const auto result = dal::decompress_zip(this->m_data.data(), this->m_data.size(), base64_decoded.data(), base64_decoded.size());
if (dal::CompressResult::success != result.m_result) {
return false;
}
assert(result.m_output_size == this->m_data.size());
}
else {
this->m_data = std::move(base64_decoded);
}
return true;
}
};
void parse_vec3(const json_t& json_data, glm::vec3& output) {
output[0] = json_data[0];
output[1] = json_data[1];
output[2] = json_data[2];
}
void parse_quat(const json_t& json_data, glm::quat& output) {
output.w = json_data[0];
output.x = json_data[1];
output.y = json_data[2];
output.z = json_data[3];
}
void parse_mat4(const json_t& json_data, glm::mat4& output) {
const auto mat_ptr = &output[0][0];
for (int i = 0; i < 16; ++i) {
mat_ptr[i] = json_data[i];
}
}
glm::mat4 parse_mat4(const json_t& json_data) {
glm::mat4 output;
::parse_mat4(json_data, output);
return output;
}
void parse_transform(const json_t& json_data, scene_t::Transform& output) {
::parse_vec3(json_data["translation"], output.m_pos);
::parse_quat(json_data["rotation"], output.m_quat);
::parse_vec3(json_data["scale"], output.m_scale);
}
template <typename T>
void parse_list(const json_t& json_data, std::vector<T>& output) {
for (auto& x : json_data) {
output.push_back(x);
}
}
void parse_actor(const json_t& json_data, scene_t::IActor& actor) {
actor.m_name = json_data["name"];
actor.m_parent_name = json_data["parent name"];
::parse_list(json_data["collections"], actor.m_collections);
::parse_transform(json_data["transform"], actor.m_transform);
actor.m_hidden = json_data["hidden"];
}
void parse_mesh(const json_t& json_data, scene_t::Mesh& output, const ::BinaryData& binary_data) {
output.m_name = json_data["name"];
output.m_skeleton_name = json_data["skeleton name"];
size_t vertex_count = json_data["vertex count"];
output.m_vertices.resize(vertex_count);
assert(!dal::parser::is_big_endian());
static_assert(sizeof(float) * 2 == sizeof(glm::vec2));
static_assert(sizeof(float) * 3 == sizeof(glm::vec3));
{
const size_t bin_pos = json_data["vertices binary data"]["position"];
const size_t bin_size = json_data["vertices binary data"]["size"];
for (size_t i = 0; i < vertex_count; ++i) {
const auto ptr = binary_data.ptr_at(bin_pos + i * sizeof(glm::vec3));
output.m_vertices[i].m_pos = *reinterpret_cast<const glm::vec3*>(ptr);
}
}
{
const size_t bin_pos = json_data["uv coordinates binary data"]["position"];
const size_t bin_size = json_data["uv coordinates binary data"]["size"];
for (size_t i = 0; i < vertex_count; ++i) {
const auto ptr = binary_data.ptr_at(bin_pos + i * sizeof(glm::vec2));
output.m_vertices[i].uv_coord = *reinterpret_cast<const glm::vec2*>(ptr);
}
}
{
const size_t bin_pos = json_data["normals binary data"]["position"];
const size_t bin_size = json_data["normals binary data"]["size"];
for (size_t i = 0; i < vertex_count; ++i) {
const auto ptr = binary_data.ptr_at(bin_pos + i * sizeof(glm::vec3));
output.m_vertices[i].m_normal = glm::normalize(*reinterpret_cast<const glm::vec3*>(ptr));
}
}
{
const size_t bin_pos = json_data["joints binary data"]["position"];
const size_t bin_size = json_data["joints binary data"]["size"];
auto ptr = binary_data.ptr_at(bin_pos);
for (size_t i = 0; i < vertex_count; ++i) {
auto& vertex = output.m_vertices[i];
const auto joint_count = dalp::make_int32(ptr); ptr += 4;
for (size_t j = 0; j < joint_count; ++j) {
auto& joint = vertex.m_joints.emplace_back();
joint.m_index = dalp::make_int32(ptr); ptr += 4;
joint.m_weight = dalp::make_float32(ptr); ptr += 4;
}
}
assert(ptr == binary_data.ptr_at(bin_pos + bin_size));
}
{
output.m_indices.resize(output.m_vertices.size());
for (size_t i = 0; i < output.m_vertices.size(); ++i) {
output.m_indices[i] = i;
}
}
}
void parse_material(const json_t& json_mesh, scene_t::Material& output_material) {
output_material.m_name = json_mesh["name"];
output_material.m_roughness = json_mesh["roughness"];
output_material.m_metallic = json_mesh["metallic"];
output_material.m_transparency = json_mesh["transparency"];
output_material.m_albedo_map = json_mesh["albedo map"];
output_material.m_roughness_map = json_mesh["roughness map"];
output_material.m_metallic_map = json_mesh["metallic map"];
output_material.m_normal_map = json_mesh["normal map"];
}
void parse_skeleton_joint(const json_t& json_data, scene_t::SkelJoint& output) {
output.m_name = json_data["name"];
output.m_parent_name = json_data["parent name"];
output.m_joint_type = static_cast<dalp::JointType>(static_cast<int>(json_data["joint type"]));
::parse_mat4(json_data["offset matrix"], output.m_offset_mat);
}
void parse_skeleton(const json_t& json_data, scene_t::Skeleton& output) {
output.m_name = json_data["name"];
::parse_transform(json_data["transform"], output.m_root_transform);
for (auto& x : json_data["joints"]) {
::parse_skeleton_joint(x, output.m_joints.emplace_back());
}
}
void parse_anim_joint(const json_t& json_data, scene_t::AnimJoint& output) {
output.m_name = json_data["name"];
for (auto& x : json_data["positions"]) {
const auto& value = x["value"];
output.add_position(x["time point"], value[0], value[1], value[2]);
}
for (auto& x : json_data["rotations"]) {
const auto& value = x["value"];
output.add_rotation(x["time point"], value[0], value[1], value[2], value[3]);
}
for (auto& x : json_data["scales"]) {
const auto& value = x["value"];
output.add_scale(x["time point"], value);
}
}
void parse_animation(const json_t& json_data, scene_t::Animation& output) {
output.m_name = json_data["name"];
output.m_ticks_per_sec = json_data["ticks per seconds"];
for (auto& x : json_data["joints"]) {
::parse_anim_joint(x, output.m_joints.emplace_back());
}
}
void parse_mesh_actor(const json_t& json_data, scene_t::MeshActor& output) {
::parse_actor(json_data, output);
for (auto& x : json_data["render pairs"]) {
auto& pair = output.m_render_pairs.emplace_back();
pair.m_mesh_name = x["mesh name"];
pair.m_material_name = x["material name"];
}
}
void parse_ilight(const json_t& json_data, scene_t::ILight& output) {
::parse_vec3(json_data["color"], output.m_color);
output.m_intensity = json_data["intensity"];
output.m_has_shadow = json_data["has shadow"];
}
void parse_dlight(const json_t& json_data, scene_t::DirectionalLight& output) {
::parse_actor(json_data, output);
::parse_ilight(json_data, output);
}
void parse_plight(const json_t& json_data, scene_t::PointLight& output) {
output.m_max_distance = json_data["max distance"];
output.m_half_intense_distance = json_data["half intense distance"];
::parse_actor(json_data, output);
::parse_ilight(json_data, output);
}
void parse_slight(const json_t& json_data, scene_t::Spotlight& output) {
::parse_plight(json_data, output);
output.m_spot_degree = json_data["spot degree"];
output.m_spot_blend = json_data["spot blend"];
}
void parse_scene(const json_t& json_data, scene_t& scene, const ::BinaryData& binary_data) {
scene.m_name = json_data["name"];
scene.m_root_transform = ::parse_mat4(json_data["root transform"]);
for (auto& x : json_data["meshes"]) {
::parse_mesh(x, scene.m_meshes.emplace_back(), binary_data);
}
for (auto& x : json_data["materials"]) {
::parse_material(x, scene.m_materials.emplace_back());
}
for (auto& x : json_data["skeletons"]) {
::parse_skeleton(x, scene.m_skeletons.emplace_back());
}
for (auto& x : json_data["animations"]) {
::parse_animation(x, scene.m_animations.emplace_back());
}
for (auto& x : json_data["mesh actors"]) {
::parse_mesh_actor(x, scene.m_mesh_actors.emplace_back());
}
for (auto& x : json_data["directional lights"]) {
::parse_dlight(x, scene.m_dlights.emplace_back());
}
for (auto& x : json_data["point lights"]) {
::parse_plight(x, scene.m_plights.emplace_back());
}
for (auto& x : json_data["spotlights"]) {
::parse_slight(x, scene.m_slights.emplace_back());
}
}
}
namespace dal::parser {
JsonParseResult parse_json(std::vector<SceneIntermediate>& scenes, const uint8_t* const file_content, const size_t content_size) {
const auto json_data = nlohmann::json::parse(file_content, file_content + content_size);
::BinaryData binary_data;
binary_data.parse_from_json(json_data["binary data"]);
for (auto& x : json_data["scenes"]) {
::parse_scene(x, scenes.emplace_back(), binary_data);
}
return JsonParseResult::success;
}
}
| 34.231672 | 144 | 0.588281 | [
"mesh",
"render",
"vector",
"transform"
] |
87c12be8496712dd3524f240be763845f6a5fc27 | 6,930 | cpp | C++ | src/liblightmetrica/property.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | 150 | 2015-12-28T10:26:02.000Z | 2021-03-17T14:36:16.000Z | src/liblightmetrica/property.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | null | null | null | src/liblightmetrica/property.cpp | jammm/lightmetrica-v2 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | [
"MIT"
] | 17 | 2016-02-08T10:57:55.000Z | 2020-09-04T03:57:33.000Z | /*
Lightmetrica - A modern, research-oriented renderer
Copyright (c) 2015 Hisanari Otsu
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 <pch.h>
#include <lightmetrica/property.h>
#include <lightmetrica/logger.h>
#include <yaml-cpp/yaml.h>
LM_NAMESPACE_BEGIN
class PropertyTree_;
class PropertyNode_ final : public PropertyNode
{
friend class PropertyTree_;
public:
LM_IMPL_CLASS(PropertyNode_, PropertyNode);
public:
LM_IMPL_F(Tree) = [this]() -> const PropertyTree* { return tree_; };
LM_IMPL_F(Type) = [this]() -> PropertyNodeType { return type_; };
LM_IMPL_F(Line) = [this]() -> int { return line_; };
//LM_IMPL_F(Scalar) = [this]() -> std::string { return scalar_; };
LM_IMPL_F(RawScalar) = [this]() -> const char* { return scalar_.c_str(); };
LM_IMPL_F(Key) = [this]() -> std::string { return key_; };
LM_IMPL_F(Size) = [this]() -> int { return (int)(sequence_.size()); };
LM_IMPL_F(Child) = [this](const std::string& key) -> const PropertyNode* { const auto it = map_.find(key); return it != map_.end() ? it->second : nullptr; };
LM_IMPL_F(At) = [this](int index) -> const PropertyNode* { return sequence_.at(index); };
LM_IMPL_F(Parent) = [this]() -> const PropertyNode* { return parent_; };
private:
// Pointer to property tree
const PropertyTree* tree_;
// Type of the node
PropertyNodeType type_;
// Line
int line_;
// For map node type
std::string key_;
std::unordered_map<std::string, const PropertyNode_*> map_;
// For sequence node type
std::vector<const PropertyNode_*> sequence_;
// For scalar type
std::string scalar_;
// Parent node (nullptr for root node)
const PropertyNode_* parent_ = nullptr;
};
LM_COMPONENT_REGISTER_IMPL_DEFAULT(PropertyNode_);
// --------------------------------------------------------------------------------
class PropertyTree_ final : public PropertyTree
{
public:
LM_IMPL_CLASS(PropertyTree_, PropertyTree);
public:
LM_IMPL_F(LoadFromFile) = [this](const std::string& path) -> bool
{
std::ifstream t(path);
if (!t.is_open())
{
LM_LOG_ERROR("Failed to open: " + path);
return false;
}
std::stringstream ss;
ss << t.rdbuf();
if (!LoadFromString(ss.str()))
{
return false;
}
path_ = path;
return true;
};
LM_IMPL_F(LoadFromString) = [this](const std::string& input) -> bool
{
#pragma region Traverse YAML nodes and convert to the our node type
const std::function<PropertyNode_*(const YAML::Node&)> Traverse = [&](const YAML::Node& yamlNode) -> PropertyNode_*
{
// Create our node
nodes_.push_back(ComponentFactory::Create<PropertyNode>());
auto* node_internal = static_cast<PropertyNode_*>(nodes_.back().get());
node_internal->line_ = yamlNode.Mark().line;
node_internal->tree_ = this;
switch (yamlNode.Type())
{
case YAML::NodeType::Null:
{
node_internal->type_ = PropertyNodeType::Null;
break;
}
case YAML::NodeType::Scalar:
{
node_internal->type_ = PropertyNodeType::Scalar;
node_internal->scalar_ = yamlNode.Scalar();
break;
}
case YAML::NodeType::Sequence:
{
node_internal->type_ = PropertyNodeType::Sequence;
for (size_t i = 0; i < yamlNode.size(); i++)
{
node_internal->sequence_.push_back(Traverse(yamlNode[i]));
}
break;
}
case YAML::NodeType::Map:
{
node_internal->type_ = PropertyNodeType::Map;
for (const auto& p : yamlNode)
{
const auto key = p.first.as<std::string>();
auto* childNode = Traverse(p.second);
childNode->key_ = key;
childNode->parent_ = node_internal;
node_internal->map_[key] = childNode;
}
break;
}
case YAML::NodeType::Undefined:
{
LM_UNREACHABLE();
break;
}
}
return node_internal;
};
try
{
input_ = input;
const auto root = YAML::Load(input.c_str());
root_ = Traverse(root);
}
catch (const YAML::Exception& e)
{
LM_LOG_ERROR("YAML exception: " + std::string(e.what()));
return false;
}
#pragma endregion
return true;
};
LM_IMPL_F(LoadFromStringWithFilename) = [this](const std::string& input, const std::string& path, const std::string& basepath) -> bool
{
path_ = path;
basepath_ = basepath;
return LoadFromString(input);
};
LM_IMPL_F(Path) = [this]() -> std::string
{
return path_;
};
LM_IMPL_F(BasePath) = [this]() -> std::string
{
return basepath_;
};
LM_IMPL_F(Root) = [this]() -> const PropertyNode*
{
return root_;
};
LM_IMPL_F(RawInput) = [this]() -> std::string
{
return input_;
};
private:
std::string path_;
std::string basepath_;
std::string input_;
const PropertyNode* root_;
std::vector<PropertyNode::UniquePtr> nodes_;
};
LM_COMPONENT_REGISTER_IMPL_DEFAULT(PropertyTree_);
LM_NAMESPACE_END
| 30 | 165 | 0.56176 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.