hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
72c1f3333c2bc79576dfeef27ab7985f0803b4e5
17,317
cpp
C++
src/Painless_Mesh/painlessMeshSync.cpp
jaafreitas/IoTmeshToy
bb6bc6b95415f87167ef7fbd489baef9e8829044
[ "MIT" ]
7
2017-05-04T02:49:02.000Z
2019-08-01T19:17:46.000Z
src/Painless_Mesh/painlessMeshSync.cpp
jaafreitas/IoTmeshToy
bb6bc6b95415f87167ef7fbd489baef9e8829044
[ "MIT" ]
null
null
null
src/Painless_Mesh/painlessMeshSync.cpp
jaafreitas/IoTmeshToy
bb6bc6b95415f87167ef7fbd489baef9e8829044
[ "MIT" ]
5
2017-04-26T01:07:09.000Z
2020-09-17T15:29:57.000Z
#include "painlessMesh.h" #include "painlessMeshSync.h" #include "painlessMeshJson.h" #include "time.h" extern painlessMesh* staticThis; uint32_t timeAdjuster = 0; // timeSync Functions //*********************************************************************** uint32_t ICACHE_FLASH_ATTR painlessMesh::getNodeTime(void) { auto base_time = micros(); uint32_t ret = base_time + timeAdjuster; debugMsg(GENERAL, "getNodeTime(): time=%u\n", ret); return ret; } //*********************************************************************** String ICACHE_FLASH_ATTR timeSync::buildTimeStamp(timeSyncMessageType_t timeSyncMessageType, uint32_t originateTS, uint32_t receiveTS, uint32_t transmitTS) { staticThis->debugMsg(S_TIME, "buildTimeStamp(): Type = %u, t0 = %u, t1 = %u, t2 = %u\n", timeSyncMessageType, originateTS, receiveTS, transmitTS); #if ARDUINOJSON_VERSION_MAJOR==6 StaticJsonDocument<75> jsonBuffer; JsonObject timeStampObj = jsonBuffer.to<JsonObject>(); #else StaticJsonBuffer<75> jsonBuffer; JsonObject& timeStampObj = jsonBuffer.createObject(); #endif timeStampObj["type"] = (int)timeSyncMessageType; if (originateTS > 0) timeStampObj["t0"] = originateTS; if (receiveTS > 0) timeStampObj["t1"] = receiveTS; if (transmitTS > 0) timeStampObj["t2"] = transmitTS; String timeStampStr; #if ARDUINOJSON_VERSION_MAJOR==6 serializeJson(timeStampObj, timeStampStr); #else timeStampObj.printTo(timeStampStr); #endif staticThis->debugMsg(S_TIME, "buildTimeStamp(): timeStamp=%s\n", timeStampStr.c_str()); return timeStampStr; } //*********************************************************************** timeSyncMessageType_t ICACHE_FLASH_ATTR timeSync::processTimeStampDelay(String &str) { // Extracts and fills timestamp values from json timeSyncMessageType_t ret = TIME_SYNC_ERROR; staticThis->debugMsg(S_TIME, "processTimeStamp(): str=%s\n", str.c_str()); #if ARDUINOJSON_VERSION_MAJOR==6 DynamicJsonDocument jsonBuffer(1024 + str.length()); DeserializationError error = deserializeJson(jsonBuffer, str); if (error) { staticThis->debugMsg(ERROR, "processTimeStamp(): out of memory1?\n"); return TIME_SYNC_ERROR; } JsonObject timeStampObj = jsonBuffer.as<JsonObject>(); #else DynamicJsonBuffer jsonBuffer(75); JsonObject& timeStampObj = jsonBuffer.parseObject(str); if (!timeStampObj.success()) { staticThis->debugMsg(ERROR, "processTimeStamp(): out of memory1?\n"); return TIME_SYNC_ERROR; } #endif ret = static_cast<timeSyncMessageType_t>(timeStampObj["type"].as<int>()); if (ret == TIME_REQUEST || ret == TIME_RESPONSE) { timeDelay[0] = timeStampObj["t0"].as<uint32_t>(); } if (ret == TIME_RESPONSE) { timeDelay[1] = timeStampObj["t1"].as<uint32_t>(); timeDelay[2] = timeStampObj["t2"].as<uint32_t>(); } return ret; // return type of sync message } //*********************************************************************** int32_t ICACHE_FLASH_ATTR timeSync::calcAdjustment(uint32_t times[NUMBER_OF_TIMESTAMPS]) { staticThis->debugMsg(S_TIME, "calcAdjustment(): Start calculation. t0 = %u, t1 = %u, t2 = %u, t3 = %u\n", times[0], times[1], times[2], times[3]); if (times[0] == 0 || times[1] == 0 || times[2] == 0 || times[3] == 0) { // if any value is 0 staticThis->debugMsg(ERROR, "calcAdjustment(): TimeStamp error.\n"); return 0x7FFFFFFF; // return max value } // We use the SNTP protocol https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm. uint32_t offset = ((int32_t)(times[1] - times[0]) / 2) + ((int32_t)(times[2] - times[3]) / 2); if (offset < TASK_SECOND && offset > 4) timeAdjuster += offset/4; // Take small steps to avoid over correction else timeAdjuster += offset; // Accumulate offset staticThis->debugMsg(S_TIME, "calcAdjustment(): Calculated offset %d us.\n", offset); staticThis->debugMsg(S_TIME, "calcAdjustment(): New adjuster = %u. New time = %u\n", timeAdjuster, staticThis->getNodeTime()); return offset; // return offset to decide if sync is OK } //*********************************************************************** int32_t ICACHE_FLASH_ATTR timeSync::delayCalc() { staticThis->debugMsg(S_TIME, "delayCalc(): Start calculation. t0 = %u, t1 = %u, t2 = %u, t3 = %u\n", timeDelay[0], timeDelay[1], timeDelay[2], timeDelay[3]); if (timeDelay[0] == 0 || timeDelay[1] == 0 || timeDelay[2] == 0 || timeDelay[3] == 0) { // if any value is 0 staticThis->debugMsg(ERROR, "delayCalc(): TimeStamp error.\n"); return -1; // return max value } // We use the SNTP protocol https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm. uint32_t tripDelay = ((timeDelay[3] - timeDelay[0]) - (timeDelay[2] - timeDelay[1]))/2; staticThis->debugMsg(S_TIME, "delayCalc(): Calculated Network delay %d us\n", tripDelay); return tripDelay; } //*********************************************************************** void ICACHE_FLASH_ATTR painlessMesh::handleNodeSync(std::shared_ptr<MeshConnection> conn, JsonObject& root) { debugMsg(SYNC, "handleNodeSync(): with %u\n", conn->nodeId); meshPackageType message_type = (meshPackageType)(int)root["type"]; uint32_t remoteNodeId = root["from"]; if (remoteNodeId == 0) { debugMsg(ERROR, "handleNodeSync(): received invalid remote nodeId\n"); return; } if (conn->newConnection) { // There is a small but significant probability that we get connected twice to the // same node, e.g. if scanning happened while sub connection data was incomplete. auto oldConnection = findConnection(remoteNodeId); if (oldConnection) { debugMsg(SYNC, "handleNodeSync(): already connected to %u. Closing the new connection \n", remoteNodeId); conn->close(); return; } // debugMsg(SYNC, "handleNodeSync(): conn->nodeId updated from %u to %u\n", conn->nodeId, remoteNodeId); conn->nodeId = remoteNodeId; // TODO: Move this to its own function newConnectionTask.set(TASK_SECOND, TASK_ONCE, [remoteNodeId]() { staticThis->debugMsg(CONNECTION, "newConnectionTask():\n"); staticThis->debugMsg(CONNECTION, "newConnectionTask(): adding %u now= %u\n", remoteNodeId, staticThis->getNodeTime()); if (staticThis->newConnectionCallback) staticThis->newConnectionCallback(remoteNodeId); // Connection dropped. Signal user }); _scheduler.addTask(newConnectionTask); newConnectionTask.enable(); // Initially interval is every 10 seconds, // this will slow down to TIME_SYNC_INTERVAL // after first succesfull sync conn->timeSyncTask.set(10*TASK_SECOND, TASK_FOREVER, [conn]() { staticThis->debugMsg(S_TIME, "timeSyncTask(): %u\n", conn->nodeId); staticThis->startTimeSync(conn); }); _scheduler.addTask(conn->timeSyncTask); if (conn->station) // We are STA, request time immediately conn->timeSyncTask.enable(); else // We are the AP, give STA the change to initiate time sync conn->timeSyncTask.enableDelayed(); conn->newConnection = false; } if (conn->nodeId != remoteNodeId) { debugMsg(SYNC, "handleNodeSync(): Changed nodeId %u, closing connection %u.\n", conn->nodeId, remoteNodeId); conn->close(); return; } // check to see if subs have changed. String inComingSubs = root["subs"]; bool changed = !conn->subConnections.equals(inComingSubs); painlessmesh::parseNodeSyncRoot(conn, root, changed); if (changed) { // change in the network // Check whether we already know any of the nodes // This is necessary to avoid loops.. Not sure if we need to check // for both this node and master node, but better safe than sorry if ( painlessmesh::stringContainsNumber(inComingSubs, String(conn->nodeId)) || painlessmesh::stringContainsNumber(inComingSubs, String(this->_nodeId))) { // This node is also in the incoming subs, so we have a loop // Disconnecting to break the loop debugMsg(SYNC, "handleNodeSync(): Loop detected, disconnecting %u.\n", remoteNodeId); conn->close(); return; } debugMsg(SYNC, "handleNodeSync(): Changed connections %u.\n", remoteNodeId); conn->subConnections = inComingSubs; if (changedConnectionsCallback) changedConnectionsCallback(); staticThis->syncSubConnections(conn->nodeId); } else { stability += min(1000-stability,(size_t)25); } debugMsg(SYNC, "handleNodeSync(): json = %s\n", inComingSubs.c_str()); switch (message_type) { case NODE_SYNC_REQUEST: { debugMsg(SYNC, "handleNodeSync(): valid NODE_SYNC_REQUEST %u sending NODE_SYNC_REPLY\n", conn->nodeId); String myOtherSubConnections = subConnectionJson(conn); sendMessage(conn, conn->nodeId, _nodeId, NODE_SYNC_REPLY, myOtherSubConnections, true); break; } case NODE_SYNC_REPLY: debugMsg(SYNC, "handleNodeSync(): valid NODE_SYNC_REPLY from %u\n", conn->nodeId); break; default: debugMsg(ERROR, "handleNodeSync(): weird type? %d\n", message_type); } } //*********************************************************************** void ICACHE_FLASH_ATTR painlessMesh::startTimeSync(std::shared_ptr<MeshConnection> conn) { String timeStamp; debugMsg(S_TIME, "startTimeSync(): with %u, local port: %d\n", conn->nodeId, conn->client->getLocalPort()); auto adopt = adoptionCalc(conn); if (adopt) { timeStamp = conn->time.buildTimeStamp(TIME_REQUEST, getNodeTime()); // Ask other party its time debugMsg(S_TIME, "startTimeSync(): Requesting %u to adopt our time\n", conn->nodeId); } else { timeStamp = conn->time.buildTimeStamp(TIME_SYNC_REQUEST); // Tell other party to ask me the time debugMsg(S_TIME, "startTimeSync(): Requesting time from %u\n", conn->nodeId); } sendMessage(conn, conn->nodeId, _nodeId, TIME_SYNC, timeStamp, true); } //*********************************************************************** bool ICACHE_FLASH_ATTR painlessMesh::adoptionCalc(std::shared_ptr<MeshConnection> conn) { if (conn == NULL) // Missing connection return false; // make the adoption calulation. Figure out how many nodes I am connected to exclusive of this connection. // We use length as an indicator for how many subconnections both nodes have uint16_t mySubCount = subConnectionJson(conn).length(); //exclude this connection. uint16_t remoteSubCount = conn->subConnections.length(); bool ap = conn->client->getLocalPort() == _meshPort; // ToDo. Simplify this logic bool ret = (mySubCount > remoteSubCount) ? false : true; if (mySubCount == remoteSubCount && ap) { // in case of draw, ap wins ret = false; } debugMsg(S_TIME, "adoptionCalc(): mySubCount=%d remoteSubCount=%d role=%s adopt=%s\n", mySubCount, remoteSubCount, ap ? "AP" : "STA", ret ? "true" : "false"); return ret; } //*********************************************************************** void ICACHE_FLASH_ATTR painlessMesh::handleTimeSync(std::shared_ptr<MeshConnection> conn, JsonObject& root, uint32_t receivedAt) { auto timeSyncMessageType = static_cast<timeSyncMessageType_t>(root["msg"]["type"].as<int>()); String msg; switch (timeSyncMessageType) { case (TIME_SYNC_ERROR): debugMsg(S_TIME, "handleTimeSync(): Received time sync error. Restarting time sync.\n"); conn->timeSyncTask.forceNextIteration(); break; case (TIME_SYNC_REQUEST): // Other party request me to ask it for time debugMsg(S_TIME, "handleTimeSync(): Received requesto to start TimeSync with node: %u\n", conn->nodeId); root["msg"]["type"] = static_cast<int>(TIME_REQUEST); root["msg"]["t0"] = getNodeTime(); msg = root["msg"].as<String>(); staticThis->sendMessage(conn, conn->nodeId, _nodeId, TIME_SYNC, msg, true); break; case (TIME_REQUEST): root["msg"]["type"] = static_cast<int>(TIME_RESPONSE); root["msg"]["t1"] = receivedAt; root["msg"]["t2"] = getNodeTime(); msg = root["msg"].as<String>(); staticThis->sendMessage(conn, conn->nodeId, _nodeId, TIME_SYNC, msg, true); // Build time response debugMsg(S_TIME, "handleTimeSync(): Response sent %s\n", msg.c_str()); debugMsg(S_TIME, "handleTimeSync(): timeSyncStatus with %u completed\n", conn->nodeId); // After response is sent I assume sync is completed conn->timeSyncTask.delay(TIME_SYNC_INTERVAL); break; case (TIME_RESPONSE): debugMsg(S_TIME, "handleTimeSync(): TIME RESPONSE received.\n"); uint32_t times[NUMBER_OF_TIMESTAMPS] = { root["msg"]["t0"], root["msg"]["t1"], root["msg"]["t2"], receivedAt}; int32_t offset = conn->time.calcAdjustment(times); // Adjust time and get calculated offset // flag all connections for re-timeSync if (nodeTimeAdjustedCallback) { nodeTimeAdjustedCallback(offset); } if (offset < TIME_SYNC_ACCURACY && offset > -TIME_SYNC_ACCURACY) { // mark complete only if offset was less than 10 ms conn->timeSyncTask.delay(TIME_SYNC_INTERVAL); debugMsg(S_TIME, "handleTimeSync(): timeSyncStatus with %u completed\n", conn->nodeId); // Time has changed, update other nodes for (auto &&connection : _connections) { if (connection->nodeId != conn->nodeId) { // exclude this connection connection->timeSyncTask.forceNextIteration(); debugMsg(S_TIME, "handleTimeSync(): timeSyncStatus with %u brought forward\n", connection->nodeId); } } } else { // Iterate sync procedure if accuracy was not enough conn->timeSyncTask.delay(200*TASK_MILLISECOND); // Small delay debugMsg(S_TIME, "handleTimeSync(): timeSyncStatus with %u needs further tries\n", conn->nodeId); } break; } debugMsg(S_TIME, "handleTimeSync(): ----------------------------------\n"); } void ICACHE_FLASH_ATTR painlessMesh::handleTimeDelay(std::shared_ptr<MeshConnection> conn, JsonObject& root, uint32_t receivedAt) { String timeStamp = root["msg"]; uint32_t from = root["from"]; debugMsg(S_TIME, "handleTimeDelay(): from %u in timestamp = %s\n", from, timeStamp.c_str()); timeSyncMessageType_t timeSyncMessageType = conn->time.processTimeStampDelay(timeStamp); // Extract timestamps and get type of message String t_stamp; switch (timeSyncMessageType) { case (TIME_SYNC_ERROR): debugMsg(ERROR, "handleTimeDelay(): Error in requesting time delay. Please try again.\n"); break; case (TIME_REQUEST): //conn->timeSyncStatus == IN_PROGRESS; debugMsg(S_TIME, "handleTimeDelay(): TIME REQUEST received.\n"); // Build time response t_stamp = conn->time.buildTimeStamp(TIME_RESPONSE, conn->time.timeDelay[0], receivedAt, getNodeTime()); staticThis->sendMessage(conn, from, _nodeId, TIME_DELAY, t_stamp); debugMsg(S_TIME, "handleTimeDelay(): Response sent %s\n", t_stamp.c_str()); // After response is sent I assume sync is completed //conn->timeSyncStatus == COMPLETE; //conn->lastTimeSync = getNodeTime(); break; case (TIME_RESPONSE): { debugMsg(S_TIME, "handleTimeDelay(): TIME RESPONSE received.\n"); conn->time.timeDelay[3] = receivedAt; // Calculate fourth timestamp (response received time) int32_t delay = conn->time.delayCalc(); // Adjust time and get calculated offset debugMsg(S_TIME, "handleTimeDelay(): Delay is %d\n", delay); //conn->timeSyncStatus == COMPLETE; if (nodeDelayReceivedCallback) nodeDelayReceivedCallback(from, delay); } break; default: debugMsg(S_TIME, "handleTimeDelay(): Unknown timeSyncMessageType received. Ignoring for now.\n"); } debugMsg(S_TIME, "handleTimeSync(): ----------------------------------\n"); } void ICACHE_FLASH_ATTR painlessMesh::syncSubConnections(uint32_t changedId) { debugMsg(SYNC, "syncSubConnections(): changedId = %u\n", changedId); for (auto &&connection : _connections) { if (connection->connected && !connection->newConnection && connection->nodeId != 0 && connection->nodeId != changedId) { // Exclude current connection->nodeSyncTask.forceNextIteration(); } } staticThis->stability /= 2; }
41.828502
162
0.620951
jaafreitas
72c3cbda03a0d09996564859542dafec9baa5ca8
8,128
cpp
C++
src/bin/settings.cpp
D7ry/valhallaCombat
07929d29a48401c2878a1ed5993b7bba14743c6f
[ "MIT" ]
1
2022-01-19T07:13:48.000Z
2022-01-19T07:13:48.000Z
src/bin/settings.cpp
D7ry/valhallaCombat
07929d29a48401c2878a1ed5993b7bba14743c6f
[ "MIT" ]
null
null
null
src/bin/settings.cpp
D7ry/valhallaCombat
07929d29a48401c2878a1ed5993b7bba14743c6f
[ "MIT" ]
1
2022-01-19T07:13:52.000Z
2022-01-19T07:13:52.000Z
#include "include/stunHandler.h" #include "include/settings.h" #include "ValhallaCombat.hpp" using namespace Utils; void settings::ReadIntSetting(CSimpleIniA& a_ini, const char* a_sectionName, const char* a_settingName, uint32_t& a_setting) { const char* bFound = nullptr; bFound = a_ini.GetValue(a_sectionName, a_settingName); if (bFound) { //INFO("found {} with value {}", a_settingName, bFound); a_setting = static_cast<int>(a_ini.GetDoubleValue(a_sectionName, a_settingName)); } } void settings::ReadFloatSetting(CSimpleIniA& a_ini, const char* a_sectionName, const char* a_settingName, float& a_setting) { const char* bFound = nullptr; bFound = a_ini.GetValue(a_sectionName, a_settingName); if (bFound) { //INFO("found {} with value {}", a_settingName, bFound); a_setting = static_cast<float>(a_ini.GetDoubleValue(a_sectionName, a_settingName)); } } void settings::ReadBoolSetting(CSimpleIniA& a_ini, const char* a_sectionName, const char* a_settingName, bool& a_setting) { const char* bFound = nullptr; bFound = a_ini.GetValue(a_sectionName, a_settingName); if (bFound) { //INFO("found {} with value {}", a_settingName, bFound); a_setting = a_ini.GetBoolValue(a_sectionName, a_settingName); } } void settings::init() { INFO("Initilize settings..."); auto dataHandler = RE::TESDataHandler::GetSingleton(); if (dataHandler) { #define LOOKGLOBAL dataHandler->LookupForm<RE::TESGlobal> glob_Nemesis_EldenCounter_Damage = LOOKGLOBAL(0x56A23, "ValhallaCombat.esp"); glob_Nemesis_EldenCounter_NPC = LOOKGLOBAL(0x56A24, "ValhallaCombat.esp"); glob_TrueHudAPI = LOOKGLOBAL(0x56A25, "ValhallaCombat.esp"); glob_TrueHudAPI_SpecialMeter = LOOKGLOBAL(0x56A26, "ValhallaCombat.esp"); } INFO("...done"); } void settings::updateGlobals() { INFO("Update globals..."); if (glob_TrueHudAPI) { glob_TrueHudAPI->value = ValhallaCombat::GetSingleton()->ersh != nullptr ? 1.f : 0.f; } if (glob_TrueHudAPI_SpecialMeter) { glob_TrueHudAPI_SpecialMeter->value = TrueHudAPI_HasSpecialBarControl ? 1.f : 0.f; } auto pc = RE::PlayerCharacter::GetSingleton(); if (pc) { if (glob_Nemesis_EldenCounter_Damage) { bool bDummy; glob_Nemesis_EldenCounter_Damage->value = pc->GetGraphVariableBool("is_Guard_Countering", bDummy); } if (glob_Nemesis_EldenCounter_NPC) { bool bDummy; glob_Nemesis_EldenCounter_NPC->value = pc->GetGraphVariableBool("IsValGC", bDummy); } } INFO("...done"); } /*read settings from ini, and update them into game settings.*/ void settings::readSettings() { INFO("Read ini settings..."); #if JL_AntiPiracy #define anti_PiracyMsg_PATH "Data\\Val_Config.ini" CSimpleIniA anti_PiracyMsg; anti_PiracyMsg.LoadFile(anti_PiracyMsg_PATH); JueLun_LoadMsg = anti_PiracyMsg.GetValue("load", "msg"); auto hash = std::hash<std::string>{}(JueLun_LoadMsg); INFO(hash); if (hash != 13375109384697678453) { ERROR("Error: Mod Piracy detected"); } #endif #define SETTINGFILE_PATH "Data\\MCM\\Settings\\ValhallaCombat.ini" CSimpleIniA mcm; mcm.LoadFile(SETTINGFILE_PATH); std::list<CSimpleIniA::Entry> ls; /*Read stamina section*/ ReadBoolSetting(mcm, "Stamina", "bUIalert", bUIAlert); ReadBoolSetting(mcm, "Stamina", "bNonCombatStaminaDebuff", bNonCombatStaminaDebuff); ReadFloatSetting(mcm, "Stamina", "fStaminaRegenMult", fStaminaRegenMult); ReadFloatSetting(mcm, "Stamina", "fStaminaRegenLimit", fStaminaRegenLimit); ReadFloatSetting(mcm, "Stamina", "fCombatStaminaRegenMult", fCombatStaminaRegenMult); ReadFloatSetting(mcm, "Stamina", "fStaminaRegenDelay", fStaminaRegenDelay); ReadBoolSetting(mcm, "Stamina", "bBlockStaminaToggle", bBlockStaminaToggle); ReadBoolSetting(mcm, "Stamina", "bGuardBreak", bGuardBreak); ReadFloatSetting(mcm, "Stamina", "fBckShdStaminaMult_NPC_Block_NPC", fBckShdStaminaMult_NPC_Block_NPC); ReadFloatSetting(mcm, "Stamina", "fBckShdStaminaMult_NPC_Block_PC", fBckShdStaminaMult_NPC_Block_PC); ReadFloatSetting(mcm, "Stamina", "fBckShdStaminaMult_PC_Block_NPC", fBckShdStaminaMult_PC_Block_NPC); ReadFloatSetting(mcm, "Stamina", "fBckWpnStaminaMult_NPC_Block_NPC", fBckWpnStaminaMult_NPC_Block_NPC); ReadFloatSetting(mcm, "Stamina", "fBckWpnStaminaMult_NPC_Block_PC", fBckWpnStaminaMult_NPC_Block_PC); ReadFloatSetting(mcm, "Stamina", "fBckWpnStaminaMult_PC_Block_NPC", fBckWpnStaminaMult_PC_Block_NPC); ReadBoolSetting(mcm, "Stamina", "bAttackStaminaToggle", bAttackStaminaToggle); ReadBoolSetting(mcm, "Stamina", "bBlockedHitRegenStamina", bBlockedHitRegenStamina); ReadFloatSetting(mcm, "Stamina", "fMeleeCostLightMiss_Point", fMeleeCostLightMiss_Point); ReadFloatSetting(mcm, "Stamina", "fMeleeRewardLightHit_Percent", fMeleeRewardLightHit_Percent); ReadFloatSetting(mcm, "Stamina", "fMeleeCostHeavyMiss_Percent", fMeleeCostHeavyMiss_Percent); ReadFloatSetting(mcm, "Stamina", "fMeleeCostHeavyHit_Percent", fMeleeCostHeavyHit_Percent); /*Read perfect blocking section*/ ReadBoolSetting(mcm, "Parrying", "bBlockProjectileToggle", bBlockProjectileToggle); ReadBoolSetting(mcm, "Parrying", "bTimedBlockToggle", bTimedBlockToggle); ReadBoolSetting(mcm, "Parrying", "bTimedBlockProjectileToggle", bTimedBlockProjectileToggle); ReadBoolSetting(mcm, "Parrying", "bTimedBlockScreenShake", bTimedBlockScreenShake); ReadBoolSetting(mcm, "Parrying", "bTimeBlockSFX", bTimeBlockSFX); ReadBoolSetting(mcm, "Parrying", "bTimedBlockVFX", bTimedBlockVFX); ReadBoolSetting(mcm, "Parrying", "bTimedBlockSlowTime", bTimedBlockSlowTime); ReadFloatSetting(mcm, "Parrying", "fTimedBlockWindow", fTimedBlockWindow); ReadFloatSetting(mcm, "Parrying", "fTimedBlockCooldownTime", fTimedBlockCooldownTime); ReadFloatSetting(mcm, "Parrying", "fTimedBlockStaminaCostMult", fTimedBlockStaminaCostMult); ReadIntSetting(mcm, "Parrying", "uAltBlockKey", uAltBlockKey); /*Read stun section*/ ReadBoolSetting(mcm, "Stun", "bStunToggle", bStunToggle); ReadBoolSetting(mcm, "Stun", "bStunMeterToggle", bStunMeterToggle); ReadBoolSetting(mcm, "Stun", "bExecutionLimit", bExecutionLimit); ReadFloatSetting(mcm, "Stun", "fStunParryMult", fStunParryMult); ReadFloatSetting(mcm, "Stun", "fStunBashMult", fStunBashMult); ReadFloatSetting(mcm, "Stun", "fStunPowerBashMult", fStunPowerBashMult); ReadFloatSetting(mcm, "Stun", "fStunNormalAttackMult", fStunNormalAttackMult); ReadFloatSetting(mcm, "Stun", "fStunPowerAttackMult", fStunPowerAttackMult); ReadFloatSetting(mcm, "Stun", "fStunUnarmedMult", fStunUnarmedMult); ReadFloatSetting(mcm, "Stun", "fStunDaggerMult", fStunDaggerMult); ReadFloatSetting(mcm, "Stun", "fStunSwordMult", fStunSwordMult); ReadFloatSetting(mcm, "Stun", "fStunWarAxeMult", fStunWarAxeMult); ReadFloatSetting(mcm, "Stun", "fStunMaceMult", fStunMaceMult); ReadFloatSetting(mcm, "Stun", "fStunGreatSwordMult", fStunGreatSwordMult); ReadFloatSetting(mcm, "Stun", "fStun2HBluntMult", fStun2HBluntMult); ReadBoolSetting(mcm, "Stun", "bAutoExecution", bAutoExecution); ReadIntSetting(mcm, "Stun", "uExecutionKey", uExecutionKey); ReadBoolSetting(mcm, "Compatibility", "bPoiseCompatibility", bPoiseCompatibility); /*Read Balance section*/ ReadBoolSetting(mcm, "Balance", "bBalanceToggle", bBalanceToggle); INFO("...done"); INFO("Apply game settings..."); /*Set some game settings*/ setGameSettingf("fDamagedStaminaRegenDelay", fStaminaRegenDelay); setGameSettingf("fCombatStaminaRegenRateMult", fCombatStaminaRegenMult); /* setGameSettingf("fStaggerMin", 0); setGameSettingf("fStaggerPlayerMassMult", 0); setGameSettingf("fStaminaAttackWeaponBase", 0); setGameSettingf("fStaggerAttackMult", 0); setGameSettingf("fStaggerAttackBase", 0); setGameSettingf("fStaggerMassBase", 0); setGameSettingf("fStaggerMassMult", 0); setGameSettingf("fStaggerMassOffsetBase", 0); setGameSettingf("fStaggerMassOffsetMult", 0); setGameSettingb("bPlayStaggers:Combat", false);*/ multStaminaRegen(fStaminaRegenMult, fStaminaRegenLimit); /*Release truehud meter if set so.*/ if (bStunMeterToggle && bStunToggle){ ValhallaCombat::GetSingleton()->requestTrueHudSpecialBarControl(); } else { ValhallaCombat::GetSingleton()->releaseTrueHudSpecialBarControl(); } INFO("...done"); }
45.155556
126
0.779405
D7ry
72c3fe1c2eb1c0d8e098ce9d2704980581650056
1,207
cpp
C++
ch_3/p3-5.cpp
bg2d/accelerated_cpp
a558d90090ceadeedd83e4726f6e7497219e9626
[ "MIT" ]
null
null
null
ch_3/p3-5.cpp
bg2d/accelerated_cpp
a558d90090ceadeedd83e4726f6e7497219e9626
[ "MIT" ]
null
null
null
ch_3/p3-5.cpp
bg2d/accelerated_cpp
a558d90090ceadeedd83e4726f6e7497219e9626
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> int main() { const int NO_HOMEWORKS = 3; std::vector<std::string> students; std::vector<double> grades; std::string name; std::cout << "Please give the sutend's name: "; while (std::cin >> name) { students.push_back(name); // ask for and read the midterm and final grades std::cout << "Please enter student's midterm and final exam grades:"; double midterm, final; std::cin >> midterm >> final; // read the homeworks' grades std::cout << "Enter all student's homework grades: "; double grade; double sum = 0; for (int i = 0; i < NO_HOMEWORKS; i++) { std::cin >> grade; sum += grade; } double final_grade = 0.2 * midterm + 0.4 * final + 0.4 * sum / NO_HOMEWORKS; grades.push_back(final_grade); std::cout << std::endl; std::cout << "Please give the name of another student or end-of-file to exit: "; } // display the final result for (int i = 0; i < students.size(); i++) { std::cout << students[i] << " : " << grades[i] << std::endl; } return 0; }
28.069767
88
0.553438
bg2d
72c614948d1978a55a64a0988f3443249e92771e
570
hpp
C++
src/miniframes/miniframe.hpp
helloer/polybobin
63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1
[ "MIT" ]
8
2016-10-06T11:49:14.000Z
2021-11-06T21:06:36.000Z
src/miniframes/miniframe.hpp
helloer/polybobin
63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1
[ "MIT" ]
20
2017-04-25T14:23:02.000Z
2018-12-04T22:46:04.000Z
src/miniframes/miniframe.hpp
helloer/polybobin
63b2cea40d3afcfc9d6f62f49acbfacf6a8783e1
[ "MIT" ]
4
2018-07-04T00:14:41.000Z
2018-07-17T09:08:25.000Z
#ifndef MINIFRAME_HPP #define MINIFRAME_HPP #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/minifram.h> /** * \brief Generic mini frame with custom behavior. */ class MiniFrame: public wxMiniFrame { public: MiniFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize &size); void ToggleVisibility(); private: /** * \brief We want custom behavior when the "X" icon is pressed. */ void OnClosed(wxCloseEvent &event); }; #endif
21.111111
119
0.659649
helloer
72c640e5c1c99d1e9d1492a77c840eb641a07413
121
cpp
C++
Source/QuarantineProject/Private/Inventory/QP_InventoryItem.cpp
AInsolence/QuarantineProject
99e07b82edbf05510453822383d713602c4a3510
[ "MIT" ]
1
2021-08-28T04:07:58.000Z
2021-08-28T04:07:58.000Z
Source/QuarantineProject/Private/Inventory/QP_InventoryItem.cpp
AInsolence/QuarantineProject
99e07b82edbf05510453822383d713602c4a3510
[ "MIT" ]
null
null
null
Source/QuarantineProject/Private/Inventory/QP_InventoryItem.cpp
AInsolence/QuarantineProject
99e07b82edbf05510453822383d713602c4a3510
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Inventory/QP_InventoryItem.h"
24.2
78
0.793388
AInsolence
72cecc7e5d7d83c7a40a07c1af0dd53f8fc53f4e
12,655
cpp
C++
Settings.cpp
Bozebo/buddhabrot
71bf4d971c0305e7ef063ebc7bb03b3eab88d81e
[ "Unlicense" ]
1
2018-10-23T21:49:30.000Z
2018-10-23T21:49:30.000Z
Settings.cpp
Bozebo/buddhabrot
71bf4d971c0305e7ef063ebc7bb03b3eab88d81e
[ "Unlicense" ]
null
null
null
Settings.cpp
Bozebo/buddhabrot
71bf4d971c0305e7ef063ebc7bb03b3eab88d81e
[ "Unlicense" ]
null
null
null
#include "Settings.h" //the constructor sets up some workable defaults Settings::Settings() { // ----- Orbits //if an orbit has not been determined as being outside the set in at least this many iterations (n, AKA orbit depth), discard it maxIts = 10000; //if an orbit _has_ been determined as being outside the set in less than this many iterations, discard it minIts = 18; //how orbit start locations are decided orbitMode = 2; // 2; //0 = naive (full random), 1 = apertures (my strange method of finding detailed orbit starts), 2 = metropolis hastings //GA (Genetic Algorithm) settings, the GA allows for painting more detailed orbits (only for apertures orbit mode) //the size of the orbit casting "box", a smaller number makes a smaller box //orbits casts are begun from random seeds within the box (instead of the whole plane) //until the box moves (a "set" of casts), to a new random location //mutStr = 0.005; //mutStr = 0.0025; mutStr = 0.0075; mutStrFocus = 0.0025; //smaller casting box for more exaggerated GA outcome when in "focus mode" (hold I by default) //mutation set "size", the box moves once this reaches 0 //maxMutations = 4096; maxMutations = 2048; maxMutationsFocus = 4096; // ----- Painting xRes = 768; yRes = 768; brightness = 1.0f; gamma = 1.0f; //important: this applies when outputting the buddhabrot to an RGB bitmap (texture or image file). Not when painting orbits. colMethod = 1; //1 = sqrt (better), otherwise linear (poorly shows details). //viewport: //these settings are good for a 0.0, 0.0 julia seed and viewing the zR, zI plane ("default") xScale = 2.7; yScale = 2.5; xOffset = -0.48; yOffset = 0; /* xScale = 3.0; yScale = 2.5; xOffset = -0.5; yOffset = 0.0; */ /* xScale = .017; yScale = .017; xOffset = -0.158; yOffset = 1.034; */ //good for zooming into a minibrot on the stalk //xScale = 0.0002; //yScale = 0.0002; //xScale = 0.00018; //yScale = 0.0002; //xOffset = -1.484472; //yOffset = 0; //start - end orbit depths (n) for paint ranges //intensity is minimum at n=s and maximum at n=e (default painting method) //where n trends from minIts+start*(maxIts-minIts) to minIts+end*(maxIts-minIts) rStart = 0.002f, rEnd = 0.50f; gStart = 0.020f, gEnd = 0.75f; bStart = 0.200f, bEnd = 1.00f; //rStart = 0.01f, rEnd = 0.25f; //gStart = 0.2f, gEnd = 0.3f; //bStart = 0.28f, bEnd = 1.0f; /* sRed = 16; eRed = 512; sGreen = 64; eGreen = 1024; sBlue = 96; eBlue = 1100; */ // ----- Advanced //interesting visuals can be achieved on planes other than Zr, Zi xAxis = 0; //0 = Zr, 1 = Zi, 2 = Cr yAxis = 0; //0 = Zi, 1 = Cr, 2 = Ci //seed for juliabrot (0.0, 0.0 = mandel/buddhabrot) sR = 0; // -0.7; sI = 0; // -0.7; fourDims = false; //if true, z is also seeded at random paintMirror = false; //if using metropolis hastings, this enables mirroring painting around the center x axis of the image (so it should be false if not rendering a symmetrical viewport) skipIsOutsideMandel = false; //if true, isOutsideMandel is skipped forceSkipIsOutsideMandel = false; //if true, override automation of this setting paintStartMap = false; //if true, a buffer will be saved of where orbits that resulted in painting began from //custom orbit start region on the Z complex plane (defaults to mandelbrot range if false) doCustomOrbitStart = false; //mirrorCustomOrbitStart = true; /* orbitXScale = 0.016; orbitYScale = 0.016; orbitXOffset = -.1585; orbitYOffset = 1.033; */ /* xScale = 0.00018; yScale = 0.0002; xOffset = -1.484472; */ /* orbitXScale = 0.00019; orbitYScale = 0.00021; orbitXOffset = -1.484474; orbitYOffset = 0.0; */ } void Settings::init(){ // ----- Internal processing //start - end orbit depths (n) for paint ranges //intensity is minimum at n=s and maximum at n=e (default colouring method) paintStartIts = minIts; //paintStartIts = 4; //checking if there's any reason for paintStartIts to be different from minIts (maybe with some exotic colouring/painting) int intsDiff = maxIts - paintStartIts; sRed = paintStartIts + int(intsDiff * rStart); eRed = paintStartIts + int(intsDiff * rEnd); sGreen = paintStartIts + int(intsDiff * gStart); eGreen = paintStartIts + int(intsDiff * gEnd); sBlue = paintStartIts + int(intsDiff * bStart); eBlue = paintStartIts + int(intsDiff * bEnd); paintStartIts = (sRed < ( (sBlue < sGreen)? sBlue : sGreen))? sRed : ( (sBlue < sGreen)? sBlue : sGreen); //the smallest //skip quick mandelbrot region check if the plane is not default and skipIsOutsideMandel is not forced if(!forceSkipIsOutsideMandel && (xAxis != 0 && yAxis!= 0)) skipIsOutsideMandel = true; //sRed = minIts; //sGreen = minIts; //sBlue = minIts; /* sRed = 16; eRed = 512; sGreen = 64; eGreen = 1024; sBlue = 96; eBlue = 1100; */ /* if (xPlane == 1 && yPlane == 2){ //any other viewports are bad for the zI cI plane so override the setting xScale = 4.2; yScale = 2.3; xOffset = 0.0; yOffset = 0.0; } */ } Settings::~Settings() { } using namespace tinyxml2; int Settings::loadFromFile(const char* path){ settingsFile = new XMLDocument (); XMLError xmlErr = settingsFile->LoadFile(path); if (xmlErr != XML_SUCCESS){ FILE* xmlErrFile; //fopen_s(&xmlErrFile, "xmlErr.txt", "w"); //fprintf_s(xmlErrFile, "settings load failed: %d\n", xmlErr); xmlErrFile = fopen("xmlErr.txt", "w"); fprintf(xmlErrFile, "settings load failed: %d\n", xmlErr); fclose(xmlErrFile); if(xmlErr != XML_ERROR_FILE_NOT_FOUND) return -1; //failed return 0; } //find the first <brot> element with an "active" attribute set to true XMLElement* brot = settingsFile->FirstChildElement("brot"); while(brot != NULL){ bool bActive = false; brot->QueryBoolAttribute("active", &bActive); if(!bActive){ brot = brot->NextSiblingElement("brot"); continue; } //found our way here? then this is the (first, and only one we care about) active <brot> //~read window resolution // -- read texture resolution int sXRes, sYRes; int sRes = -1; brot->QueryIntAttribute("resolution", &sRes); switch(sRes){ //which resolutions can be used depends on the graphics device case 0: sXRes = sYRes = 512; break; case 1: sXRes = sYRes = 768; break; case 2: sXRes = sYRes = 1024; break; case 3: sXRes = sYRes = 2048; break; case 4: sXRes = sYRes = 4096; break; case 5: sXRes = sYRes = 8192; break; } //also read exact resolutions if specified brot->QueryIntAttribute("xRes", &sXRes); brot->QueryIntAttribute("yRes", &sYRes); //constrain values if(sXRes < 128) sXRes = 128; if(sYRes < 128) sYRes = 128; //apply the read values xRes = sXRes; yRes = sYRes; // -- read min and max iterations brot->QueryIntAttribute("minIts", &minIts); brot->QueryIntAttribute("maxIts", &maxIts); //constrain values if(minIts < 1) minIts = 1; if(maxIts < minIts) maxIts = minIts; // -- read colour start & end depths //XMLElement *col = brot->FirstChildElement("col"); //if(col != NULL){ //XMLElement *red = col->FirstChildElement("red"); XMLElement *red = brot->FirstChildElement("red"); if(red != NULL){ red->QueryFloatAttribute("start", &rStart); red->QueryFloatAttribute("end", &rEnd); if(rStart < 0.0f) rStart = 0.0f; if(rStart > 1.0f) rStart = 1.0f; if(rEnd < rStart) rEnd = rStart; } //XMLElement *green = col->FirstChildElement("green"); XMLElement *green = brot->FirstChildElement("green"); if(red != NULL){ green->QueryFloatAttribute("start", &gStart); green->QueryFloatAttribute("end", &gEnd); if(gStart < 0.0f) gStart = 0.0f; if(gStart > 1.0f) gStart = 1.0f; if(gEnd < gStart) gEnd = gStart; } //XMLElement *blue = col->FirstChildElement("blue"); XMLElement *blue = brot->FirstChildElement("blue"); if(red != NULL){ blue->QueryFloatAttribute("start", &bStart); blue->QueryFloatAttribute("end", &bEnd); if(bStart < 0.0f) bStart = 0.0f; if(bStart > 1.0f) bStart = 1.0f; if(bEnd < bStart) bEnd = bStart; } //} // -- read orbit mode brot->QueryIntAttribute("orbitMode", &orbitMode); if(orbitMode < 0) orbitMode = 0; if(orbitMode > 2) orbitMode = 2; // -- read viewport settings (x/y scale and x/y offset) if set XMLElement* viewport = brot->FirstChildElement("viewport"); if(viewport != NULL){ float sXScale, sYScale, sXOffset, sYOffset; viewport->QueryFloatAttribute("xScale", &sXScale); viewport->QueryFloatAttribute("yScale", &sYScale); viewport->QueryFloatAttribute("xOffset", &sXOffset); viewport->QueryFloatAttribute("yOffset", &sYOffset); //apply read values (can only read floats, no problem, but it's a double internally) xScale = sXScale; yScale = sYScale; xOffset = sXOffset; yOffset = sYOffset; //clamp scales as their internal form (double) if(xScale < 0.) xScale = 0.; if(yScale < 0.) yScale = 0.; } // -- read GA settings if orbit mode is apertures if(orbitMode == 1){ XMLElement* GA = brot->FirstChildElement("GA"); if(GA != NULL){ float sMutStr, sMutStrFocus; GA->QueryFloatAttribute("mutStr", &sMutStr); GA->QueryFloatAttribute("mutStrFocus", &sMutStrFocus); if(sMutStr < 0.f) sMutStr = 0.f; //0. is way too small, but let the user do what they want because it shouldn't cause bugs if(sMutStr > 1.f) sMutStr = 1.f; //1. is huge, same as above if(sMutStrFocus < 0.f) sMutStrFocus = 0.f; if(sMutStrFocus > 1.f) sMutStrFocus = 1.f; //don't even constrain this ^ to be sensible in relation to mutStr, it's the user's choice //apply read values (can only read floats, no problem, but it's a double internally) mutStr = sMutStr; mutStrFocus = sMutStrFocus; GA->QueryIntAttribute("maxMutations", &maxMutations); if(maxMutations < 0) maxMutations = 0; GA->QueryIntAttribute("maxMutationsFocus", &maxMutationsFocus); if(maxMutationsFocus < 0) maxMutationsFocus = 0; //again, don't even constrain this ^ to be sensible in relation to maxMutations, it's the user's choice } } // -- read complex planes to be rendered as x/y brot->QueryIntAttribute("xAxis", &xAxis); brot->QueryIntAttribute("yAxis", &yAxis); //clamp if(xAxis < 0) xAxis = 0; else if(xAxis > 2) xAxis = 2; if(yAxis < 0) yAxis = 0; else if(yAxis > 2) yAxis = 2; // -- read julia seed float sSR = float(sR), sSI = float(sI); brot->QueryFloatAttribute("sR", &sSR); brot->QueryFloatAttribute("sI", &sSI); sR = sSR; sI = sSI; // -- read custom orbit start, if set XMLElement* orbitStart = brot->FirstChildElement("orbitStart"); if(orbitStart != NULL){ doCustomOrbitStart = true; float sOXScale, sOYScale, sOXOffset, sOYOffset; //this "convention" is getting hard to read orbitStart->QueryFloatAttribute("xScale", &sOXScale); orbitStart->QueryFloatAttribute("yScale", &sOYScale); orbitStart->QueryFloatAttribute("xOffset", &sOXOffset); orbitStart->QueryFloatAttribute("yOffset", &sOYOffset); //apply read values (can only read floats, no problem, but it's a double internally) orbitXScale = sOXScale; orbitYScale = sOYScale; orbitXOffset = sOXOffset; orbitYOffset = sOYOffset; //clamp scales as their internal form (double) if(orbitXScale < 0.) orbitXScale = 0.; if(orbitYScale < 0.) orbitYScale = 0.; } // -- some more boolean values brot->QueryBoolAttribute("paintStartMap", &paintStartMap); brot->QueryBoolAttribute("randImaginary", &fourDims); brot->QueryBoolAttribute("paintMirror", &paintMirror); brot->QueryBoolAttribute("skipIsOutsideMandel", &skipIsOutsideMandel); brot->QueryBoolAttribute("forceSkipIsOutsideMandel", &forceSkipIsOutsideMandel); // -- should also add int-based colour ranges // -- allowing the start paint value to be specified instead of it being automated to the minimum colour range would also be good break; //don't infinite loop } delete settingsFile; //deconstruct the settings file return 1; //success }
27.391775
188
0.642197
Bozebo
72cf4197d08588a29618b64b9f8326a27d550bd8
2,649
cpp
C++
src/engine/memory/managermusic.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/memory/managermusic.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/memory/managermusic.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
#include "managermusic.hpp" #ifdef _USE_MUSIC_ #include "../engine.hpp" #define MAX_MUSIC_COUNT 105 ManagerMusic::ManagerMusic() { } ManagerMusic::~ManagerMusic() { for(auto &i : data) { i.second.ptr->stop(); delete (i.second.ptr); } } bool ManagerMusic::load(const std::string &name) { std::map<std::string, MusicContainer>::iterator it = data.find(name); if(it == data.end()) { MusicContainer tmp; tmp.ptr = new Music(); if(!tmp.ptr->load(name)) { delete tmp.ptr; return false; } data[name] = tmp; } data[name].toDelete = false; return true; } void ManagerMusic::unload(const std::string &name) { std::map<std::string, MusicContainer>::iterator it = data.find(name); if(it != data.end()) it->second.toDelete = true; } void ManagerMusic::play(const std::string &name) { if(data.size() >= MAX_MUSIC_COUNT) return; if(load(name)) { data[name].ptr->setVolume(engine.masterVolume); data[name].ptr->play(); } } void ManagerMusic::pause(const std::string &name) { if(data.find(name) != data.end()) { data[name].ptr->pause(); } } void ManagerMusic::stop(const std::string &name) { if(data.find(name) != data.end()) { data[name].ptr->stop(); } } std::vector<std::string> ManagerMusic::getMusicList() const { std::vector<std::string> l; l.reserve(data.size()); for(auto &i : data) l.push_back(i.first); return l; } void ManagerMusic::setLoop(const std::string &name, bool b, int32_t start, int32_t end) { if(data.find(name) != data.end()) { data[name].ptr->loop(b, start, end); } } void ManagerMusic::garbageCollection() { std::map<std::string, MusicContainer>::iterator it = data.begin(); std::map<std::string, MusicContainer>::iterator tmp; while(it != data.end()) { if(it->second.toDelete) { delete it->second.ptr; tmp = it; ++it; data.erase(tmp); } else ++it; } } void ManagerMusic::update() { for(auto &i : data) i.second.ptr->update(); } void ManagerMusic::setVolume(const std::string &name, float v) { if(data.find(name) != data.end()) { data[name].ptr->setVolume(v); } } void ManagerMusic::updateVolume() { for(auto &i : data) { i.second.ptr->setVolume(engine.masterVolume); } } void ManagerMusic::clear() { for(auto &i : data) { i.second.ptr->stop(); delete (i.second.ptr); } data.clear(); } #endif
19.195652
87
0.567761
FoFabien
72cfb271bfa82b0d5a733965b933eb1095e70d8b
866
hpp
C++
Enemy.hpp
polinaucc/galaga
6feea0a6a74669c5d3fa6e106653ceacda19b416
[ "MIT" ]
null
null
null
Enemy.hpp
polinaucc/galaga
6feea0a6a74669c5d3fa6e106653ceacda19b416
[ "MIT" ]
null
null
null
Enemy.hpp
polinaucc/galaga
6feea0a6a74669c5d3fa6e106653ceacda19b416
[ "MIT" ]
null
null
null
#pragma once #include "livingobject.hpp" enum class EnemyType { green, purple }; class Enemy : public LivingObject { private: mutable bool m_state; mutable int m_counter; EnemyType m_type; protected: shared_ptr<Sprite> m_sprite_b; public: Enemy(double x, double y, shared_ptr<Sprite> s1, shared_ptr<Sprite> s2, unsigned int lives, EnemyType type): LivingObject(x, y, s1, lives), m_sprite_b(s2), m_state(false), m_counter(0), m_type(type) {} virtual shared_ptr<Sprite> const sprite() const override; virtual void on_tick() override {} virtual EnemyType type() const {return m_type; } static shared_ptr<Enemy> create(double x, double y, EnemyType type); }; class GreenEnemy: public Enemy { public: GreenEnemy(double x, double y); }; class PurpleEnemy: public Enemy { public: PurpleEnemy(double x, double y); };
21.65
112
0.711316
polinaucc
72d87bc37bd77a2ba4912e02cbe84d9249aeecc9
1,387
hpp
C++
tvm_backend/tvm_backend.hpp
elvin-n/dldt_tools
d77b11aafc389f68305b2514db306c3c0b42cddf
[ "MIT" ]
2
2020-06-20T02:54:37.000Z
2020-07-17T04:38:26.000Z
tvm_backend/tvm_backend.hpp
elvin-nnov/dldt_tools
d77b11aafc389f68305b2514db306c3c0b42cddf
[ "MIT" ]
null
null
null
tvm_backend/tvm_backend.hpp
elvin-nnov/dldt_tools
d77b11aafc389f68305b2514db306c3c0b42cddf
[ "MIT" ]
1
2020-02-11T14:21:32.000Z
2020-02-11T14:21:32.000Z
// Copyright 2021 the dldt tools authors. All rights reserved. // Use of this source code is governed by a BSD-style license #include "backend.hpp" #include "tvm/runtime/module.h" extern "C" { Backend* createBackend(); } class TVMBackend : public Backend { public: virtual bool loadModel(const std::string &model, const std::string &device, const std::vector<std::string> &outputs, const std::map<std::string, std::string>& config)override; virtual std::shared_ptr<InferenceMetrics> process(bool streamOutput = false)override { return nullptr; } virtual void report(const InferenceMetrics &im) const override; virtual bool infer()override; virtual void release()override; virtual std::shared_ptr<VBlob> getBlob(const std::string &name)override; virtual VInputInfo getInputDataMap() const override; virtual VOutputInfo getOutputDataMap() const override; protected: tvm::runtime::PackedFunc run_; tvm::runtime::PackedFunc setInput_; tvm::runtime::PackedFunc getInput_; tvm::runtime::PackedFunc getOutput_; tvm::runtime::Module gmod_; DLDevice ctx_; // TODO: which object retain TVM network not to be released? tvm::runtime::Module mod_factory_; tvm::runtime::NDArray x_, y_; std::map<std::string, std::shared_ptr<VBlob> > _blobs; VInputInfo _inputInfo; VOutputInfo _outputInfo; };
30.822222
86
0.719539
elvin-n
72d977939da19ca1218598fd9ee399e38ef04eb7
3,090
hpp
C++
include/operations/CompoundOperation.hpp
TobiasPrie/qfr
843db11651763ac3aecf10c9aa0dffebdd572055
[ "MIT" ]
null
null
null
include/operations/CompoundOperation.hpp
TobiasPrie/qfr
843db11651763ac3aecf10c9aa0dffebdd572055
[ "MIT" ]
1
2021-08-09T18:42:16.000Z
2021-08-09T18:42:16.000Z
include/operations/CompoundOperation.hpp
TobiasPrie/qfr
843db11651763ac3aecf10c9aa0dffebdd572055
[ "MIT" ]
1
2021-08-08T08:55:10.000Z
2021-08-08T08:55:10.000Z
/* * This file is part of IIC-JKU QFR library which is released under the MIT license. * See file README.md or go to http://iic.jku.at/eda/research/quantum/ for more information. */ #ifndef INTERMEDIATEREPRESENTATION_COMPOUNDOPERATION_H #define INTERMEDIATEREPRESENTATION_COMPOUNDOPERATION_H #include "Operation.hpp" namespace qc { class CompoundOperation : public Operation { protected: std::vector<std::shared_ptr<Operation>> ops{ }; public: explicit CompoundOperation(unsigned short nq) { std::strcpy(name, "Compound operation:"); nqubits = nq; } template<class T, class... Args> auto emplace_back(Args&& ... args) { parameter[0]++; return ops.emplace_back(std::make_shared<T>(args ...)); } void setNqubits(unsigned short nq) override { nqubits = nq; for (auto& op:ops) { op->setNqubits(nq); } } dd::Edge getDD(std::unique_ptr<dd::Package>& dd, std::array<short, MAX_QUBITS>& line) const override { dd::Edge e = dd->makeIdent(0, short(nqubits - 1)); for (auto& op: ops) { e = dd->multiply(op->getDD(dd, line), e); } return e; } dd::Edge getInverseDD(std::unique_ptr<dd::Package>& dd, std::array<short, MAX_QUBITS>& line) const override { dd::Edge e = dd->makeIdent(0, short(nqubits - 1)); for (auto& op: ops) { e = dd->multiply(e, op->getInverseDD(dd, line)); } return e; } dd::Edge getDD(std::unique_ptr<dd::Package>& dd, std::array<short, MAX_QUBITS>& line, std::map<unsigned short, unsigned short>& permutation) const override { dd::Edge e = dd->makeIdent(0, short(nqubits - 1)); for (auto& op: ops) { e = dd->multiply(op->getDD(dd, line, permutation), e); } return e; } dd::Edge getInverseDD(std::unique_ptr<dd::Package>& dd, std::array<short, MAX_QUBITS>& line, std::map<unsigned short, unsigned short>& permutation) const override { dd::Edge e = dd->makeIdent(0, short(nqubits - 1)); for (auto& op: ops) { e = dd->multiply(e, op->getInverseDD(dd, line, permutation)); } return e; } std::ostream& print(std::ostream& os) const override { return print(os, standardPermutation); } std::ostream& print(std::ostream& os, const std::map<unsigned short, unsigned short>& permutation) const override { os << name; for (const auto & op : ops) { os << std::endl << "\t\t"; op->print(os, permutation); } return os; } bool actsOn(unsigned short i) override { for (const auto& op: ops) { if(op->actsOn(i)) return true; } return false; } void dumpOpenQASM(std::ofstream& of, const regnames_t& qreg, const regnames_t& creg) const override { for (auto& op: ops) { op->dumpOpenQASM(of, qreg, creg); } } void dumpReal(std::ofstream& of) const override { for (auto& op: ops) { op->dumpReal(of); } } void dumpQiskit(std::ofstream& of, const regnames_t& qreg, const regnames_t& creg, const char *anc_reg_name) const override { for (auto& op: ops) { op->dumpQiskit(of, qreg, creg, anc_reg_name); } } }; } #endif //INTERMEDIATEREPRESENTATION_COMPOUNDOPERATION_H
28.348624
166
0.653398
TobiasPrie
72db52bf57e9bd068259dc6b3f3ab19f284d8d9b
529
cpp
C++
Exam_3/Program4.cpp
othneildrew/CPP-Programming-Practices
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
[ "MIT" ]
1
2020-12-03T15:26:20.000Z
2020-12-03T15:26:20.000Z
Exam_3/Program4.cpp
othneildrew/CPP-Programming-Practices
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
[ "MIT" ]
null
null
null
Exam_3/Program4.cpp
othneildrew/CPP-Programming-Practices
27a20c00b395446a7d2e0dd4b199f4cd9e35591b
[ "MIT" ]
null
null
null
// Exam 3 - Program 4 /*** Write a C++ Program to find the 15 sequences of Fibonacci number. **/ # include <iostream> using namespace std; int main(void) { int Num1 = 0, Num2 = 1, Result = 0, Generation = 15; cout << "\n\t This program finds the fibonacci number after the 15th generation \n"; while (Result <= Generation) { Num1 = Num2; Num2 = Result; Result = Num1 + Num2; } cout << "Fibonacci Number (15th generation) = " << Result << endl; system("pause"); return 0; } // Code written by: Othneil Drew
18.241379
85
0.642722
othneildrew
72dbb6b45ba77fcab92d7e0471026d4f4dea3b6a
880
hpp
C++
ms29/classes/camera.hpp
LeeFoulger/ProxyDll
d8dd9e736055f3263ac8b1671d009c88dc4ecc04
[ "MIT" ]
1
2022-03-15T21:29:19.000Z
2022-03-15T21:29:19.000Z
ms29/classes/camera.hpp
TwisterForPosterity/ProxyDll
d8dd9e736055f3263ac8b1671d009c88dc4ecc04
[ "MIT" ]
null
null
null
ms29/classes/camera.hpp
TwisterForPosterity/ProxyDll
d8dd9e736055f3263ac8b1671d009c88dc4ecc04
[ "MIT" ]
null
null
null
#pragma once #include <Utils.hpp> #include "../memory/local_types.hpp" char __cdecl sub_553660_hook(uint8_t *a1) { auto result = ((char(__cdecl *)(uint8_t *))GetMainModule(0x153660))(a1); auto fov = ((s_camera_definition*)a1)->Print(true, true, true, true)->field_of_view.Get(); auto new_val = fov < 90 ? Utils::Math::Map<float>(fov, 55, 70, 1.15, 1.0) : Utils::Math::Map<float>(fov, 55, 120, 1.15, 0.7); *(float *)0x1913434 = new_val + fov < 90 ? new_val + 0.0f : fov < 110 ? new_val + 0.05f : fov < 110 ? new_val + 0.15f : new_val + 0.20f; return result; } inline void SubmitCameraHooks(const char *name) { if (ConfigManager.GetBool("Hooks", name)) { HookManager.Submit({ 0x0054690A }, &sub_553660_hook, "camera_definition_validate", HookFlags::IsCall); } } inline void SubmitCameraPatches(const char *name) { if (ConfigManager.GetBool("Patches", name)) { } }
29.333333
137
0.681818
LeeFoulger
72e5e1c703489a3be21ed60b0d06e6fac3eda5f6
1,920
cpp
C++
src/clear_benchmark.cpp
jlakness-intel/backend-cpu-helib
ff74311abd749809b732f1f2f63fe78e245c726d
[ "Apache-2.0" ]
1
2022-02-28T17:57:32.000Z
2022-02-28T17:57:32.000Z
src/clear_benchmark.cpp
jlakness-intel/backend-cpu-helib
ff74311abd749809b732f1f2f63fe78e245c726d
[ "Apache-2.0" ]
2
2021-12-06T19:37:42.000Z
2021-12-16T23:37:53.000Z
src/clear_benchmark.cpp
jlakness-intel/backend-cpu-helib
ff74311abd749809b732f1f2f63fe78e245c726d
[ "Apache-2.0" ]
1
2021-11-05T18:01:48.000Z
2021-11-05T18:01:48.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include <algorithm> #include <cstring> #include <memory> #include <vector> #include "../include/clear_benchmark.h" #include "../include/clear_engine.h" #include "../include/clear_error.h" //------------------------ // class ExampleBenchmark //------------------------ ClearTextBenchmark::ClearTextBenchmark(hebench::cpp::BaseEngine &engine, const hebench::APIBridge::BenchmarkDescriptor &bench_desc) : hebench::cpp::BaseBenchmark(engine, bench_desc) { // } ClearTextBenchmark::~ClearTextBenchmark() { // nothing needed in this example } hebench::APIBridge::Handle ClearTextBenchmark::encrypt(hebench::APIBridge::Handle encoded_data) { // we only do plain text in this example, so, just return a copy of our internal data std::shared_ptr<void> p_encoded_data = this->getEngine().template retrieveFromHandle<std::shared_ptr<void>>(encoded_data); // the copy is shallow, but shared_ptr ensures correct destruction using reference counting return this->getEngine().template createHandle<decltype(p_encoded_data)>(encoded_data.size, 0, p_encoded_data); } hebench::APIBridge::Handle ClearTextBenchmark::decrypt(hebench::APIBridge::Handle encrypted_data) { // we only do plain text in this example, so, just return a copy of our internal data std::shared_ptr<void> p_encrypted_data = this->getEngine().template retrieveFromHandle<std::shared_ptr<void>>(encrypted_data); // the copy is shallow, but shared_ptr ensures correct destruction using reference counting return this->getEngine().template createHandle<decltype(p_encrypted_data)>(encrypted_data.size, 0, p_encrypted_data); }
37.647059
102
0.660417
jlakness-intel
72e72d422c2cffcc31d6228dc082f7c7d7bc23bb
3,466
cc
C++
src/cable_plot_options_dialog.cc
Transmission-Line-Software/SpanAnalyzer
37d5f1f849f4c11d83f767b5539845c18ddc371b
[ "Unlicense" ]
4
2017-04-29T19:55:53.000Z
2020-12-20T13:44:03.000Z
src/cable_plot_options_dialog.cc
Transmission-Line-Software/SpanAnalyzer
37d5f1f849f4c11d83f767b5539845c18ddc371b
[ "Unlicense" ]
null
null
null
src/cable_plot_options_dialog.cc
Transmission-Line-Software/SpanAnalyzer
37d5f1f849f4c11d83f767b5539845c18ddc371b
[ "Unlicense" ]
1
2017-12-19T02:13:43.000Z
2017-12-19T02:13:43.000Z
// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "spananalyzer/cable_plot_options_dialog.h" #include "wx/clrpicker.h" #include "wx/spinctrl.h" #include "wx/xrc/xmlres.h" BEGIN_EVENT_TABLE(CablePlotOptionsDialog, wxDialog) EVT_BUTTON(wxID_CANCEL, CablePlotOptionsDialog::OnCancel) EVT_BUTTON(wxID_OK, CablePlotOptionsDialog::OnOk) EVT_CLOSE(CablePlotOptionsDialog::OnClose) END_EVENT_TABLE() CablePlotOptionsDialog::CablePlotOptionsDialog( wxWindow* parent, CablePlotOptions* options) { // loads dialog from virtual xrc file system wxXmlResource::Get()->LoadDialog(this, parent, "cable_plot_options_dialog"); // saves unmodified reference, and copies to modified options_ = options; options_modified_ = CablePlotOptions(*options_); // transfers non-validator data to the window TransferCustomDataToWindow(); // fits the dialog around the sizers this->Fit(); } CablePlotOptionsDialog::~CablePlotOptionsDialog() { } void CablePlotOptionsDialog::OnCancel(wxCommandEvent &event) { EndModal(wxID_CANCEL); } void CablePlotOptionsDialog::OnClose(wxCloseEvent &event) { EndModal(wxID_CLOSE); } void CablePlotOptionsDialog::OnOk(wxCommandEvent &event) { // validates data from form if (this->Validate() == false) { wxMessageBox("Errors on form"); return; } wxBusyCursor cursor; // transfers data from dialog controls TransferCustomDataFromWindow(); // commits changes and exits the dialog *options_ = options_modified_; EndModal(wxID_OK); } void CablePlotOptionsDialog::TransferCustomDataFromWindow() { wxColourPickerCtrl* pickerctrl = nullptr; wxSpinCtrl* spinctrl = nullptr; // transfers color-core pickerctrl = XRCCTRL(*this, "colorpicker_core", wxColourPickerCtrl); options_modified_.color_core = pickerctrl->GetColour(); // transfers color-shell pickerctrl = XRCCTRL(*this, "colorpicker_shell", wxColourPickerCtrl); options_modified_.color_shell = pickerctrl->GetColour(); // transfers color-total pickerctrl = XRCCTRL(*this, "colorpicker_total", wxColourPickerCtrl); options_modified_.color_total = pickerctrl->GetColour(); // transfers color-markers pickerctrl = XRCCTRL(*this, "colorpicker_markers", wxColourPickerCtrl); options_modified_.color_markers = pickerctrl->GetColour(); // transfers thickness-line spinctrl = XRCCTRL(*this, "spinctrl_line_thickness", wxSpinCtrl); options_modified_.thickness_line = spinctrl->GetValue(); } void CablePlotOptionsDialog::TransferCustomDataToWindow() { wxColourPickerCtrl* pickerctrl = nullptr; wxSpinCtrl* spinctrl = nullptr; // transfers color-core pickerctrl = XRCCTRL(*this, "colorpicker_core", wxColourPickerCtrl); pickerctrl->SetColour(options_modified_.color_core); // transfers color-shell pickerctrl = XRCCTRL(*this, "colorpicker_shell", wxColourPickerCtrl); pickerctrl->SetColour(options_modified_.color_shell); // transfers color-total pickerctrl = XRCCTRL(*this, "colorpicker_total", wxColourPickerCtrl); pickerctrl->SetColour(options_modified_.color_total); // transfers color-markers pickerctrl = XRCCTRL(*this, "colorpicker_markers", wxColourPickerCtrl); pickerctrl->SetColour(options_modified_.color_markers); // transfers thickness-line spinctrl = XRCCTRL(*this, "spinctrl_line_thickness", wxSpinCtrl); spinctrl->SetValue(options_modified_.thickness_line); }
31.798165
78
0.772072
Transmission-Line-Software
72e92440229ae9d7e56281842b6e9ffb5197ba45
1,109
cpp
C++
fog/Prim/PrimOstrstream.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
fog/Prim/PrimOstrstream.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
fog/Prim/PrimOstrstream.cpp
UltimateScript/Forgotten
ac59ad21767af9628994c0eecc91e9e0e5680d95
[ "BSD-3-Clause" ]
null
null
null
#include <Prim/PrimIncludeAll.h> PrimOstrstream::PrimOstrstream() : _fixed_buffer(false), _ends(false) {} PrimOstrstream::PrimOstrstream(char *fixedBuffer, int fixedSize, ios_base::openmode aMode) : Super(fixedBuffer, fixedSize, aMode), _fixed_buffer(true), _ends(false) {} PrimOstrstream::~PrimOstrstream() { if (!_fixed_buffer) delete[] Super::str(); } PrimOstrstream& PrimOstrstream::ends() { std::ends(super()); _ends = true; return *this; } const PrimId& PrimOstrstream::id() { if (!_id) _id = PrimIdHandle(str()); return *_id; } const char *PrimOstrstream::str() { if (!_ends) ends(); return Super::str(); } const char *PrimOstrstream::str() const { return ((PrimOstrstream *)this)->str(); } size_t PrimOstrstream::strlen() { return ::strlen(str()); } const PrimString& PrimOstrstream::string() { if (!_string) _string = str(); return *_string; } std::ostream& operator<<(std::ostream& s, PrimOstrstream& anObject) { s << anObject.str(); return s; } std::ostream& operator<<(std::ostream& s, const PrimOstrstream& anObject) { s << anObject.str(); return s; }
15.191781
90
0.681695
UltimateScript
639229c35f0cc8371b20ad7e53135e49c4d6893f
962
hpp
C++
Sources/SolarTears/Rendering/Vulkan/VulkanMemory.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
4
2021-06-30T16:00:20.000Z
2021-10-13T06:17:56.000Z
Sources/SolarTears/Rendering/Vulkan/VulkanMemory.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
Sources/SolarTears/Rendering/Vulkan/VulkanMemory.hpp
Sixshaman/SolarTears
97d07730f876508fce8bf93c9dc90f051c230580
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #include "../../Logging/LoggerQueue.hpp" #include "VulkanDeviceParameters.hpp" #include <span> namespace Vulkan { class MemoryManager { public: enum class BufferAllocationType { DEVICE_LOCAL, HOST_VISIBLE }; MemoryManager(LoggerQueue* logger, VkPhysicalDevice physicalDevice, const DeviceParameters& deviceParameters); ~MemoryManager(); VkDeviceMemory AllocateImagesMemory(VkDevice device, std::span<VkBindImageMemoryInfo> inoutBindMemoryInfos) const; VkDeviceMemory AllocateBuffersMemory(VkDevice device, const std::span<VkBuffer> buffers, BufferAllocationType allocationType, std::vector<VkDeviceSize>& outMemoryOffsets) const; VkDeviceMemory AllocateIntermediateBufferMemory(VkDevice device, VkBuffer buffer) const; private: LoggerQueue* mLogger; VkPhysicalDeviceMemoryProperties mMemoryProperties; VkPhysicalDeviceMemoryBudgetPropertiesEXT mMemoryBudgetProperties; }; }
29.151515
179
0.803534
Sixshaman
6395e57e1c318de9d4b5b5aba029b9c50177356b
3,482
cpp
C++
src/StepLibrary/Leaker.cpp
dale-wilson/HSQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
2
2015-12-29T17:33:25.000Z
2021-12-20T02:30:44.000Z
src/StepLibrary/Leaker.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
src/StepLibrary/Leaker.cpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #include <Steps/StepPch.hpp> #include "Leaker.hpp" #include <Steps/StepFactory.hpp> #include <Steps/SharedResources.hpp> #include <Steps/Configuration.hpp> #include <HighQueue/MemoryPool.hpp> using namespace HighQueue; using namespace Steps; namespace { StepFactory::Registrar<Leaker> registerStep("leaker", "**TESTING**: Discard selected messages. Pass the rest true to the next step."); const std::string keyStart = "offset"; const std::string keyCount = "count"; const std::string keyEvery = "every"; const std::string keyHeartbeats = "heartbeats"; const std::string keyShutdowns = "shutdowns"; } Leaker::Leaker() : count_(0) , every_(0) , offset_(0) , leakHeartbeats_(false) , leakShutdowns_(false) , messageNumber_(0) , published_(0) , leaked_(0) { } std::ostream & Leaker::usage(std::ostream & out) const { out << " " << keyStart << ": How many messages not to leak at beginning." << std::endl; out << " " << keyCount << ": How many consecutive messages to leak." << std::endl; out << " " << keyEvery << ": How often to leak a block of messages" << std::endl; out << " " << keyHeartbeats << ": Can heartbeats leak? (default is false)" << std::endl; out << " " << keyShutdowns << ": Can shutdown requests leak? (default is false)" << std::endl; return Step::usage(out); } bool Leaker::configureParameter(const std::string & key, const ConfigurationNode & configuration) { if(key == keyCount) { uint64_t value; if(configuration.getValue(value)) { count_ = size_t(value); return true; } } else if(key == keyStart) { uint64_t value; if(configuration.getValue(value)) { offset_ = size_t(value); return true; } } else if(key == keyEvery) { uint64_t value; if(configuration.getValue(value)) { every_ = size_t(value); return true; } } else if(key == keyHeartbeats) { if(configuration.getValue(leakHeartbeats_)) { return true; } } else if(key == keyShutdowns) { if(configuration.getValue(leakShutdowns_)) { return true; } } else { return Step::configureParameter(key, configuration); } return false; } void Leaker::validate() { mustHaveDestination(); if(every_ == 0) { std::stringstream msg; msg << "Leaker: \"" << keyEvery << "\" cannot be zero."; throw std::runtime_error(msg.str()); } Step::validate(); } void Leaker::handle(Message & message) { bool leak = true; auto type = message.getType(); if(type == Message::MessageType::Heartbeat) { leak = leakHeartbeats_; } else if(type == Message::MessageType::Shutdown) { leak = leakShutdowns_; } if(leak) { ++messageNumber_; auto p = (messageNumber_ + offset_ ) % every_; if(p >= count_) { send(message); ++published_; } else { ++leaked_; } } } void Leaker::logStats() { LogStatistics("Leaker published: " << published_); LogStatistics("Leaker leaked: " << leaked_); }
24.180556
139
0.571511
dale-wilson
639c035b8fa2958a6d4d18fff0b7366fe04bdabc
21,588
cpp
C++
src/utils/crc.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
149
2017-10-16T03:24:58.000Z
2022-03-25T02:29:13.000Z
src/utils/crc.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
297
2017-10-19T03:23:34.000Z
2022-03-17T08:00:12.000Z
src/utils/crc.cpp
acelyc111/rdsn
298769147750167949af800b96d5b9dcdfab0aeb
[ "MIT" ]
63
2017-10-19T01:55:27.000Z
2022-03-09T11:09:00.000Z
#include <cstdio> #include <dsn/utility/crc.h> namespace dsn { namespace utils { template <typename uintxx_t, uintxx_t uPoly> struct crc_generator { typedef uintxx_t uint; static const uintxx_t MSB = ((uintxx_t)1) << (8 * sizeof(uintxx_t) - 1); static const uintxx_t POLY = uPoly; static uintxx_t _crc_table[256]; static uintxx_t _uX2N[64]; // // compute CRC // static uintxx_t compute(const void *pSrc, size_t uSize, uintxx_t uCrc) { const uint8_t *pData = (const uint8_t *)pSrc; size_t uBytes; uCrc = ~uCrc; while (uSize > 15) { uBytes = 0x80000000u; if (uBytes > uSize) uBytes = uSize; uSize -= uBytes; for (; uBytes > 15; uBytes -= 16, pData += 16) { uCrc = _crc_table[(uint8_t)(uCrc ^ pData[0])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[1])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[2])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[3])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[4])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[5])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[6])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[7])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[8])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[9])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[10])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[11])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[12])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[13])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[14])] ^ (uCrc >> 8); uCrc = _crc_table[(uint8_t)(uCrc ^ pData[15])] ^ (uCrc >> 8); } uSize += uBytes; } for (uBytes = uSize; uBytes > 0; uBytes -= 1, pData += 1) uCrc = _crc_table[(uint8_t)(uCrc ^ pData[0])] ^ (uCrc >> 8); uCrc = ~uCrc; return (uCrc); }; // // Returns (a * b) mod POLY. // "a" and "b" are represented in "reversed" order -- LSB is x**(XX-1) coefficient, MSB is x^0 // coefficient. // "POLY" is represented in the same manner except for omitted x**XX coefficient // static uintxx_t MulPoly(uintxx_t a, uintxx_t b) { uintxx_t r; if (a == 0) return (0); r = 0; do { if (a & MSB) r ^= b; if (b & 1) b = (b >> 1) ^ POLY; else b >>= 1; a <<= 1; } while (a != 0); return (r); }; // // Returns (x ** (8*uSize)) mod POLY // static uintxx_t ComputeX_N(uint64_t uSize) { size_t i; uintxx_t r; r = MSB; // r = 1 for (i = 0; uSize != 0; uSize >>= 1, i += 1) { if (uSize & 1) r = MulPoly(r, _uX2N[i]); } return (r); }; // // Allows to change initial CRC value // static uintxx_t ConvertInitialCrc(uintxx_t uNew, uintxx_t uOld, uintxx_t uCrc, size_t uSize) { // // CRC (A, uSize, uCrc) = (uCrc * x**uSize + A * x**XX) mod POLY (let's forget about double // NOTs of uCrc) // // we know uCrc(uOld) = (uOld * x**uSize + A * x**XX) mod POLY; we need to compute // uCrc(uNew) = (uNew * x**uSize + A * x**XX) mod POLY // // uCrc(uNew) = uCrc(Old) + (uNew - uOld) * x**uSize) // uNew ^= uOld; uOld = ComputeX_N(uSize); uOld = MulPoly(uOld, uNew); uCrc ^= uOld; return (uCrc); }; // // Given // uFinalCrcA = ComputeCrc (A, uSizeA, uInitialCrcA) // and // uFinalCrcB = ComputeCrc (B, uSizeB, uInitialCrcB), // compute CRC of concatenation of A and B // uFinalCrcAB = ComputeCrc (AB, uSizeA + uSizeB, uInitialCrcAB) // without touching A and B // // NB: uSizeA and/or uSizeB may be 0s (this trick may be used to "recompute" CRC for another // initial value) // static uintxx_t concatenate(uintxx_t uInitialCrcAB, uintxx_t uInitialCrcA, uintxx_t uFinalCrcA, uint64_t uSizeA, uintxx_t uInitialCrcB, uintxx_t uFinalCrcB, uint64_t uSizeB) { uintxx_t uX_nA, uX_nB, uFinalCrcAB; // // Crc (X, uSizeX, uInitialCrcX) = ~(((~uInitialCrcX) * x**uSizeX + X * x**XX) mod POLY) // // // first, convert CRC's to canonical values getting rid of double bitwise NOT around uCrc // uInitialCrcAB = ~uInitialCrcAB; uInitialCrcA = ~uInitialCrcA; uFinalCrcA = ~uFinalCrcA; uInitialCrcB = ~uInitialCrcB; uFinalCrcB = ~uFinalCrcB; // // convert uFinalCrcX into canonical form, so that // uFinalCrcX = (X * x**XX) mod POLY // uX_nA = ComputeX_N(uSizeA); uFinalCrcA ^= MulPoly(uX_nA, uInitialCrcA); uX_nB = ComputeX_N(uSizeB); uFinalCrcB ^= MulPoly(uX_nB, uInitialCrcB); // // we know // uFinalCrcA = (A * x**XX) mod POLY // uFinalCrcB = (B * x**XX) mod POLY // and need to compute // uFinalCrcAB = (AB * x**XX) mod POLY = // = ((A * x**uSizeB + B) * x**XX) mod POLY = // = (A * x**XX) * x**uSizeB + B * x**XX mod POLY = // = uFinalCrcB + (uFinalCrcA * x**uSizeB) mod POLY // uFinalCrcAB = uFinalCrcB ^ MulPoly(uFinalCrcA, uX_nB); // // Finally, adjust initial value; we have // uFinalCrcAB = (AB * x**XX) mod POLY // but want to have // uFinalCrcAB = (UInitialCrcAB * x**(uSizeA + uSizeB) + AB * x**XX) mod POLY // uFinalCrcAB ^= MulPoly(uInitialCrcAB, MulPoly(uX_nA, uX_nB)); // convert back to double NOT uFinalCrcAB = ~uFinalCrcAB; return (uFinalCrcAB); }; static void InitializeTables(void) { size_t i, j; uintxx_t k; _uX2N[0] = MSB >> 8; for (i = 1; i < sizeof(_uX2N) / sizeof(_uX2N[0]); ++i) _uX2N[i] = MulPoly(_uX2N[i - 1], _uX2N[i - 1]); for (i = 0; i < 256; ++i) { k = (uintxx_t)i; for (j = 0; j < 8; ++j) { if (k & 1) k = (k >> 1) ^ POLY; else k = (k >> 1); } _crc_table[i] = k; } } static void PrintTables(char *pTypeName, char *pClassName) { size_t i, w; InitializeTables(); printf("%s %s::_uX2N[sizeof (%s::_uX2N) / sizeof (%s::_uX2N[0])] = {", pTypeName, pClassName, pClassName, pClassName); for (i = w = 0; i < sizeof(_uX2N) / sizeof(_uX2N[0]); ++i) { if (i != 0) printf(","); if (w == 0) printf("\n "); printf(" 0x%0*llx", static_cast<int>(sizeof(uintxx_t) * 2), (uint64_t)_uX2N[i]); w = (w + sizeof(uintxx_t)) & 31; } printf("\n};\n\n"); printf("%s %s::_crc_table[sizeof (%s::_crc_table) / sizeof (%s::_crc_table[0])] = {", pTypeName, pClassName, pClassName, pClassName); for (i = w = 0; i < sizeof(_crc_table) / sizeof(_crc_table[0]); ++i) { if (i != 0) printf(","); if (w == 0) printf("\n "); printf(" 0x%0*llx", static_cast<int>(sizeof(uintxx_t) * 2), (uint64_t)_crc_table[i]); w = (w + sizeof(uintxx_t)) & 31; } printf("\n};\n\n"); }; }; #define BIT64(n) (1ull << (63 - (n))) #define crc64_POLY \ (BIT64(63) + BIT64(61) + BIT64(59) + BIT64(58) + BIT64(56) + BIT64(55) + BIT64(52) + \ BIT64(49) + BIT64(48) + BIT64(47) + BIT64(46) + BIT64(44) + BIT64(41) + BIT64(37) + \ BIT64(36) + BIT64(34) + BIT64(32) + BIT64(31) + BIT64(28) + BIT64(26) + BIT64(23) + \ BIT64(22) + BIT64(19) + BIT64(16) + BIT64(13) + BIT64(12) + BIT64(10) + BIT64(9) + BIT64(6) + \ BIT64(4) + BIT64(3) + BIT64(0)) #define BIT32(n) (1u << (31 - (n))) #define crc32_POLY \ (BIT32(28) + BIT32(27) + BIT32(26) + BIT32(25) + BIT32(23) + BIT32(22) + BIT32(20) + \ BIT32(19) + BIT32(18) + BIT32(14) + BIT32(13) + BIT32(11) + BIT32(10) + BIT32(9) + BIT32(8) + \ BIT32(6) + BIT32(0)) typedef crc_generator<uint32_t, crc32_POLY> crc32; typedef crc_generator<uint64_t, crc64_POLY> crc64; template <> uint32_t crc32::_uX2N[sizeof(crc32::_uX2N) / sizeof(crc32::_uX2N[0])] = { 0x00800000, 0x00008000, 0x82f63b78, 0x6ea2d55c, 0x18b8ea18, 0x510ac59a, 0xb82be955, 0xb8fdb1e7, 0x88e56f72, 0x74c360a4, 0xe4172b16, 0x0d65762a, 0x35d73a62, 0x28461564, 0xbf455269, 0xe2ea32dc, 0xfe7740e6, 0xf946610b, 0x3c204f8f, 0x538586e3, 0x59726915, 0x734d5309, 0xbc1ac763, 0x7d0722cc, 0xd289cabe, 0xe94ca9bc, 0x05b74f3f, 0xa51e1f42, 0x40000000, 0x20000000, 0x08000000, 0x00800000, 0x00008000, 0x82f63b78, 0x6ea2d55c, 0x18b8ea18, 0x510ac59a, 0xb82be955, 0xb8fdb1e7, 0x88e56f72, 0x74c360a4, 0xe4172b16, 0x0d65762a, 0x35d73a62, 0x28461564, 0xbf455269, 0xe2ea32dc, 0xfe7740e6, 0xf946610b, 0x3c204f8f, 0x538586e3, 0x59726915, 0x734d5309, 0xbc1ac763, 0x7d0722cc, 0xd289cabe, 0xe94ca9bc, 0x05b74f3f, 0xa51e1f42, 0x40000000, 0x20000000, 0x08000000, 0x00800000, 0x00008000}; template <> uint32_t crc32::_crc_table[sizeof(crc32::_crc_table) / sizeof(crc32::_crc_table[0])] = { 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351}; template <> uint64_t crc64::_uX2N[sizeof(crc64::_uX2N) / sizeof(crc64::_uX2N[0])] = { 0x0080000000000000, 0x0000800000000000, 0x0000000080000000, 0x9a6c9329ac4bc9b5, 0x10f4bb0f129310d6, 0x70f05dcea2ebd226, 0x311211205672822d, 0x2fc297db0f46c96e, 0xca4d536fabf7da84, 0xfb4cdc3b379ee6ed, 0xea261148df25140a, 0x59ccb2c07aa6c9b4, 0x20b3674a839af27a, 0x2d8e1986da94d583, 0x42cdf4c20337635d, 0x1d78724bf0f26839, 0xb96c84e0afb34bd5, 0x5d2e1fcd2df0a3ea, 0xcd9506572332be42, 0x23bda2427f7d690f, 0x347a953232374f07, 0x1c2a807ac2a8ceea, 0x9b92ad0e14fe1460, 0x2574114889f670b2, 0x4a84a6c45e3bf520, 0x915bbac21cd1c7ff, 0xb0290ec579f291f5, 0xcf2548505c624e6e, 0xb154f27bf08a8207, 0xce4e92344baf7d35, 0x51da8d7e057c5eb3, 0x9fb10823f5be15df, 0x73b825b3ff1f71cf, 0x5db436c5406ebb74, 0xfa7ed8f3ec3f2bca, 0xc4d58efdc61b9ef6, 0xa7e39e61e855bd45, 0x97ad46f9dd1bf2f1, 0x1a0abb01f853ee6b, 0x3f0827c3348f8215, 0x4eb68c4506134607, 0x4a46f6de5df34e0a, 0x2d855d6a1c57a8dd, 0x8688da58e1115812, 0x5232f417fc7c7300, 0xa4080fb2e767d8da, 0xd515a7e17693e562, 0x1181f7c862e94226, 0x9e23cd058204ca91, 0x9b8992c57a0aed82, 0xb2c0afb84609b6ff, 0x2f7160553a5ea018, 0x3cd378b5c99f2722, 0x814054ad61a3b058, 0xbf766189fce806d8, 0x85a5e898ac49f86f, 0x34830d11bc84f346, 0x9644d95b173c8c1c, 0x150401ac9ac759b1, 0xebe1f7f46fb00eba, 0x8ee4ce0c2e2bd662, 0x4000000000000000, 0x2000000000000000, 0x0800000000000000}; template <> uint64_t crc64::_crc_table[sizeof(crc64::_crc_table) / sizeof(crc64::_crc_table[0])] = { 0x0000000000000000, 0x7f6ef0c830358979, 0xfedde190606b12f2, 0x81b31158505e9b8b, 0xc962e5739841b68f, 0xb60c15bba8743ff6, 0x37bf04e3f82aa47d, 0x48d1f42bc81f2d04, 0xa61cecb46814fe75, 0xd9721c7c5821770c, 0x58c10d24087fec87, 0x27affdec384a65fe, 0x6f7e09c7f05548fa, 0x1010f90fc060c183, 0x91a3e857903e5a08, 0xeecd189fa00bd371, 0x78e0ff3b88be6f81, 0x078e0ff3b88be6f8, 0x863d1eabe8d57d73, 0xf953ee63d8e0f40a, 0xb1821a4810ffd90e, 0xceecea8020ca5077, 0x4f5ffbd87094cbfc, 0x30310b1040a14285, 0xdefc138fe0aa91f4, 0xa192e347d09f188d, 0x2021f21f80c18306, 0x5f4f02d7b0f40a7f, 0x179ef6fc78eb277b, 0x68f0063448deae02, 0xe943176c18803589, 0x962de7a428b5bcf0, 0xf1c1fe77117cdf02, 0x8eaf0ebf2149567b, 0x0f1c1fe77117cdf0, 0x7072ef2f41224489, 0x38a31b04893d698d, 0x47cdebccb908e0f4, 0xc67efa94e9567b7f, 0xb9100a5cd963f206, 0x57dd12c379682177, 0x28b3e20b495da80e, 0xa900f35319033385, 0xd66e039b2936bafc, 0x9ebff7b0e12997f8, 0xe1d10778d11c1e81, 0x606216208142850a, 0x1f0ce6e8b1770c73, 0x8921014c99c2b083, 0xf64ff184a9f739fa, 0x77fce0dcf9a9a271, 0x08921014c99c2b08, 0x4043e43f0183060c, 0x3f2d14f731b68f75, 0xbe9e05af61e814fe, 0xc1f0f56751dd9d87, 0x2f3dedf8f1d64ef6, 0x50531d30c1e3c78f, 0xd1e00c6891bd5c04, 0xae8efca0a188d57d, 0xe65f088b6997f879, 0x9931f84359a27100, 0x1882e91b09fcea8b, 0x67ec19d339c963f2, 0xd75adabd7a6e2d6f, 0xa8342a754a5ba416, 0x29873b2d1a053f9d, 0x56e9cbe52a30b6e4, 0x1e383fcee22f9be0, 0x6156cf06d21a1299, 0xe0e5de5e82448912, 0x9f8b2e96b271006b, 0x71463609127ad31a, 0x0e28c6c1224f5a63, 0x8f9bd7997211c1e8, 0xf0f5275142244891, 0xb824d37a8a3b6595, 0xc74a23b2ba0eecec, 0x46f932eaea507767, 0x3997c222da65fe1e, 0xafba2586f2d042ee, 0xd0d4d54ec2e5cb97, 0x5167c41692bb501c, 0x2e0934dea28ed965, 0x66d8c0f56a91f461, 0x19b6303d5aa47d18, 0x980521650afae693, 0xe76bd1ad3acf6fea, 0x09a6c9329ac4bc9b, 0x76c839faaaf135e2, 0xf77b28a2faafae69, 0x8815d86aca9a2710, 0xc0c42c4102850a14, 0xbfaadc8932b0836d, 0x3e19cdd162ee18e6, 0x41773d1952db919f, 0x269b24ca6b12f26d, 0x59f5d4025b277b14, 0xd846c55a0b79e09f, 0xa72835923b4c69e6, 0xeff9c1b9f35344e2, 0x90973171c366cd9b, 0x1124202993385610, 0x6e4ad0e1a30ddf69, 0x8087c87e03060c18, 0xffe938b633338561, 0x7e5a29ee636d1eea, 0x0134d92653589793, 0x49e52d0d9b47ba97, 0x368bddc5ab7233ee, 0xb738cc9dfb2ca865, 0xc8563c55cb19211c, 0x5e7bdbf1e3ac9dec, 0x21152b39d3991495, 0xa0a63a6183c78f1e, 0xdfc8caa9b3f20667, 0x97193e827bed2b63, 0xe877ce4a4bd8a21a, 0x69c4df121b863991, 0x16aa2fda2bb3b0e8, 0xf86737458bb86399, 0x8709c78dbb8deae0, 0x06bad6d5ebd3716b, 0x79d4261ddbe6f812, 0x3105d23613f9d516, 0x4e6b22fe23cc5c6f, 0xcfd833a67392c7e4, 0xb0b6c36e43a74e9d, 0x9a6c9329ac4bc9b5, 0xe50263e19c7e40cc, 0x64b172b9cc20db47, 0x1bdf8271fc15523e, 0x530e765a340a7f3a, 0x2c608692043ff643, 0xadd397ca54616dc8, 0xd2bd67026454e4b1, 0x3c707f9dc45f37c0, 0x431e8f55f46abeb9, 0xc2ad9e0da4342532, 0xbdc36ec59401ac4b, 0xf5129aee5c1e814f, 0x8a7c6a266c2b0836, 0x0bcf7b7e3c7593bd, 0x74a18bb60c401ac4, 0xe28c6c1224f5a634, 0x9de29cda14c02f4d, 0x1c518d82449eb4c6, 0x633f7d4a74ab3dbf, 0x2bee8961bcb410bb, 0x548079a98c8199c2, 0xd53368f1dcdf0249, 0xaa5d9839ecea8b30, 0x449080a64ce15841, 0x3bfe706e7cd4d138, 0xba4d61362c8a4ab3, 0xc52391fe1cbfc3ca, 0x8df265d5d4a0eece, 0xf29c951de49567b7, 0x732f8445b4cbfc3c, 0x0c41748d84fe7545, 0x6bad6d5ebd3716b7, 0x14c39d968d029fce, 0x95708ccedd5c0445, 0xea1e7c06ed698d3c, 0xa2cf882d2576a038, 0xdda178e515432941, 0x5c1269bd451db2ca, 0x237c997575283bb3, 0xcdb181ead523e8c2, 0xb2df7122e51661bb, 0x336c607ab548fa30, 0x4c0290b2857d7349, 0x04d364994d625e4d, 0x7bbd94517d57d734, 0xfa0e85092d094cbf, 0x856075c11d3cc5c6, 0x134d926535897936, 0x6c2362ad05bcf04f, 0xed9073f555e26bc4, 0x92fe833d65d7e2bd, 0xda2f7716adc8cfb9, 0xa54187de9dfd46c0, 0x24f29686cda3dd4b, 0x5b9c664efd965432, 0xb5517ed15d9d8743, 0xca3f8e196da80e3a, 0x4b8c9f413df695b1, 0x34e26f890dc31cc8, 0x7c339ba2c5dc31cc, 0x035d6b6af5e9b8b5, 0x82ee7a32a5b7233e, 0xfd808afa9582aa47, 0x4d364994d625e4da, 0x3258b95ce6106da3, 0xb3eba804b64ef628, 0xcc8558cc867b7f51, 0x8454ace74e645255, 0xfb3a5c2f7e51db2c, 0x7a894d772e0f40a7, 0x05e7bdbf1e3ac9de, 0xeb2aa520be311aaf, 0x944455e88e0493d6, 0x15f744b0de5a085d, 0x6a99b478ee6f8124, 0x224840532670ac20, 0x5d26b09b16452559, 0xdc95a1c3461bbed2, 0xa3fb510b762e37ab, 0x35d6b6af5e9b8b5b, 0x4ab846676eae0222, 0xcb0b573f3ef099a9, 0xb465a7f70ec510d0, 0xfcb453dcc6da3dd4, 0x83daa314f6efb4ad, 0x0269b24ca6b12f26, 0x7d0742849684a65f, 0x93ca5a1b368f752e, 0xeca4aad306bafc57, 0x6d17bb8b56e467dc, 0x12794b4366d1eea5, 0x5aa8bf68aecec3a1, 0x25c64fa09efb4ad8, 0xa4755ef8cea5d153, 0xdb1bae30fe90582a, 0xbcf7b7e3c7593bd8, 0xc399472bf76cb2a1, 0x422a5673a732292a, 0x3d44a6bb9707a053, 0x759552905f188d57, 0x0afba2586f2d042e, 0x8b48b3003f739fa5, 0xf42643c80f4616dc, 0x1aeb5b57af4dc5ad, 0x6585ab9f9f784cd4, 0xe436bac7cf26d75f, 0x9b584a0fff135e26, 0xd389be24370c7322, 0xace74eec0739fa5b, 0x2d545fb4576761d0, 0x523aaf7c6752e8a9, 0xc41748d84fe75459, 0xbb79b8107fd2dd20, 0x3acaa9482f8c46ab, 0x45a459801fb9cfd2, 0x0d75adabd7a6e2d6, 0x721b5d63e7936baf, 0xf3a84c3bb7cdf024, 0x8cc6bcf387f8795d, 0x620ba46c27f3aa2c, 0x1d6554a417c62355, 0x9cd645fc4798b8de, 0xe3b8b53477ad31a7, 0xab69411fbfb21ca3, 0xd407b1d78f8795da, 0x55b4a08fdfd90e51, 0x2ada5047efec8728}; #undef crc32_POLY #undef crc64_POLY #undef BIT64 #undef BIT32 } } namespace dsn { namespace utils { uint32_t crc32_calc(const void *ptr, size_t size, uint32_t init_crc) { return dsn::utils::crc32::compute(ptr, size, init_crc); } uint32_t crc32_concat(uint32_t xy_init, uint32_t x_init, uint32_t x_final, size_t x_size, uint32_t y_init, uint32_t y_final, size_t y_size) { return dsn::utils::crc32::concatenate( 0, x_init, x_final, (uint64_t)x_size, y_init, y_final, (uint64_t)y_size); } uint64_t crc64_calc(const void *ptr, size_t size, uint64_t init_crc) { return dsn::utils::crc64::compute(ptr, size, init_crc); } uint64_t crc64_concat(uint32_t xy_init, uint64_t x_init, uint64_t x_final, size_t x_size, uint64_t y_init, uint64_t y_final, size_t y_size) { return ::dsn::utils::crc64::concatenate( 0, x_init, x_final, (uint64_t)x_size, y_init, y_final, (uint64_t)y_size); } } }
47.342105
100
0.659765
acelyc111
639ee49b13bd12ebaa335be234d65a7351ce96c6
5,965
cpp
C++
engine/screens/source/SkillsScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/screens/source/SkillsScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/screens/source/SkillsScreen.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "Conversion.hpp" #include "Game.hpp" #include "SkillsScreen.hpp" #include "OptionsComponent.hpp" #include "Prompt.hpp" #include "Setting.hpp" #include "TextComponent.hpp" #include "PromptTextKeys.hpp" #include "SkillTextKeys.hpp" using namespace std; SkillsScreen::SkillsScreen(DisplayPtr new_display, CreaturePtr new_creature, const SkillCategory sc, const SkillsSelectionType s_type) : Screen(new_display) , creature(new_creature) , category(sc) , sst(s_type) , skills_for_category({{SkillCategory::SKILL_CATEGORY_GENERAL, {SkillType::SKILL_GENERAL_ARCHERY, SkillType::SKILL_GENERAL_WEAVING}}, {SkillCategory::SKILL_CATEGORY_MELEE, {SkillType::SKILL_MELEE_AXES, SkillType::SKILL_MELEE_EXOTIC}}, {SkillCategory::SKILL_CATEGORY_RANGED, {SkillType::SKILL_RANGED_AXES, SkillType::SKILL_RANGED_EXOTIC}}, {SkillCategory::SKILL_CATEGORY_MAGIC, {SkillType::SKILL_MAGIC_ARCANE, SkillType::SKILL_MAGIC_CANTRIPS}}}) { initialize(); } void SkillsScreen::initialize() { screen_titles = { {SkillCategory::SKILL_CATEGORY_GENERAL, {make_pair(SkillsSelectionType::SKILLS_SELECTION_SELECT_SKILL, SkillTextKeys::SKILLS_GENERAL), make_pair(SkillsSelectionType::SKILLS_SELECTION_IMPROVE_SKILL, SkillTextKeys::SKILLS_IMPROVE_GENERAL)}}, {SkillCategory::SKILL_CATEGORY_MELEE, {make_pair(SkillsSelectionType::SKILLS_SELECTION_SELECT_SKILL, SkillTextKeys::SKILLS_WEAPON), make_pair(SkillsSelectionType::SKILLS_SELECTION_IMPROVE_SKILL, SkillTextKeys::SKILLS_IMPROVE_WEAPON)}}, {SkillCategory::SKILL_CATEGORY_RANGED, {make_pair(SkillsSelectionType::SKILLS_SELECTION_SELECT_SKILL, SkillTextKeys::SKILLS_RANGED_WEAPON), make_pair(SkillsSelectionType::SKILLS_SELECTION_IMPROVE_SKILL, SkillTextKeys::SKILLS_IMPROVE_RANGED_WEAPON)}}, {SkillCategory::SKILL_CATEGORY_MAGIC, {make_pair(SkillsSelectionType::SKILLS_SELECTION_SELECT_SKILL, SkillTextKeys::SKILLS_MAGIC), make_pair(SkillsSelectionType::SKILLS_SELECTION_IMPROVE_SKILL, SkillTextKeys::SKILLS_IMPROVE_MAGIC)}}}; vector<ScreenComponentPtr> sk_screen; auto s_it = screen_titles.find(category); if (s_it != screen_titles.end()) { title_text_sid = s_it->second[sst]; if (sst == SkillsSelectionType::SKILLS_SELECTION_IMPROVE_SKILL && creature != nullptr) { int skill_pts_remaining = creature->get_skill_points(); title_text_sid = SkillTextKeys::get_skill_improvement_message(title_text_sid, skill_pts_remaining); } } auto sty_it = skills_for_category.find(category); SkillType min = SkillType::SKILL_GENERAL_ARCHERY; SkillType max = SkillType::SKILL_GENERAL_WEAVING; std::map<char, SkillType> selection_map; bool selection_require_uppercase = Game::instance().get_settings_ref().get_setting_as_bool(Setting::SKILL_SELECTION_REQUIRE_CAPITALIZATION); if (sty_it != skills_for_category.end()) { pair<SkillType, SkillType> min_max = sty_it->second; min = min_max.first; max = min_max.second; } int cnt = 0; int current_id = 0; if (creature != nullptr) { for (int i = static_cast<int>(min); i <= static_cast<int>(max); i++) { OptionsComponentPtr options = std::make_shared<OptionsComponent>(); Option current_option; TextComponentPtr option_text_component = current_option.get_description(); SkillType st = static_cast<SkillType>(i); Skill* skill = creature->get_skills().get_skill(st); if (skill != nullptr && (skill->get_value() > 0 || skill->can_train_from_unlearned())) { string skill_desc = StringTable::get(skill->get_skill_name_sid()); ostringstream ss; ss << skill_desc << " (" << skill->get_value() << ")"; option_text_component->add_text(ss.str()); options->add_option_description(""); cnt++; if (can_add_component(cnt) == false) { current_id = 0; cnt = 1; screen_selection_to_skill_map.push_back(selection_map); selection_map.clear(); add_page(sk_screen); sk_screen.clear(); } // Set the ID after we've done a check on whether or not we can // add the component so that if a new page was added, and the // current id updated, we aren't setting the old value. current_option.set_id(current_id); current_option.set_external_id(to_string(i)); current_option.set_uppercase(selection_require_uppercase); options->add_option(current_option); add_options_component(sk_screen, options, cnt, current_id); // Add to the selection map after the option component has been added // so that if we've started a new page, the skill is added to the // correct place. // // Do both uppercase and lowercase. if (selection_require_uppercase) { selection_map['A' + current_id] = st; } else { selection_map['a' + current_id] = st; } current_id++; } } } screen_selection_to_skill_map.push_back(selection_map); add_page(sk_screen); // Set the prompt PromptPtr inv_prompt = std::make_unique<Prompt>(PromptLocation::PROMPT_LOCATION_LOWER_RIGHT); // Accept any input to the inventory manager will take care of sorting out // what's a valid command and what is not. inv_prompt->set_accept_any_input(true); inv_prompt->set_text_sid(PromptTextKeys::PROMPT_SKILLS); user_prompt = std::move(inv_prompt); line_increment = 1; } SkillType SkillsScreen::get_selected_skill(const char selection) const { SkillType st = SkillType::SKILL_UNDEFINED; const auto& selection_map = screen_selection_to_skill_map.at(get_cur_page_idx()); map<char, SkillType>::const_iterator selection_map_it = selection_map.find(selection); if (selection_map_it != selection_map.end()) { st = selection_map_it->second; } return st; }
38.733766
271
0.713495
prolog
63aa836274d91d000c85c4ee6c9a7173b7110b00
1,832
cpp
C++
src/gameworld/gameworld/effect/skilleffect/effecthurtinc.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/effect/skilleffect/effecthurtinc.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/effect/skilleffect/effecthurtinc.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "effecthurtinc.hpp" EffectIncHurt::EffectIncHurt() : m_effect_time(0), m_inc_percent_to_role(0), m_inc_percent_to_monster(0) { } EffectIncHurt::EffectIncHurt(ObjID deliverer, UInt16 skill, int effect_time, char product_level, char product_method) : EffectBase(deliverer, skill, product_method, product_level), m_effect_time(effect_time), m_inc_percent_to_role(0), m_inc_percent_to_monster(0) { m_merge_rule = EffectBase::MERGE_RULE_NOMERGE_2; } EffectIncHurt::~EffectIncHurt() { } bool EffectIncHurt::Update(unsigned long interval, Character *cha, bool *die) { m_effect_time -= (int)interval; return m_effect_time > 0; } void EffectIncHurt::SetIncPercent(int percent) { if (percent > 0) { m_inc_percent_to_role = percent; m_inc_percent_to_monster = percent; } } void EffectIncHurt::SetIncPercent(int percent_to_role, int percent_to_monster) { if (percent_to_role > 0) { m_inc_percent_to_role = percent_to_role; m_inc_percent_to_monster = percent_to_monster; } } int EffectIncHurt::GetIncPercent(Character *target) { if (NULL != target && Obj::OBJ_TYPE_MONSTER == target->GetObjType()) { return m_inc_percent_to_monster; } else { return m_inc_percent_to_role; } } void EffectIncHurt::GetEffectParam(short *count, long long param[EFFECT_INFO_PARAM_MAX]) { UNSTD_STATIC_CHECK(EFFECT_INFO_PARAM_MAX >= 3); param[0] = m_effect_time; param[1] = m_inc_percent_to_role; param[2] = m_inc_percent_to_monster; *count = 3; } bool EffectIncHurt::Serialize(TLVSerializer &s) const { return SerializeBase(s) && s.Push(m_effect_time) && s.Push(m_inc_percent_to_role) && s.Push(m_inc_percent_to_monster); } bool EffectIncHurt::Unserialize(TLVUnserializer &s) { return UnserializeBase(s) && s.Pop(&m_effect_time) && s.Pop(&m_inc_percent_to_role) && s.Pop(&m_inc_percent_to_monster); }
23.487179
121
0.76583
mage-game
63b5456b7e18ed31a2746f75fc4a5591ee10080f
1,833
cpp
C++
MSCL/source/mscl/MicroStrain/MIP/Commands/GetDeviceInfo.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
53
2015-08-28T02:41:41.000Z
2022-03-03T07:50:53.000Z
MSCL/source/mscl/MicroStrain/MIP/Commands/GetDeviceInfo.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
209
2015-09-30T19:36:11.000Z
2022-03-04T21:52:20.000Z
MSCL/source/mscl/MicroStrain/MIP/Commands/GetDeviceInfo.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
55
2015-09-03T14:40:01.000Z
2022-02-04T02:02:01.000Z
/******************************************************************************* Copyright(c) 2015-2021 Parker Hannifin Corp. All rights reserved. MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License. *******************************************************************************/ #include "stdafx.h" #include "GetDeviceInfo.h" #include "MIP_Commands.h" #include "mscl/Utils.h" #include "mscl/MicroStrain/MIP/MipDataField.h" #include "mscl/MicroStrain/MIP/Packets/MipPacketBuilder.h" namespace mscl { ByteStream GetDeviceInfo::buildCommand() { static const uint8 DESC_SET = 0x01; static const uint8 FIELD_DESC = 0x03; //create the field to add to the packet MipDataField field(Utils::make_uint16(DESC_SET, FIELD_DESC)); //create a packet builder with with field MipPacketBuilder builder(DESC_SET, field); //build the packet and return the ByteStream result return builder.buildPacket(); } GetDeviceInfo::Response::Response(std::weak_ptr<ResponseCollector> collector): GenericMipCommand::Response(MipTypes::CMD_GET_DEVICE_INFO, collector, true, true, "Get Device Info") { } bool GetDeviceInfo::Response::match_data(const MipDataField& field) { static const uint8 FIELD_DATA_LEN = 82; //verify the field data size is correct if(field.fieldData().size() != FIELD_DATA_LEN) { return false; } //call match from the super class as well return GenericMipCommand::Response::match_data(field); } MipDeviceInfo GetDeviceInfo::Response::parseResponse(const GenericMipCmdResponse& response) const { MipDeviceInfo result; MIP_Commands::parseData_GetDeviceInfo(response, result); return result; } }
32.732143
108
0.629023
offworld-projects
63c0be814da62e4c04ee99599a46e5f60cac9ce2
1,701
hpp
C++
src/cpp-utility/perf/PerfCounter.hpp
toschmidt/cpp-utility
d58f3a0af32700b742a96143dfee97144dc7c8ce
[ "MIT" ]
1
2021-03-26T19:08:59.000Z
2021-03-26T19:08:59.000Z
src/cpp-utility/perf/PerfCounter.hpp
toschmidt/cpp-utility
d58f3a0af32700b742a96143dfee97144dc7c8ce
[ "MIT" ]
null
null
null
src/cpp-utility/perf/PerfCounter.hpp
toschmidt/cpp-utility
d58f3a0af32700b742a96143dfee97144dc7c8ce
[ "MIT" ]
null
null
null
#pragma once #include <cpp-utility/compiler/CompilerHints.hpp> #include <cstring> #include <linux/perf_event.h> #include <sys/ioctl.h> #include <syscall.h> #include <unistd.h> namespace utility::perf { using PerfConfig = std::pair<uint64_t, uint64_t>; class PerfCounter { private: struct alignas(32) read_format { uint64_t value{}; uint64_t time_enabled{}; uint64_t time_running{}; }; perf_event_attr pe{}; int fd; read_format prev; read_format data; public: explicit PerfCounter(PerfConfig config) : fd(0) { memset(&pe, 0, sizeof(perf_event_attr)); pe.type = config.first; pe.size = sizeof(perf_event_attr); pe.config = config.second; pe.disabled = true; pe.inherit = 1; pe.inherit_stat = 0; pe.exclude_kernel = false; pe.exclude_hv = false; pe.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; fd = syscall(__NR_perf_event_open, &pe, 0, -1, -1, 0); // NOLINT } forceinline void start() { ioctl(fd, PERF_EVENT_IOC_RESET, 0); ioctl(fd, PERF_EVENT_IOC_ENABLE, 0); read(fd, &prev, sizeof(uint64_t) * 3); } forceinline void stop() { read(fd, &data, sizeof(uint64_t) * 3); ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); } forceinline double get() const { return static_cast<double>(data.value - prev.value) * (static_cast<double>(data.time_enabled - prev.time_enabled) / static_cast<double>(data.time_running - prev.time_running)); } }; } // namespace utility::perf
27.435484
90
0.607878
toschmidt
63c644f7528d19adcb36891b9e9eb0be17cf9726
806
cpp
C++
tests/omphost/host_bug_libomp.cpp
ye-luo/openmp-target
f042e9d255b521e07ca32fe08799e736d4b1c70c
[ "BSD-3-Clause" ]
5
2020-02-14T03:32:58.000Z
2021-06-21T18:13:02.000Z
tests/omphost/host_bug_libomp.cpp
ye-luo/openmp-target
f042e9d255b521e07ca32fe08799e736d4b1c70c
[ "BSD-3-Clause" ]
1
2020-02-24T01:48:06.000Z
2020-02-24T01:48:57.000Z
tests/omphost/host_bug_libomp.cpp
ye-luo/openmp-target
f042e9d255b521e07ca32fe08799e736d4b1c70c
[ "BSD-3-Clause" ]
4
2020-05-20T16:04:10.000Z
2021-06-22T20:06:39.000Z
#include <iostream> #ifdef _OPENMP #include <omp.h> #else int omp_get_thread_num() { return 1; } #endif int main() { const int size = 4; int wrong_counts = 0; #pragma omp parallel reduction(+:wrong_counts) { int A[size]; for(int i = 0; i < size; i++) A[i] = 0; #pragma omp target teams distribute map(tofrom: A[:size]) for(int i = 0; i < size; i++) { A[i] = i; } #pragma omp critical { std::cout << "tid = " << omp_get_thread_num() << std::endl; for(int i = 0; i < size; i++) { if (A[i] != i) wrong_counts++; std::cout << " " << A[i]; } std::cout << std::endl; } } if (wrong_counts) std::cout << "Wrong!" << std::endl; else std::cout << "Right!" << std::endl; return wrong_counts; }
19.190476
65
0.514888
ye-luo
63c7133a66a1680e54953472443ad5aebcc1a164
3,784
cpp
C++
test/function/scalar/cospi.cpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
test/function/scalar/cospi.cpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
test/function/scalar/cospi.cpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! Copyright 2015 NumScale SAS Copyright 2015 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #include <boost/simd/function/scalar/cospi.hpp> #include <boost/simd/function/fast.hpp> #include <simd_test.hpp> #include <boost/simd/constant/inf.hpp> #include <boost/simd/constant/minf.hpp> #include <boost/simd/constant/nan.hpp> #include <boost/simd/constant/one.hpp> #include <boost/simd/constant/mone.hpp> #include <boost/simd/constant/zero.hpp> #include <boost/simd/constant/mzero.hpp> #include <boost/simd/constant/quarter.hpp> #include <boost/simd/constant/sqrt_2.hpp> #include <boost/simd/constant/sqrt_2o_2.hpp> #include <boost/dispatch/meta/as_floating.hpp> STF_CASE_TPL (" cospi", STF_IEEE_TYPES) { namespace bs = boost::simd; namespace bd = boost::dispatch; using bs::cospi; using r_t = decltype(cospi(T())); // return type conformity test STF_TYPE_IS(r_t, T); // specific values tests #ifndef BOOST_SIMD_NO_INVALIDS STF_ULP_EQUAL(cospi(bs::Inf<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Minf<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Nan<T>()), bs::Nan<r_t>(), 0.5); #endif STF_ULP_EQUAL(cospi(-bs::Quarter<T>()), bs::Sqrt_2o_2<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Half<T>()), bs::Zero<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Mhalf<T>()), bs::Zero<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::One<T>()), bs::Mone<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Quarter<T>()), bs::Sqrt_2o_2<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Zero<T>()), bs::One<r_t>(), 0.5); } STF_CASE_TPL (" cospi fast", STF_IEEE_TYPES) { namespace bs = boost::simd; namespace bd = boost::dispatch; using bs::cospi; using r_t = decltype(cospi(T())); // return type conformity test STF_TYPE_IS(r_t, T); // specific values tests #ifndef BOOST_SIMD_NO_INVALIDS STF_ULP_EQUAL(bs::fast_(cospi)(bs::Inf<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Minf<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Nan<T>()), bs::Nan<r_t>(), 0.5); #endif STF_ULP_EQUAL(bs::fast_(cospi)(-bs::Quarter<T>()), bs::Sqrt_2o_2<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Half<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Mhalf<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::One<T>()), bs::Nan<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Quarter<T>()), bs::Sqrt_2o_2<r_t>(), 0.5); STF_ULP_EQUAL(bs::fast_(cospi)(bs::Zero<T>()), bs::One<r_t>(), 0.5); } STF_CASE_TPL (" cospi unsigned", STF_UNSIGNED_INTEGRAL_TYPES) { namespace bs = boost::simd; namespace bd = boost::dispatch; using bs::cospi; using r_t = decltype(cospi(T())); using result_t = bd::as_floating_t<T>; // return type conformity test STF_TYPE_IS(r_t, result_t); // specific values tests STF_ULP_EQUAL(cospi(bs::One<T>()), bs::Mone<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Zero<T>()), bs::One<r_t>(), 0.5); } // end of test for unsigned_int_ STF_CASE_TPL (" cospi signed", STF_SIGNED_INTEGRAL_TYPES) { namespace bs = boost::simd; namespace bd = boost::dispatch; using bs::cospi; using r_t = decltype(cospi(T())); using result_t = bd::as_floating_t<T>; // return type conformity test STF_TYPE_IS(r_t, result_t); // specific values tests STF_ULP_EQUAL(cospi(bs::Mone<T>()), bs::Mone<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::One<T>()), bs::Mone<r_t>(), 0.5); STF_ULP_EQUAL(cospi(bs::Zero<T>()), bs::One<r_t>(), 0.5); } // end of test for signed_int_
34.4
100
0.634514
yaeldarmon
63ca894c603dba0988865d3e5c7111faa95a5008
2,287
cpp
C++
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
445
2015-01-04T16:30:56.000Z
2022-03-30T02:27:05.000Z
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
305
2015-01-04T09:20:03.000Z
2020-10-01T08:45:45.000Z
edbee-lib/edbee/commands/cutcommand.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
49
2015-02-14T01:43:38.000Z
2022-02-15T17:03:55.000Z
/** * Copyright 2011-2012 - Reliable Bits Software by Blommers IT. All Rights Reserved. * Author Rick Blommers */ #include "cutcommand.h" #include <QApplication> #include <QClipboard> #include <QMimeData> #include "edbee/commands/copycommand.h" #include "edbee/models/textdocument.h" #include "edbee/models/change.h" #include "edbee/models/textrange.h" #include "edbee/models/textundostack.h" #include "edbee/texteditorcontroller.h" #include "edbee/views/textselection.h" #include "edbee/debug.h" namespace edbee { /// Performs the cut command /// @param controller the controller context void CutCommand::execute(TextEditorController* controller) { QClipboard *clipboard = QApplication::clipboard(); TextRangeSet* sel = controller->textSelection(); // get the selected text QString str = sel->getSelectedText(); if( !str.isEmpty() ) { clipboard->setText( str ); controller->replaceSelection( "", 0); return; // perform a full-lines cut } else { // fetch the selected lines TextRangeSet newSel( *sel ); newSel.expandToFullLines(1); str = newSel.getSelectedText(); // we only coalesce if 1 range is available int coalesceId = ( sel->rangeCount() != 1) ? 0 : CoalesceId_CutLine; // when the previous command was a cut // and there's a line on the stack, we need to expand the line if( controller->textDocument()->textUndoStack()->lastCoalesceIdAtCurrentLevel() == CoalesceId_CutLine ) { QClipboard* clipboard = QApplication::clipboard(); const QMimeData* mimeData = clipboard->mimeData(); if( mimeData->hasFormat( CopyCommand::EDBEE_TEXT_TYPE ) ) { str = mimeData->text() + str; } } // set the new clipboard data QMimeData* mimeData = new QMimeData(); mimeData->setText( str ); mimeData->setData( CopyCommand::EDBEE_TEXT_TYPE, "line" ); clipboard->setMimeData( mimeData ); //delete mimeData; // remove the selection controller->replaceRangeSet( newSel, "", coalesceId ); return; } } /// Converts this command to a string QString CutCommand::toString() { return "CutCommand"; } } // edbee
27.890244
113
0.647136
UniSwarm
63cd6875187a29c598dc189f355139ae75080873
1,002
cpp
C++
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
2
2019-05-20T11:12:07.000Z
2021-03-25T04:24:57.000Z
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
includes/fog.cpp
MuUusta/Hello-GFX
c707570207a2db638458352c2de6c03bce5a6759
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #include <math.h> #include <fog.hpp> #include <string> #include <common.h> using namespace std; void initializeFog(){ glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, 0.0); glFogf(GL_FOG_END, 9.0); float color[] = {0.6, 0.6, 0.6, 1.0}; glFogfv(GL_FOG_COLOR, color); glEnable(GL_FOG); } void resetFog(){ glDisable(GL_FOG); } void displayFog(){ glClearColor( 0.6, 0.6, 0.6, 1.0 ); // Clear Color and Depth Buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode( GL_PROJECTION ); // Reset transformations glLoadIdentity(); gluPerspective(45.0f, SCR_WIDTH/SCR_HEIGHT, 0.1f, 1000.0f); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); if(!show_text){ glTranslatef(0,0,-7-sin(glutGet(GLUT_ELAPSED_TIME)*0.0004)*3); glRotatef(glutGet(GLUT_ELAPSED_TIME)*0.02,0,1,0); glColor3f(0.6, 0.3, 0.0); glutSolidTeapot(1); } fps_counter(); render_ImGui(); glutSwapBuffers(); }
22.266667
66
0.684631
MuUusta
63d73091144362d28c1bf1262c8e1adfd2ceb627
1,218
cpp
C++
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
7
2018-11-08T11:39:27.000Z
2020-09-10T17:50:57.000Z
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
null
null
null
HackerRank/Interview Preparation Kit/WarmUp Problems/repeated-strings.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
2
2019-09-16T14:34:03.000Z
2019-10-12T19:24:00.000Z
#include <bits/stdc++.h> using namespace std; /*int main() { long long int n, maxl=0; string s, p=""; cin >> s; cin >> n; for(long long int i=0; i<n; i++) { if( s.length() >= n ) { break; } p = p + s; } for(int i=0; i<n; i++) { if(s[i] == 'a') { maxl++; } } cout<<maxl<<"\n"; return 0; }*/ int main() { long long int n, sum=0, i = 0; string s, p = "" ; map<char, int> m; cin >> s; scanf("%lld", &n); while( !(p.length() >= n) ) { p.append(s); } //cout<< "String Before Sorting : " << p << endl; //sort(p.begin(), p.end()); //cout<< "String After Sorting : " << p << endl; string::iterator it = p.begin(); for(it; it != p.begin()+n; it++){ cout<<*it<<" "; m[*it]++; } /*for(char x : p) { if( i == n ) { break; } if( x == 'a' ) { sum++ ; } else { break ; } i ++ ; } cout << sum << " \n" ;*/ cout<<m['a']<<endl; return 0; }
15.417722
53
0.328407
annukamat
63dcb72c79c52b3efb6fe505ac43ed8c8f318902
935
cpp
C++
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
1
2018-03-30T18:10:37.000Z
2018-03-30T18:10:37.000Z
Greet-core/src/ecs/ECSManager.cpp
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
#include "ECSManager.h" namespace Greet { ECSManager::~ECSManager() { for(auto&& components : componentPool) { delete components.second; } componentPool.clear(); } EntityID ECSManager::CreateEntity() { ASSERT(currentEntityId != (uint32_t)-1, "No more entities available"); entities.emplace(currentEntityId); currentEntityId++; return currentEntityId-1; } void ECSManager::DestroyEntity(EntityID entity) { auto it = entities.find(entity); ASSERT(it != entities.end(), "Entity does not exist in ECSManager (entity=", entity, ")"); entities.erase(it); for(auto&& pool : componentPool) { pool.second->Erase(entity); } } bool ECSManager::ValidEntity(EntityID entity) { return entities.find(entity) != entities.end(); } void ECSManager::Each(std::function<void(EntityID)> function) { for(auto e : entities) function(e); } }
21.25
94
0.648128
Thraix
63e324abce25101720b78772c2aa12e260d2e0a7
255
hpp
C++
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
addons/niarms/caliber/blackout/ar15.hpp
Theseus-Aegis/GTRecoilSystem
308f260af7a2a8839d1f7a0b43d77d49c062ff6c
[ "MIT" ]
null
null
null
// AR-15 Rifles // AR15 - Medium Barrel class hlc_rifle_Bushmaster300: hlc_ar15_base { recoil = QCLASS(300B_MediumBarrel); }; // Black Jack - Medium Barrel class hlc_rifle_bcmblackjack: hlc_rifle_bcmjack { recoil = QCLASS(300B_MediumBarrel); };
21.25
49
0.745098
Theseus-Aegis
63e4027da577945329734e57710b230e5c7871f0
34,965
cpp
C++
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/classic/SxEAM.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #include <SxTimer.h> #include <SxEAM.h> #include <fstream> SxEAM::SxEAM (const SxAtomicStructure &str, const SxSymbolTable *table) { sxprintf ("This is SxEAM::SxEAM\n"); speciesData = SxSpeciesData (&*table); nAtoms = str.getNAtoms (); species.resize (nAtoms); nSpecies = str.getNSpecies (); cout << nSpecies << endl; //--- up to 2 different species implemented yet if (nSpecies > 2) { cout << "Only up to 2 different species implemented in SxEAM" << endl; SX_QUIT; } else { if (nSpecies == 1) { V.resize (1); F.resize (1); rho.resize (1); dV.resize (1); dF.resize (1); drho.resize (1); } if (nSpecies == 2) { V.resize (3); F.resize (3); rho.resize (3); dV.resize (3); dF.resize (3); drho.resize (3); } } int counter = 0; for (int is = 0; is < str.getNSpecies (); is++) { SxString elem = speciesData.chemName(is); for (int ia = 0; ia < str.getNAtoms(is); ia++) { species(counter) = elem; counter++; } } setupSplines ((table -> getGroup("eamPot") -> getGroup("params"))); if (table -> getGroup("eamPot") -> contains("noLinkCell")) noLinkCell = table -> getGroup("eamPot") -> get ("noLinkCell") -> toBool (); else noLinkCell = false; neigh.resize (nAtoms); dist.resize (nAtoms); pw.resize (nAtoms); cell.resize (nAtoms); if (!noLinkCell) { length = 6; setLinkCellMethodParams (str); } update (str); sxprintf("TOTAL ENERGY (Hartree): %.11f\n", getTotalEnergy ()); /* SxAtomicStructure test; test.copy (tau); SxMatrix3<Double> mat; mat.set(0.); for (double aLat = 3.45; aLat < 8.0; aLat += 0.01) { double a0 = tau.cell(0)(0); double a = 2.*A2B*aLat; double scale = a/a0; mat (0, 0) = mat(1, 1) = mat(2, 2) = a; test.cell.set(mat); test.set (scale*test.coordRef ()); update (test); cout << "MURN: " << aLat << " " << getTotalEnergy () << endl; } */ /* SxAtomicStructure test; test.copy (tau); for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { test.ref(i)(j) += 0.05*rand()/(double) 0x7fffffff; } } SxAtomicStructure f1 = getForces (test, table); SxAtomicStructure f2 = getNumericalForces (test, 0.01); SxAtomicStructure f3 = getNumericalForces (test, 0.0001); SxAtomicStructure f = f1 - f2; cout << "LARS3" << endl; fflush(stdout); cout << f1 << endl; cout << f2 << endl; cout << f3 << endl; cout << f << endl; QUIT; */ /* for (int i = 0; i < 100; i++) { cout << "UPDATE" << i << endl; SxAtomicStructure f = getForces (test, table); } for (int i = 0; i < neigh.getSize (); i++) cout << neigh(i).getSize () << endl; */ } SxEAM::~SxEAM () { // empty } void SxEAM::setLinkCellMethodParams (const SxAtomicStructure &tau) { int i, j; double min = 1e20; double max = -1e20; for ( i = 0; i < nAtoms; i++ ) { for (j = 0; j < 3; j++) { if ( tau(i)(j) < min ) min = tau(i)(j); if ( tau(i)(j) > max ) max = tau(i)(j); } } cout << "min " << min << endl; cout << "max " << max << endl; meshOrigin.set(min-(cutoff+2*length)); double meshLength = max + 2*cutoff + 4*length - meshOrigin(0); n = int(meshLength/length); length = meshLength/n; cout << "n: " << n << endl; cout << "length: " << length << endl; cout << "meshOrigin: " << meshOrigin << endl; int nHalf = (int) n/2; SxVector3<Double> RmeshHalf; RmeshHalf.set(length*(nHalf-1)); RmeshHalf += meshOrigin; SxArray<SxVector3<Int> > a1, a2; a1.resize(64); a2.resize(64); for (i = 0; i < 64; i++) { a1(i)(0) = (int) i/32; a1(i)(1) = (int) (i - a1(i)(0)*32)/16; a1(i)(2) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16)/8; a2(i)(0) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8)/4; a2(i)(1) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8 - a2(i)(0)*4)/2; a2(i)(2) = (int) (i - a1(i)(0)*32 - a1(i)(1)*16 - a1(i)(2)*8 - a2(i)(0)*4 - a2(i)(1)*2); } SxList<SxVector3<Int> > neighborsReference; neighborsReference.resize(0); SxVector3<Double> Rmesh, v; int x, y, z; double norm; double minNorm; for (z = 0; z < n; z++) { for (y = 0; y < n; y++) { for (x = 0; x < n; x++) { minNorm = 1e20; Rmesh(0) = length*x + meshOrigin(0); Rmesh(1) = length*y + meshOrigin(1); Rmesh(2) = length*z + meshOrigin(2); for (i = 0; i < 64; i++) { v = Rmesh + length*a1(i) - (RmeshHalf + length*a2(i)); if ((norm = v.norm()) < minNorm) minNorm = norm; } if ((minNorm < cutoff) && ((nHalf-1)!=x || (nHalf-1)!=y || (nHalf-1)!=z)) neighborsReference.append(SxVector3<Int> (x,y,z)); } } } cout << "size of neighborsReference " << neighborsReference.getSize() << endl; SxList<SxVector3<Int> > origMeshTmp; SxList<SxArray<SxVector3<Int> > > neighborsTmp; SxArray<SxVector3<Int> > shiftedReference = neighborsReference; SxVector3<Double> midVec; origMeshTmp.resize(0); neighborsTmp.resize(0); for (z = 0; z < n; z++) { for (y = 0; y < n; y++) { for (x = 0; x < n; x++) { Rmesh = length * (SxVector3<Int> (x,y,z)) + meshOrigin; for (i = 0; i < 64; i=i+8) { v = Rmesh + length*a1(i); v = tau.cell.inverse()^v; if ((v(0) >= 0. && v(0) < 1.) && (v(1) >= 0. && v(1) < 1.) && v(2) >= 0. && v(2) < 1.) { origMeshTmp.append(SxVector3<Int> (x,y,z)); for (j = 0; j < shiftedReference.getSize(); j++) shiftedReference(j) = neighborsReference(j) + (SxVector3<Double> (x-nHalf+1,y-nHalf+1,z-nHalf+1)); neighborsTmp.append(shiftedReference); break; } } } } } origMesh = origMeshTmp; neighbors = neighborsTmp; } bool SxEAM::isRegistered (const SxSymbolTable *cmd) const { SX_CHECK (cmd); SxString str = cmd->getName (); return ( str=="forces" || str=="HesseMatrix" || str=="TTensor" ); } int SxEAM::getInteractionType (int i, int j) { if (speciesData.chemName.getSize () == 1) { return 0; } else { if (i == j) { if (species(i) == speciesData.chemName(0)) return 0; if (species(i) == speciesData.chemName(1)) return 1; SX_EXIT; } else { if ( (species(i) == speciesData.chemName(0)) && (species(j) == speciesData.chemName(0)) ) return 0; if ( (species(i) == speciesData.chemName(1)) && (species(j) == speciesData.chemName(1)) ) return 1; return 2; } } } double SxEAM::getDist (int i, int j, const SxVector3<Double> &R) { SxVector3<Double> v = tau.ref(i) - tau.ref(j) - R; if (fabs(v(0)) > cutoff) return fabs (v(0)); if (fabs(v(1)) > cutoff) return fabs (v(1)); if (fabs(v(2)) > cutoff) return fabs (v(2)); return v.norm (); } void SxEAM::updateNeighsLinkCellMethod () { int cX, cY, cZ, i, j; // int sCut = (int) (cutoff/tau.cell(0, 0)) + 1; int sCut = 1; for (i = 0; i < 3; i++) { int a = (int) (cutoff/tau.cell(i, i)) + 1; if (a > sCut) sCut = a; } SxVector3<Double> v, v1, vMesh, R, vCheck, vReduced; SxArray<SxList<int> > neighList; SxArray<SxList<int> > pwList; SxArray<SxList<double> > distList; SxArray<SxList<SxVector3<Double> > > cellList; neighList.resize(nAtoms); distList.resize(nAtoms); pwList.resize(nAtoms); cellList.resize(nAtoms); SxArray<SxArray<SxArray<SxList<int> > > > meshAtomNr, meshAtomNrPeriodic; SxArray<SxArray<SxArray<SxList<SxVector3<Double> > > > > meshAtomCoord, meshAtomCoordPeriodic; SxArray<SxArray<SxArray<SxList<SxVector3<Double> > > > > meshAtomCell, meshAtomCellPeriodic; meshAtomNr.resize(n); meshAtomNrPeriodic.resize(n); meshAtomCoord.resize(n); meshAtomCoordPeriodic.resize(n); meshAtomCell.resize(n); meshAtomCellPeriodic.resize(n); for (i = 0; i < n; i++) { meshAtomNr(i).resize(n); meshAtomNrPeriodic(i).resize(n); meshAtomCoord(i).resize(n); meshAtomCoordPeriodic(i).resize(n); meshAtomCell(i).resize(n); meshAtomCellPeriodic(i).resize(n); for (j = 0; j < n; j++) { meshAtomNr(i)(j).resize(n); meshAtomNrPeriodic(i)(j).resize(n); meshAtomCoord(i)(j).resize(n); meshAtomCoordPeriodic(i)(j).resize(n); meshAtomCell(i)(j).resize(n); meshAtomCellPeriodic(i)(j).resize(n); } } SxCell inv = tau.cell.inverse(); for (cZ = -sCut; cZ <= sCut; cZ++) { for (cY = -sCut; cY <= sCut; cY++) { for (cX = -sCut; cX <= sCut; cX++) { R = cX*tau.cell(0) + cY*tau.cell(1) + cZ*tau.cell(2); for (i = 0; i < nAtoms; i++) { v = R + tau(i); vMesh = (v - meshOrigin)/length; vReduced = inv^v; // cout << vReduced << " " << n << endl; if (0 <= vMesh(0) && vMesh(0) < n && 0 <= vMesh(1) && vMesh(1) < n && 0 <= vMesh(2) && vMesh(2) < n) { if ((vReduced(0) >= -0.00001 && vReduced(0) < 0.99999999) && (vReduced(1) >= -0.00001 && vReduced(1) < 0.99999999) && (vReduced(2) >= -0.00001 && vReduced(2) < 0.99999999)) { // <-------- meshAtomNr((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(i); meshAtomCoord((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(v); meshAtomCell((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(R); // <-------- } else { // <-------------- meshAtomNrPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(i); meshAtomCoordPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(v); meshAtomCellPeriodic((int)vMesh(0))((int)vMesh(1))((int)vMesh(2)).append(R); // <-------------- } } } } } } for (i = 0; i < nAtoms; i++) { distList(i). resize (0); pwList(i). resize (0); neighList(i).resize (0); cellList(i). resize (0); } int a1, a2, k, l; double distance; SxArray<int> currentAtomNrs, neighborsAtomNrs; SxArray<int> currentAtomNrsPeriodic, neighborsAtomNrsPeriodic; SxArray<SxVector3<Double> > currentAtomCoords, neighborsAtomCoords; SxArray<SxVector3<Double> > currentAtomCoordsPeriodic, neighborsAtomCoordsPeriodic; SxArray<SxVector3<Double> > currentAtomCells, neighborsAtomCells; SxArray<SxVector3<Double> > currentAtomCellsPeriodic, neighborsAtomCellsPeriodic; for (i = 0; i < origMesh.getSize(); i++) { int a = origMesh(i)(0); int b = origMesh(i)(1); int c = origMesh(i)(2); currentAtomNrs = meshAtomNr(a)(b)(c); currentAtomCoords = meshAtomCoord(a)(b)(c); currentAtomCells = meshAtomCell(a)(b)(c); currentAtomNrsPeriodic = meshAtomNrPeriodic(a)(b)(c); currentAtomCoordsPeriodic = meshAtomCoordPeriodic(a)(b)(c); currentAtomCellsPeriodic = meshAtomCellPeriodic(a)(b)(c); for (j = 0; j < currentAtomNrs.getSize(); j++) { a1 = currentAtomNrs(j); v1 = currentAtomCoords(j); for (k = 0; k < currentAtomNrs.getSize(); k++) { if ( k != j ) { a2 = currentAtomNrs(k); v = currentAtomCoords(k); R = currentAtomCells(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } } for (k = 0; k < currentAtomNrsPeriodic.getSize(); k++) { a2 = currentAtomNrsPeriodic(k); v = currentAtomCoordsPeriodic(k); R = currentAtomCellsPeriodic(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } for (l = 0; l < neighbors(i).getSize(); l++) { int a = neighbors(i)(l)(0); int b = neighbors(i)(l)(1); int c = neighbors(i)(l)(2); // <-------- neighborsAtomNrs = meshAtomNr(a)(b)(c); neighborsAtomCoords = meshAtomCoord(a)(b)(c); neighborsAtomCells = meshAtomCell(a)(b)(c); neighborsAtomNrsPeriodic = meshAtomNrPeriodic(a)(b)(c); neighborsAtomCoordsPeriodic = meshAtomCoordPeriodic(a)(b)(c); neighborsAtomCellsPeriodic = meshAtomCellPeriodic(a)(b)(c); // <-------- for (k = 0; k < neighborsAtomNrs.getSize(); k++) { a2 = neighborsAtomNrs(k); v = neighborsAtomCoords(k); R = neighborsAtomCells(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } for (k = 0; k < neighborsAtomNrsPeriodic.getSize(); k++) { a2 = neighborsAtomNrsPeriodic(k); v = neighborsAtomCoordsPeriodic(k); R = neighborsAtomCellsPeriodic(k); vCheck = v1-v; if (fabs(vCheck(0)) < cutoff && fabs(vCheck(1)) < cutoff && fabs(vCheck(2)) < cutoff) { if ((distance = sqrt(vCheck.absSqr().sum())) < cutoff) { neighList(a1).append (a2); distList(a1).append (distance); cellList(a1).append (vCheck); pwList(a1).append (getInteractionType (a1, a2)); } } } } } } for (i = 0; i < nAtoms; i++) { neigh(i) = neighList(i); dist(i) = distList(i); pw(i) = pwList(i); cell(i) = cellList(i); } } void SxEAM::updateNeighs () { double distance; SxVector3<Double> R; SxArray<SxList<int> > neighList; SxArray<SxList<double> > distList; SxArray<SxList<SxVector3<Double> > > cellList; neighList.resize(nAtoms); distList.resize(nAtoms); cellList.resize(nAtoms); int i, j; int sCut = (int) (cutoff/tau.cell(0, 0)) + 1; for (i = 0; i < nAtoms; i++) { distList(i). resize (0); neighList(i).resize (0); cellList(i). resize (0); } for (i = 0; i < nAtoms; i++) { for (int cX = -sCut; cX <= sCut; cX++) { for (int cY = -sCut; cY <= sCut; cY++) { for (int cZ = -sCut; cZ <= sCut; cZ++) { R = cX*tau.cell(0) + cY*tau.cell(1) + cZ*tau.cell(2); for (j = 0; j < nAtoms; j++) { if ( ((i != j)) && ((distance = getDist(i, j, R)) < cutoff )) { neighList(i).append (j); distList(i).append (distance); cellList(i).append ( tau.ref(i) - tau.ref(j) - R ); } } } } } } for (i = 0; i < nAtoms; i++) { neigh(i) = neighList(i); dist(i) = distList(i); cell(i) = cellList(i); } } void SxEAM::update (const SxAtomicStructure &newTau) { double R; tau = SxAtomicStructure (newTau, SxAtomicStructure::Copy); if (noLinkCell) updateNeighs(); else updateNeighsLinkCellMethod(); //--- updating charge densities on atom positions rhoSum.resize (0); rhoSum.resize (nAtoms); int iType; for (int i = 0; i < nAtoms; i++) { rhoSum(i) = 0.; for (int j = 0; j < neigh(i).getSize (); j++) { R = dist(i)(j); iType = getInteractionType (neigh(i)(j), neigh(i)(j)); rhoSum(i) += getRho(R, iType); } } } SxList<double> SxEAM::readData(const SxString &fileName) { SxList<double> list; ifstream filestr; double d1, d2; filestr.open(fileName.ascii()); filestr >> d1; filestr >> d2; list.append(d1); list.append(d2); while (filestr) { filestr >> d1; if (filestr) { filestr >> d2; list.append(d1); list.append(d2); } } filestr.close(); return list; } void SxEAM::setupSplines (const SxSymbolTable *cmd) { cout << "Setting up splines ..." << endl; SxList<double> readList; SxArray<double> Vx, Vy, y2; double dx, dy, xMax, xMin, x; int noI = (int)V.getSize (); int nSP; //--- number of points for tabulating potentials //nPoints = 1000000; nPoints = 100000; //---read in V(r) in eV(Angstroem) if (cmd->contains("V")) readList = cmd -> get ("V") -> toList (); else readList = readData(cmd->get("VFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); V(nI).resize (2); V(nI)(0).resize (nPoints+1); V(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); cutoff = xMax * A2B; //cutoff = xMax; xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; V(nI)(0)(i) = x; V(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); } } //---read in Rho(r) in eV(Angstroem) if (cmd->contains("RHO")) readList = cmd -> get ("RHO") -> toList (); else readList = readData(cmd->get("RHOFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); rho(nI).resize (2); rho(nI)(0).resize (nPoints+1); rho(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); if ( xMax*A2B > cutoff ) cutoff = xMax*A2B; xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; rho(nI)(0)(i) = x; rho(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); // cout << "RHO: " << rho(0)(i) << " " << rho(1)(i) << endl; } } //---read in F(r) in eV(Angstroem) if (cmd->contains("F")) readList = cmd -> get ("F") -> toList (); else readList = readData(cmd->get("FFile")->toString()); nSP = (int)readList.getSize () / 2 / noI; for (int nI = 0; nI < noI; nI++) { Vx.resize (readList.getSize () / 2 / noI); Vy.resize (readList.getSize () / 2 / noI); y2.resize (readList.getSize () / 2 / noI); for (int i = 0; i < Vx.getSize (); i++) { Vx(i) = readList(2*(nSP*nI + i) ); Vy(i) = readList(2*(nSP*nI + i) + 1); } dy = Vy(1) - Vy(0); dx = Vx(1) - Vx(0); spline (Vx, Vy, (int)Vx.getSize (), dy/dx, 0., &y2); F(nI).resize (2); F(nI)(0).resize (nPoints+1); F(nI)(1).resize (nPoints+1); xMax = Vx(Vx.getSize () - 1); xMin = Vx(0); dx = (xMax - xMin)/(double)nPoints; for (int i = 0; i <= nPoints; i++) { x = xMin + dx*(double)i; F(nI)(0)(i) = x; F(nI)(1)(i) = splint (Vx, Vy, y2, (int)Vx.getSize (), x); // cout << "FF: " << F(0)(i) << " " << F(1)(i) << endl; } } //--- tabulating derivatives for (int nI = 0; nI < noI; nI++) { dV(nI).resize (2); dV(nI)(0).resize (V(nI)(0).getSize ()); dV(nI)(1).resize (V(nI)(1).getSize ()); drho(nI).resize (2); drho(nI)(0).resize (rho(nI)(0).getSize ()); drho(nI)(1).resize (rho(nI)(1).getSize ()); dF(nI).resize (2); dF(nI)(0).resize (F(nI)(0).getSize ()); dF(nI)(1).resize (F(nI)(1).getSize ()); for (int i = 1; i < (dV(nI)(0).getSize () - 1); i++) { dV(nI)(0)(i) = V(nI)(0)(i); dy = V(nI)(1)(i + 1) - V(nI)(1)(i - 1); dx = V(nI)(0)(i + 1) - V(nI)(0)(i - 1); dV(nI)(1)(i) = dy/dx; } dV(nI)(0)(0) = V(nI)(0)(0); dV(nI)(0)(dV(nI).getSize() - 1) = V(nI)(0)(dV(nI).getSize () - 1); dV(nI)(1)(0) = dV(nI)(1)(1); dV(nI)(1)(dV(nI).getSize() - 1) = dV(nI)(1)(dV(nI).getSize () - 2); for (int i = 1; i < (dF(nI)(0).getSize () - 1); i++) { dF(nI)(0)(i) = F(nI)(0)(i); dy = F(nI)(1)(i + 1) - F(nI)(1)(i - 1); dx = F(nI)(0)(i + 1) - F(nI)(0)(i - 1); dF(nI)(1)(i) = dy/dx; } dF(nI)(0)(0) = F(nI)(0)(0); dF(nI)(0)(dF(nI).getSize() - 1) = F(nI)(0)(dF(nI).getSize () - 1); dF(nI)(1)(0) = dF(nI)(1)(1); dF(nI)(1)(dF(nI).getSize() - 1) = dF(nI)(1)(dF(nI).getSize () - 2); for (int i = 1; i < (drho(nI)(0).getSize () - 1); i++) { drho(nI)(0)(i) = rho(nI)(0)(i); dy = rho(nI)(1)(i + 1) - rho(nI)(1)(i - 1); dx = rho(nI)(0)(i + 1) - rho(nI)(0)(i - 1); drho(nI)(1)(i) = dy/dx; } drho(nI)(0)(0) = rho(nI)(0)(0); drho(nI)(0)(drho(nI).getSize() - 1) = rho(nI)(0)(drho(nI).getSize () - 1); drho(nI)(1)(0) = drho(nI)(1)(1); drho(nI)(1)(drho(nI).getSize() - 1) = drho(nI)(1)(drho(nI).getSize () - 2); } // for (int i = 0; i < F(0)(0).getSize (); i++) // if ((i < 100) || (i > (drho(0)(0).getSize () - 100))) // cout << F(1)(0)(i) << " " << F(1)(1)(i) << " " << dF(1)(1)(i) << endl; // QUIT; } double SxEAM::getEnergy () const { return totalEnergy; } double SxEAM::getPotentialEnergy () const { return totalEnergy; } SxSpeciesData SxEAM::getSpeciesData () const { return speciesData; } SxAtomicStructure SxEAM::getNumericalForces (const SxAtomicStructure &tauIn, const double &dx) { SxAtomicStructure Forces (tauIn, SxAtomicStructure::Copy); SxAtomicStructure undevCoord (tauIn, SxAtomicStructure::Copy); SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); double undevEnergy; update(tauIn); undevEnergy = getTotalEnergy (); for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { Forces.ref(i)(j) = 0.; devCoord.ref(i)(j) += dx; update(devCoord); Forces.ref(i)(j) -= (getTotalEnergy () - undevEnergy)/dx/2.; devCoord.ref(i)(j) -= 2.*dx; update(devCoord); Forces.ref(i)(j) += (getTotalEnergy() - undevEnergy)/dx/2.; devCoord.ref(i)(j) += dx; } } return Forces; } SxArray<SxAtomicStructure> SxEAM::getNumericalHesseMatrix (const SxAtomicStructure &tauIn, const double &dx) { SxArray<SxAtomicStructure> Hesse; Hesse.resize (3*nAtoms); SxAtomicStructure A, B; SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); SxSymbolTable *table = NULL; // CF 2016-07-07: where should table come from ??? for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { devCoord.ref(i)(j) += dx; A = getForces (devCoord, table); devCoord.ref(i)(j) -= 2.*dx; B = getForces (devCoord, table); Hesse(3*i+j).copy ((1./dx/2.)*(A-B)); //Hesse(3*i+j) = (1./dx/2.)*(A-B); devCoord.ref(i)(j) += dx; } } return Hesse; } SxArray<SxArray<SxAtomicStructure> > SxEAM::getNumericalTTensor (const SxAtomicStructure &tauIn, const double &dx) { double threshold = 1e-9; SxArray<SxArray<SxAtomicStructure> > TTensor; TTensor.resize(3*nAtoms); SxArray<SxAtomicStructure> A, B, Delta; SxAtomicStructure devCoord (tauIn, SxAtomicStructure::Copy); int i,j,k,l,m; sxprintf("nAtoms=%d",nAtoms); fflush(stdout); for (i = 0; i < nAtoms; i++) { sxprintf(" %d",i+1); fflush(stdout); for (j = 0; j < 3; j++) { devCoord.ref(i)(j) += dx; A = getNumericalHesseMatrix (devCoord,dx); devCoord.ref(i)(j) -= 2.*dx; B = getNumericalHesseMatrix (devCoord,dx); //Delta = A-B; Delta.resize(3*nAtoms); for (k=0;k<Delta.getSize();k++) { Delta(k) = A(k) - B(k); Delta(k) = (1./dx/2.) * Delta(k); for (l=0; l<nAtoms; l++) { for (m=0; m<3; m++) { if (Delta(k).ref(l)(m) < threshold) Delta(k).ref(l)(m)=0.; } } } // cout << "Delta " << Delta(24)( << endl; TTensor(3*i+j) = Delta; devCoord.ref(i)(j) += dx; } } cout << endl; return TTensor; } void SxEAM::exportForces (const SxAtomicStructure &forces, const SxString &fileName) { int i; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (i=0; i<nAtoms; i++) { filestr << forces(i)(0) << " " << forces(i)(1) << " " << forces(i)(2) << endl; } filestr.close(); } void SxEAM::exportHesse (const SxArray<SxAtomicStructure> &hesse, const SxString &fileName) { int i, j; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (i=0; i<3*nAtoms; i++) { for (j=0; j<nAtoms; j++) { filestr << -hesse(i)(j)(0) << " " << -hesse(i)(j)(1) << " " << -hesse(i)(j)(2) << " "; } filestr << endl; } filestr.close(); } void SxEAM::exportTTensor (const SxArray<SxArray<SxAtomicStructure> > &TTensor, const SxString &fileName) { int i, j, k; ofstream filestr; filestr.open(fileName.ascii(), ifstream::trunc); for (k=0;k<3*nAtoms;k++) { for (i=0; i<3*nAtoms; i++) { for (j=0; j<nAtoms; j++) { filestr << TTensor(k)(i)(j)(0) << " " << TTensor(k)(i)(j)(1) << " " << TTensor(k)(i)(j)(2) << " "; } } filestr << endl; } filestr.close(); } SxAtomicStructure SxEAM::getForces (const SxAtomicStructure &tauIn, const SxSymbolTable *dummy) { // SVN_HEAD; // this line MUST NOT be removed SxAtomicStructure forces (tauIn, SxAtomicStructure::Copy); update (tauIn); double R = 0.; SxVector3<Double> e; int n = 0; int iType1; int iType2; int iType3; for (int i = 0; i < nAtoms; i++) { forces.ref(i).set(0.); for (int j = 0; j < neigh(i).getSize (); j++) { n = neigh(i)(j); R = dist(i)(j); e = (1./R)*cell(i)(j); iType1 = getInteractionType(i, n); iType2 = getInteractionType(n, n); iType3 = getInteractionType(i, i); forces.ref(i) -= (getdV(R, iType1) + getdF(rhoSum(n), iType2) *getdRho(R, iType3) + getdF(rhoSum(i), iType3) *getdRho(R, iType2))*e; } } totalEnergy = getTotalEnergy (); // cout << tauIn << endl; return ((1./HA2EV)*forces); } double SxEAM::getV (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - V(isP)(0)(0))/(V(isP)(0)(1)-V(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; return ((1. - interpol)*V(isP)(1)(idx) + interpol*V(isP)(1)(idx + 1)); } double SxEAM::getdV (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - dV(isP)(0)(0))/(dV(isP)(0)(1)-dV(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; //double interpol = 0.; return (((1. - interpol)*dV(isP)(1)(idx) + interpol*dV(isP)(1)(idx + 1))/A2B); } double SxEAM::getRho (const double &r, int isP) { double rB = r/A2B; //double last = rho(isP)(0)(rho(isP)(0).getSize()-1); double idxD = ((rB - rho(isP)(0)(0))/(rho(isP)(0)(1) -rho(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; return ((1. - interpol)*rho(isP)(1)(idx) + interpol*rho(isP)(1)(idx + 1)); } double SxEAM::getdRho (const double &r, int isP) { double rB = r/A2B; double idxD = ((rB - drho(isP)(0)(0))/(drho(isP)(0)(1) - drho(isP)(0)(0))); int idx = (int) idxD; double interpol = idxD - (double)idx; //double interpol = 0.; return (((1. - interpol)*drho(isP)(1)(idx) + interpol*drho(isP)(1)(idx + 1))/A2B); } double SxEAM::getF (const double &rh, int isP) { double rB = rh; double idxD = ((rB - F(isP)(0)(0))/(F(isP)(0)(1)-F(isP)(0)(0))); int idx = (int) idxD; if (idx >= F(isP)(0).getSize ()) return (F(isP)(1)(F(isP)(0).getSize () - 1)); double interpol = idxD - (double)idx; return ((1. - interpol)*F(isP)(1)(idx) + interpol*F(isP)(1)(idx + 1)); } double SxEAM::getdF (const double &rh, int isP) { double rB = rh; double idxD = ((rB - dF(isP)(0)(0))/(dF(isP)(0)(1) - dF(isP)(0)(0))); int idx = (int) idxD; if (idx >= dF(isP)(0).getSize ()) return 0.; double interpol = idxD - (double)idx; //double interpol = 0.; return ((1. - interpol)*dF(isP)(1)(idx) + interpol*dF(isP)(1)(idx + 1)); } double SxEAM::getTotalEnergy () { double energy, R; int i, j; energy = 0.; int iType; for (i = 0; i < nAtoms; i++) { for (j = 0; j < neigh(i).getSize (); j++) { iType = getInteractionType(i, neigh(i)(j)); R = dist(i)(j); energy += 0.5*getV (R, iType); } iType = getInteractionType(i, i); energy += getF (rhoSum(i), iType); } return (energy/HA2EV); } void SxEAM::execute (const SxSymbolTable *cmd, bool calc) { cout << "Executing EAM Potential" << endl << endl; SxString s = cmd->getName(); double disp; update (tau); SxAtomicStructure str=tau; exportForces(tau,"cartesian_coords"); cout << "cartesian_coords in bohr exported." << endl << endl; if (s=="forces") { if (cmd->contains("numerical")) { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical forces with displacement " << disp << " Angstrom..." << endl; exportForces(getNumericalForces(tau, disp),"Forces"); cout << "Forces in hartree/bohr exported." << endl << endl; } else { cout << "Calculating analytical forces..." << endl; exportForces(getForces(tau),"Forces"); cout << "Forces in hartree/bohr exported." << endl << endl; } } if (s=="HesseMatrix") { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical Hesse matrix with displacement " << disp << " Angstrom (forces are analytical)..." << endl; exportHesse(getNumericalHesseMatrix(tau, disp),"HesseMatrix"); cout << "HesseMatrix in hartree/(u*bohr^2) exported." << endl << endl; } if (s=="TTensor") { disp = (cmd->contains("disp")) ? cmd->get("disp")->toReal() : 0.01; cout << "Calculating numerical TTensor with displacement " << disp << " Angstrom (forces are analytical)..." << endl; SxArray<SxArray<SxAtomicStructure> > TTensor; TTensor = getNumericalTTensor(tau,disp); exportTTensor(TTensor,"TTensor"); cout << "TTensor in hartree/(u*bohr^3) exported." << endl << endl; } return; } void SxEAM::spline (const SxArray<double> &x, const SxArray<double> &y, int n, double yp1, double ypn, SxArray<double> *y2) { int i, k; double p, qn, sig, un; SxArray<double> u (x.getSize ()); if (yp1 > 0.99e30) (*y2)(0) = u(0) = 0.; else { (*y2)(0) = -0.5; u(0) = (3.0/(x(1) - x(0))) * ((y(1) - y(0))/(x(1) - x(0)) - yp1); } for (i = 1; i <= (n-2); i++) { sig = (x(i) - x(i-1))/(x(i+1) - (x(i-1))); p = sig* (*y2)(i-1) + 2.; (*y2)(i) = (sig - 1.)/p; u(i) = (y(i+1) - y(i))/(x(i+1) - x(i)) - (y(i) - y(i-1))/(x(i) - x(i-1)); u(i) = (6.0*u(i)/(x(i+1) - x(i-1)) -sig*u(i-1))/p; } if (ypn > 0.99e30) qn = un = 0.0; else { qn = 0.5; un = (3.0/(x(n-1) - x(n-2)))*(ypn - (y(n-1) - y(n-2))/(x(n-1) - x(n-2))); } (*y2)(n-1) = (un - qn*u(n-2))/(qn* (*y2)(n-2) + 1.); for (k = (n-2); k>= 0; k--) (*y2)(k) = (*y2)(k)*(*y2)(k + 1) + u(k); } double SxEAM::splint (const SxArray<double> &xa, const SxArray<double> &ya, const SxArray<double> &y2a, int n, double x) { int klo, khi, k; double h,b,a; klo = 0; khi = n-1; while ( (khi-klo) > 1) { k = (khi + klo) >> 1; if (xa(k) > x) khi = k; else klo = k; } h = (xa(khi) - xa(klo)); if (h == 0.) { cout << "Bad xa input to routine splint" << endl; SX_EXIT; } a = (xa(khi) - x)/h; b = (x - xa(klo))/h; double y = a*ya(klo) + b*ya(khi)+((a*a*a - a)*y2a(klo) + (b*b*b - b)*y2a(khi))*(h*h)/6.0; return y; }
29.606266
115
0.498956
ashtonmv
63e5ce142b41ff52370b391a71f1250f4dcdfbf7
8,335
cpp
C++
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
operators/data_sender_bcast_tcp.cpp
damodar123/pythia-core
6b90aafed40aa63185105a652b20c61fc5a4320d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2015, Pythia authors (see AUTHORS file). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "operators.h" #include "operators_priv.h" #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <ifaddrs.h> #include <arpa/inet.h> #include <unistd.h> #include <iostream> #include <cstdlib> #include <iomanip> #include "../rdtsc.h" #include "../util/tcpsocket.h" #include <fstream> #include <string> using std::make_pair; //input attributes for rdma send: // int port: port used for TCP/IP to do sync // int msgsize: send message size, 4096 bytes by default // int buffnum: number of buffers used in send void DataSenderBcastTcpOp::init(libconfig::Config& root, libconfig::Setting& cfg) { //static_assert(sizeof(struct thread_rc_t)%CACHE_LINE_SIZE == 0); //static_assert(sizeof(struct destlink_t)%CACHE_LINE_SIZE == 0); Operator::init(root, cfg); schema = nextOp->getOutSchema(); //todo: the following varaibles should come from config file if (cfg.exists("threadnum")) { threadnum_ = cfg["threadnum"]; } else { threadnum_ = 1; } if (cfg.exists("opid")) { operator_id_ = cfg["opid"]; } else { operator_id_ = 0; } atomic_thread_cnt_ = threadnum_; msgsize_ = cfg["msgsize"]; nodenum_ = cfg["nodenum"]; assert(nodenum_ < MAX_LINKS); node_id_ = cfg["nodeid"]; //node id is to identify each node, frange from 0 to n-1 host_ip_ = (const char*) cfg["hostIP"]; //loop to get all ip adress of remote node libconfig::Setting& ipgrp = cfg["destIP"]; int size = ipgrp.getLength(); assert( size != 0 ); assert( size <= MAX_LINKS ); for (int i=0; i<size; ++i) { std::string ipaddr = (const char*) ipgrp[i]; dest_ip_.push_back(ipaddr); } vector<int> temp_sock_id; for (int i=0; i<size; i++) { temp_sock_id.push_back(-1); } for (int i=0; i<threadnum_; i++) { sock_id_.push_back(temp_sock_id); } //buffer for data to each destination for (int i=0; i<MAX_THREADS; i++) { thread_rc_[i].out_buffer = &EmptyPage; } } void DataSenderBcastTcpOp::threadInit(unsigned short threadid) { assert(threadid < threadnum_); thread_rc_[threadid].buf = numaallocate_local("DSbf", msgsize_, this); thread_rc_[threadid].rdma_buf.set((char*)thread_rc_[threadid].buf); if (threadid == 0) { for (int i=0; i<threadnum_; i++) { TcpServer(LISTEN_PORT+i+operator_id_*MAX_THREADS, host_ip_.c_str(), nodenum_, sock_id_[i]); for (int j=0; j<nodenum_; j++) { assert(sock_id_[i][j] != -1); } //sync to exit for (int j=0; j<nodenum_; j++) { if(sock_id_[i][j] == -1) { continue; } char temp = 'a'; assert(send(sock_id_[i][j], &temp, sizeof(temp), MSG_DONTWAIT) != -1); //cout << "send hand sig from " << node_id_ << " to " << j << endl; } for (int j=0; j<nodenum_; j++) { if(sock_id_[i][j] == -1) { continue; } char temp = 'b'; assert(recv(sock_id_[i][j], &temp, sizeof(temp), MSG_WAITALL) != -1); //cout << "recv hand sig " << temp << " from " << j << " to " << node_id_ << endl; } } } } Operator::ResultCode DataSenderBcastTcpOp::scanStart(unsigned short threadid, Page* indexdatapage, Schema& indexdataschema) { //cout << "before scan start" << endl; ResultCode rescode; thread_rc_[threadid].out_buffer = new Page(thread_rc_[threadid].rdma_buf.msg, msgsize_-12, NULL, schema.getTupleSize()); thread_rc_[threadid].out_buffer->clear(); rescode = nextOp->scanStart(threadid, indexdatapage, indexdataschema); return rescode; } Operator::GetNextResultT DataSenderBcastTcpOp::getNext(unsigned short threadid) { //here we assume a one to one mapping between rdma wr_id and send buff //addr and 0 to buffer0, 1 to buffer1, buffnum_-1 to buffer buffnum_-1 //cout << "before getnext" << endl; Operator::GetNextResultT result; result = nextOp->getNext(threadid); Page* in; Operator::ResultCode rc; in = result.second; rc = result.first; void *tuple; int tupoffset = 0; while (1) { while ((tuple = in->getTupleOffset(tupoffset)) != NULL) { //if data in page in is less than left space in send buffer uint64_t left_data_in = in->getUsedSpace()-tupoffset*in->getTupleSize(); if (thread_rc_[threadid].out_buffer->canStore(left_data_in)) { void * bucketspace = thread_rc_[threadid].out_buffer->allocate(left_data_in); memcpy(bucketspace, tuple, left_data_in); break; } //data in page in is more than left space in send buffer else { uint64_t left_space_in_buffer = thread_rc_[threadid].out_buffer->capacity() - thread_rc_[threadid].out_buffer->getUsedSpace(); void *bucketspace = thread_rc_[threadid].out_buffer->allocate(left_space_in_buffer); memcpy(bucketspace, tuple, left_space_in_buffer); tupoffset += left_space_in_buffer/in->getTupleSize(); int datalen = thread_rc_[threadid].out_buffer->getUsedSpace(); thread_rc_[threadid].rdma_buf.deplete = MoreData; thread_rc_[threadid].rdma_buf.datalen = datalen; thread_rc_[threadid].rdma_buf.nodeid = node_id_; thread_rc_[threadid].rdma_buf.serialize(); for (int i=0; i<nodenum_; i++) { send(sock_id_[threadid][i], thread_rc_[threadid].rdma_buf.buffaddr(), msgsize_, MSG_WAITALL); } //clear buffer after send out thread_rc_[threadid].out_buffer->clear(); } } if (rc == Finished) { int datalen = thread_rc_[threadid].out_buffer->getUsedSpace(); thread_rc_[threadid].rdma_buf.deplete = Depleted; thread_rc_[threadid].rdma_buf.datalen = datalen; thread_rc_[threadid].rdma_buf.nodeid = node_id_; thread_rc_[threadid].rdma_buf.serialize(); for (int i=0; i<nodenum_; i++) { send(sock_id_[threadid][i], thread_rc_[threadid].rdma_buf.buffaddr(), msgsize_, MSG_WAITALL); } //clear buffer after send out thread_rc_[threadid].out_buffer->clear(); return make_pair(Finished, &EmptyPage); } result = nextOp->getNext(threadid); rc = result.first; in = result.second; tupoffset = 0; } } void DataSenderBcastTcpOp::threadClose(unsigned short threadid) { //shake hands to exit //block until all destinations receive all the data //is this necessary? or should we put this in scan stop? //cout << "before t close" << endl; for (int i=0; i<nodenum_; i++) { char temp = 'a'; assert(send(sock_id_[threadid][i], &temp, sizeof(temp), MSG_DONTWAIT) != -1); //cout << "send hand sig from " << node_id_ << " to " << i << endl; } for (int i=0; i<nodenum_; i++) { char temp = 'b'; assert(recv(sock_id_[threadid][i], &temp, sizeof(temp), MSG_WAITALL) != -1); //cout << "recv hand sig " << temp << " from " << i << " to " << node_id_ << endl; } numadeallocate(thread_rc_[threadid].buf); //delete Page in out_buffer_ if (thread_rc_[threadid].out_buffer != &EmptyPage) { delete thread_rc_[threadid].out_buffer; } for (int i=0; i<nodenum_; i++) { close(sock_id_[threadid][i]); } }
32.558594
130
0.695381
damodar123
63e7071bdaa4b29f8cf58e81570e3d44530ebdc4
564
cpp
C++
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
Pyramid Printer/pyramid.cpp
noahkiss/intro-to-cpp
8a4a8836f9e52ddffe6229d8d07e7b34d6a6fbb1
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { int row = 8; //cout << "How many rows of numbers? "; //cin >> row; row--; for (int line = 0; line <= row; line++) { cout << setw(36 - 4 * line) << 1; for (int num = 1; num <= line; num++) { cout << setw(4) << pow(2, num); } for (int num = line - 1; num > 0; num--) { cout << setw(4) << pow(2, num); } if (line) cout << setw(4) << 1; cout << endl; } return 0; }
20.142857
50
0.437943
noahkiss
63f277898b3f89389f3df8d83b2aec541ab3bcf7
240
cc
C++
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
cpp-tutorial/main/test/hello-greet-test.cc
yuryu/bazel-examples
817f2f84211ca21733a78eefcb0b47aeb2cfddf0
[ "Apache-2.0" ]
null
null
null
#include "gtest/gtest.h" #include "../hello-greet.h" TEST(hello_greet_test, empty_string) { EXPECT_EQ(get_greet(""), std::string("Hello ")); } TEST(hello_greet_test, with_name) { EXPECT_EQ(get_greet("abc"), std::string("Hello ")); }
17.142857
53
0.683333
yuryu
120b366f5428ed1a54fb4067419c09d17a495ecd
535
cpp
C++
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
minorGems/graphics/openGL/testNavigatorGL.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
/* * Modification History * * 2001-August-29 Jason Rohrer * Created. */ #include "TestSceneHandlerGL.h" #include "SceneNavigatorDisplayGL.h" #include "minorGems/util/random/StdRandomSource.h" // simple test function int main() { StdRandomSource *randSource = new StdRandomSource( 2 ); TestSceneHandlerGL *handler = new TestSceneHandlerGL(); char *name = "test window"; SceneNavigatorDisplayGL *screen = new SceneNavigatorDisplayGL( 200, 200, false, name, handler ); screen->start(); return 0; }
15.735294
64
0.702804
PhilipLudington
120efb8217919a11260f48ea71db2767e661803e
1,323
hpp
C++
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
2
2015-10-08T15:07:07.000Z
2017-09-17T10:08:36.000Z
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
lab2/13_documentpermissions/application.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
// (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine #ifndef _APPLICATION_HPP_ #define _APPLICATION_HPP_ /*****************************************************************************/ class Document; class User; /*****************************************************************************/ class Application { /*-----------------------------------------------------------------*/ public: /*-----------------------------------------------------------------*/ Application (); ~ Application (); void generateTestModel (); void printUserPermissionsReport () const; void printDocumentsNotHavingPermittedUsers () const; void printUsersNotHavingPermittedDocuments () const; void printDocumentsHavingMultipleWriteUsers () const; /*-----------------------------------------------------------------*/ private: /*-----------------------------------------------------------------*/ Application ( const Application & ); Application & operator = ( const Application & ); /*-----------------------------------------------------------------*/ // TODO ... declare the top of the object model hierarchy here ... /*-----------------------------------------------------------------*/ }; /*****************************************************************************/ #endif // _APPLICATION_HPP_
22.810345
79
0.368103
zaychenko-sergei
1210d99a23384b0d94d7d60e0274abd5d0ce428f
554
cpp
C++
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/Buildables/FGBuildableStorage.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGBuildableStorage.h" void AFGBuildableStorage::GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps) const{ } AFGBuildableStorage::AFGBuildableStorage(){ } void AFGBuildableStorage::BeginPlay(){ } void AFGBuildableStorage::GetDismantleRefund_Implementation( TArray< FInventoryStack >& out_refund) const{ } void AFGBuildableStorage::Factory_CollectInput_Implementation(){ } void AFGBuildableStorage::OnRep_ReplicationDetailActor(){ }
50.363636
109
0.833935
iam-Legend
12218e1b49e132f99abf151cfeba03616ebf1392
1,752
hpp
C++
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/javax/swing/JComponent_ActionStandin.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/awt/event/fwd-POI.hpp> #include <java/beans/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <javax/swing/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <javax/swing/Action.hpp> struct default_init_tag; class javax::swing::JComponent_ActionStandin final : public virtual ::java::lang::Object , public Action { public: typedef ::java::lang::Object super; private: Action* action { }; ::java::awt::event::ActionListener* actionListener { }; ::java::lang::String* command { }; public: /* package */ JComponent* this$0 { }; protected: void ctor(::java::awt::event::ActionListener* actionListener, ::java::lang::String* command); public: void actionPerformed(::java::awt::event::ActionEvent* ae) override; void addPropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; ::java::lang::Object* getValue(::java::lang::String* key) override; bool isEnabled() override; void putValue(::java::lang::String* key, ::java::lang::Object* value) override; void removePropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; void setEnabled(bool b) override; // Generated public: /* package */ JComponent_ActionStandin(JComponent *JComponent_this, ::java::awt::event::ActionListener* actionListener, ::java::lang::String* command); protected: JComponent_ActionStandin(JComponent *JComponent_this, const ::default_init_tag&); public: static ::java::lang::Class *class_(); JComponent *JComponent_this; private: virtual ::java::lang::Class* getClass0(); };
30.206897
141
0.712329
pebble2015
1222bf42564258b8741d3a4e1ee4d04f8f9386e6
119
hpp
C++
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
91
2017-11-28T07:23:09.000Z
2022-03-28T08:31:51.000Z
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
59
2017-11-28T06:12:18.000Z
2022-03-18T09:00:59.000Z
src/TSBlank.hpp
miRackModular/trowaSoft-VCV
56ab2f95bcd0f788b3eb8714718c972cbb0546d9
[ "MIT" ]
15
2017-11-28T13:42:35.000Z
2021-12-26T08:03:37.000Z
#ifndef TSBLANK_HPP #define TSBLANK_HPP extern Model* modelBlank; struct TSBlankWidget; struct TSBlankModule; #endif
13.222222
25
0.823529
miRackModular
12282f70ba99bdfd96964f5135a3aef17678e1d3
1,015
cpp
C++
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
1
2021-08-20T03:01:16.000Z
2021-08-20T03:01:16.000Z
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
null
null
null
Heap/2/Phase3Main.cpp
PeterTheAmazingAsian/ProjectTestCases
85ddd13216d65267cbf0ea76ea014af902f3d9da
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #include "Heap.cpp" int main() { Heap<short int> A; Heap<double> B; Heap<unsigned long long int> C; Heap<long double> D; Heap<string> E; A.insert(4); A.insert(9); A.insert(3); A.insert(5); A.insert(100); A.printKey(); Heap<short int> AA(A); Heap<short int> AAA(AA); AA.printKey(); AAA.printKey(); AAA.extractMin(); AA.extractMin(); AA.extractMin(); AAA.printKey(); AA.printKey(); A.printKey(); string alphabet[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; Heap<string> F(alphabet, 26); F.printKey(); Heap<string> FF = F; Heap<string> FFF = FF; FF.printKey(); FFF.printKey(); FFF.extractMin(); FF.extractMin(); FF.extractMin(); FFF.printKey(); FF.printKey(); F.printKey(); return 0; }
19.150943
69
0.483744
PeterTheAmazingAsian
1228306b07197609b134f9c0c3cd7bc9b598adba
13,063
cpp
C++
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
call_stats5.cpp
juan2357/call_stats5
0eb23f66ab5f4e8c60f16072ba784f9e03ee6589
[ "MIT" ]
null
null
null
/* Name: Juan Perez Z#:23026404 Course: COP 3014 Professor: Dr. Lofton Bullard Due Date: 3/20/18 Due Time: 11:59 Total Points: 20 Assignment 8: call_stats5.cpp Description 1. Read the contents of a data file one record at a time in a dynamic array; 2. Process the data that was read from the data file one record at a time, into a dynamic array; 3. Print the records in a dynamic array to a datafile using an ofstream object; 4. Use the operator new to allocate memory for a dynamic array; 5. Use the operator delete to de-allocate the memory allocated by the new; (basically, making previously used memory available for use again) 6. Copy the content of one dynamic array into another dynamic array (basically, copying memory from one location to another) 4. Be able to use the fstream library; 5. Be able to use a dynamic array of record records; 6. Be able to use an ifstream object; 7. Be able to use an ofstream object; */ #include <iostream> #include <string> #include <fstream> #include <iostream> using namespace std; //sample record (class with no functionality) class call_record { public: string firstname; string lastname; string cell_number; int relays; int call_length; double net_cost; double tax_rate; double call_tax; double total_cost; }; //Function Prototypes void Initialize(call_record *& call_DB, int & count, int & size); bool Is_empty(const int count); //inline implementation bool Is_full(const int count, int size);//inline implementation int Search(const call_record *call_DB, const int count, const string key);//returns location if item in listl; otherwise return -1 void Add(call_record * &call_DB, int & count, int & size, const string key); //adds item inorder to the list void Remove(call_record *call_DB, int & count, const string key); //removes an item from the list void Double_size(call_record * &call_DB, int & count, int & size); void Process(call_record *call_DB, const int & count); void Print(const call_record *call_DB, int & count); //prints all the elements in the list to the screen void Destroy_call_DB(call_record * &call_DB); //de-allocates all memory allocate to call_DB by operator new. /************************************************************************************************************************************/ //Name: Initialize //Precondition: The varialbes firstname, lastname, cell_num, relays, and call_length have not been initialized //Postcondition: The variables have been initialized by data file. //Decription: Reads the data file of call information (firstname, lastname, cell number, relays and call length) into the dynamic array of call record, //call_DB. If the count because equal to the size the function double_size is called and the memory allocated to call_DB is doubled. /************************************************************************************************************************************/ void Initialize(call_record * & call_DB, int & count, int & size) { ifstream in; //input file stream object declaration in.open("callstats_data.txt"); //bind the file "call_data.txt" to the input count = 0; //remember to initialize count before the first come if (in.fail()) //if file not found print message and exit program { cout << "Input file did not open correctly" << endl; exit(1); } //Remember to use a while loop when reading from a file because //you do not know how many records you will be reading. while (!in.eof()) { if (Is_full(count, size)) { Double_size(call_DB, count, size); } in >> call_DB[count].firstname; in >> call_DB[count].lastname; in >> call_DB[count].cell_number; in >> call_DB[count].relays; in >> call_DB[count].call_length; count++; } in.close();//file stream "in" closes. } /***********************************************************************************************************************************/ //Name: Is_empty //Precondition: Checks to see if call_DB is empty //Postcondition: call_DB status verifeid. //Decription: returns true if call_DB is empty /**********************************************************************************************************************************/ //ONE WAY TO MAKE A FUNCTION INLINE IS TO PUT THE KEYWORD "inline" in from of the //FUNCTION HEADER AS SHOWN BELOW: inline bool Is_empty(const int count) { if (count == 0){ return 0; } else { return -1; } } //ONE WAY TO MAKE A FUNCTION INLINE IS TO PUT THE KEYWORD "inline" in from of the //FUNCTION HEADER AS SHOWN BELOW: /**********************************************************************************************************************************/ //Name: Is_full //Precondition: Checks to see if call_DB is full //Postcondition: call_DB status verifeid. //Decription: returns true if call_DB is full /*********************************************************************************************************************************/ inline bool Is_full(const int count, int size) { if (count == size){ return 0; } else { return -1; } } /**********************************************************************************************************************************/ //Name: search //Precondition: Checks to see if there is a call_DB //Postcondition: call_DB status verifeid. //Decription: locates key in call_DB if it is there; otherwise -1 is returned /*********************************************************************************************************************************/ int Search(const call_record *call_DB, const int count, const string key) { for (int i = 0; i < count; i++){ if (call_DB[i].cell_number == key) { return i; } else { return -1; } } return 0; } /*********************************************************************************************************************************/ //Name: Add //Precondition: Checks memory of call_DB //Postcondition: Increase call_DB size if full. //Decription: add key to call_DB; if call_DB is full, double_size is called to increase the size of call_DB. /********************************************************************************************************************************/ void Add(call_record * &call_DB, int & count, int & size, const string key) { int index = count; if (Is_full(count, size)) { Double_size(call_DB, count, size); call_DB[index].cell_number = key; std::cout << "Enter First Name" << '\n'; std::cin >> call_DB[index].firstname; std::cout << "Enter Last Name" << '\n'; std::cin >> call_DB[index].lastname; std::cout << "Enter number of Relays" << '\n'; std::cin >> call_DB[index].relays; std::cout << "Enter Call Length" << '\n'; std::cin >> call_DB[index].call_length; count++; } return; } /********************************************************************************************************************************/ //Name: Remove //Precondition: Checks location of call_DB //Postcondition: call_DB is removed if exists. //Decription: remove key from call_DB if it is there. /*******************************************************************************************************************************/ void Remove(call_record *call_DB, int & count, const string key) { if (Is_empty(count) == 0) { return; } int location = Search(call_DB, count, key); if (location == -1) { std::cout << "Location" << location << '\n'; return; } else if (location != -1){ for (int j = location; j < count - 1; j++) { call_DB[j] = call_DB[j+1]; } count = count - 1; } } /******************************************************************************************************************************/ //Name: Double_Size //Precondition: Checks capacity of call_DB //Postcondition: capacity doubled. //Decription: doubles the size (capacity) of call_DB /******************************************************************************************************************************/ void Double_size(call_record * &call_DB, int & count, int & size) { size *= 2; call_record * temp = new call_record[size]; for (int i = 0; i < count; i++) { temp[i] = call_DB[i]; } std::cout << "Size: " << size << '\n'; delete[] call_DB; call_DB = temp; return; } /******************************************************************************************************************************/ //Name: Process //Precondition: The variables have been initialized by the data file. //Postcondition: Conditional statements initialize relay variables. //Decription: calculate the net cost, tax rate, call tax and total cost for every call record in call_DB. /*****************************************************************************************************************************/ void Process(call_record *call_DB, const int & count) { //Remember to use a "for" loop when you know how many items //you will be processing. Use the dot operator when you are //accessing fields in a record. For example, when we need //to access the relay field in the first record in the array use //call_DB[0].relay for (int i = 0; i < count; i++) { call_DB[i].net_cost = call_DB[i].relays / 50.0 * .40 * call_DB[i].call_length; call_DB[i].call_tax = call_DB[i].net_cost * call_DB[i].tax_rate; call_DB[i].total_cost = call_DB[i].net_cost + call_DB[i].call_tax; //Conditional statements to determine tax rates if (call_DB[i].relays <= 0 && call_DB[i].relays <=5) { call_DB[i].tax_rate = 0.01; } else if (call_DB[i].relays <= 6 && call_DB[i].relays <=11) { call_DB[i].tax_rate = 0.03; } else if (call_DB[i].relays <= 12 && call_DB[i].relays <=20) { call_DB[i].tax_rate = 0.05; } else if (call_DB[i].relays <= 21 && call_DB[i].relays <=50) { call_DB[i].tax_rate = 0.08; } else { call_DB[i].tax_rate = 0.12; } } return; } /****************************************************************************************************************************/ //Name: Print //Precondition: The variables have been initialized and calculated //Postcondition: Results are displayed. //Decription: prints every field of every call_record in call_DB formatted to the screen. /***************************************************************************************************************************/ void Print(const call_record *call_DB, int & count) { ofstream out; //declare the output file stream "out". //bind the file "weekly4_call_info.txt" to //to the output file stream "out". out.open("weekly5_call_info.txt"); //Magic Formula out.setf(ios::showpoint); out.precision(2); out.setf(ios::fixed); if (out.fail()) // if problem opening file, print message and exit program { cout << "Output file did not open correctly" << endl; exit(1); } // use a "for" loop here to // print the output to file for (int i = 0; i < count; i++) { out << "First Name " <<call_DB[i].firstname<<" "<<endl; out << "Last Name " <<call_DB[i].lastname<<" "<<endl; out << "Cell Phone " <<call_DB[i].cell_number<<" "<<endl; out << "Number of Relay Stations " <<call_DB[i].relays<<" "<<endl; out << "Minutes Used " <<call_DB[i].call_length<<endl; out << "Net Cost " <<call_DB[i].net_cost<<endl; out << "Tax Rate " <<call_DB[i].tax_rate<<endl; out << "Call Tax " <<call_DB[i].call_tax<<endl; out << "Total Cost of Call " <<call_DB[i].total_cost<<endl<<endl; } out.close(); return; } /****************************************************************************************************************************/ //Name: Destroy_call_DB //Precondition: Checks to see if call_DB exists //Postcondition: Deletes call_DB. //Decription: de-allocates all memory allocated to call_DB. This should be the last function to be called before the program // is exited. /***************************************************************************************************************************/ void Destroy_call_DB(call_record * &call_DB) { delete[] call_DB; return; } //Main Function int main() { int size = 5; //total amount of memory (cells) allocated for the dynamic array of call records int count = 0; call_record *call_DB = new call_record[size]; string key; //put code here to test your funcitons Initialize(call_DB, count, size); Is_empty(count); //inline implementation Is_full(count, size);//inline implementation Search(call_DB, count, key);//returns location if item in listl; otherwise return -1 Add(call_DB, count, size, key); //adds item inorder to the list Remove(call_DB, count, key); //removes an item from the list Double_size(call_DB, count, size); Process(call_DB, count); Print(call_DB, count); //prints all the elements in the list to the screen Destroy_call_DB(call_DB); //de-allocates all memory allocate to call_DB by operator new. return 0; }
44.431973
152
0.548572
juan2357
122c7874cc4a80a35bbb7aeb6e489bef86c8e356
837
cpp
C++
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
libraries/clock/rtcClock.cpp
PetrakovKirill/nixie_hrono
0eff6aa253b84294dd41c6f233a00dd035514b07
[ "MIT" ]
null
null
null
#include "rtc_clock.h" #include <stdio.h> #define SEC_24_HOURS (86400) #define SEC_1_HOUR ( 3600) #define SEC_1_MIN ( 60) rtcClock :: rtcClock(display *pDisplay, rtc *pRtc) { displ = pDisplay; time = pRtc; } void rtcClock :: ShowTime(void) { char printString[5] = {0}; uint32_t currentTime; uint16_t hour, min; time->ReadTime(); currentTime = time->GetTime(); hour = (currentTime % SEC_24_HOURS) / SEC_1_HOUR; min = (currentTime % SEC_1_HOUR) / SEC_1_MIN; snprintf(printString, sizeof(printString), "%02u%02u", hour, min); displ->Print(printString); } void rtcClock :: SetTime(uint32_t seconds) { time->SetTime(seconds); } uint32_t rtcClock :: GetTime(void) { return (time->GetTime()); }
19.465116
59
0.590203
PetrakovKirill
122e0365a281223a404404f59426e148cd88636f
3,356
cpp
C++
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
examples/07-editor.cpp
cyrilcode/cyfw-examples
18fde906b606ff0b9e589a4ef53125186fe5a578
[ "MIT" ]
null
null
null
#include <cyfw/main.h> #include <cyfw/Gui.h> #include <Resource.h> using namespace std; using namespace cy; class MyApp : public cy::App { Gui gui; bool guiOpen; char text[1024*16]; bool escPressed; bool shouldQuit; ImFont* font1; public: MyApp() : escPressed{false}, shouldQuit{false} { char * t = "rotate\nbox\0"; memcpy(text, t, 11); Resource fontdata = LOAD_RESOURCE(a_scp_r_ttf); auto font_cfg_template = ImFontConfig(); font_cfg_template.FontDataOwnedByAtlas = false; font1 = ImGui::GetIO().Fonts->AddFontFromMemoryTTF( (void*)fontdata.begin(), fontdata.size(), 32, &font_cfg_template); } void setup() { window->closeOnEscapeKey(false); window->setClearColor({0,0,0,1}); gui.init(window); ImGuiStyle& style = ImGui::GetStyle(); style.WindowRounding = 0; style.WindowPadding = {0, 0}; style.Colors[ImGuiCol_Text] = {1,1,1,1}; style.Colors[ImGuiCol_WindowBg] = {0,0,0,0}; style.Colors[ImGuiCol_FrameBg] = {0,0,0,0}; } void draw() { window->clear(); gui.clear(); doGui(); gui.draw(); } void doGui() { ImGui::SetNextWindowPos(ImVec2(10,10)); ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse; if (!ImGui::Begin("Buffer", &guiOpen, windowFlags)) { ImGui::End(); return; } ImGui::PushFont(font1); vec2i dim = window->getWindowSize(); ImGui::SetWindowSize(ImVec2(dim.x() - 20, dim.y() - 20)); ImGui::InputTextMultiline("source", text, sizeof(text), ImVec2(-1.0f, -1.0f), 0); if (escPressed) ImGui::OpenPopup("Quit?"); if (ImGui::BeginPopupModal("Quit?", NULL, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove)) { ImGui::SetWindowFontScale(1.0f); ImGui::Text("Are you sure you want to quit?\n\n"); ImGui::Separator(); if (ImGui::Button("Quit", ImVec2(120,0))) { escPressed = false; shouldQuit = true; window->quit(); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel", ImVec2(120,0))) { escPressed = false; window->quit(false); ImGui::CloseCurrentPopup(); } if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::PopFont(); ImGui::End(); } bool quit() { escPressed = true; return shouldQuit; } void key(window::KeyEvent e) { if (e.key == window::key::ESCAPE && e.action == window::action::PRESSED) { escPressed = true; } gui.key(e); } void scroll(window::ScrollEvent e) { gui.scroll(e); } void textInput(window::CharEvent e) { gui.character(e); } void mouseButton(window::MouseButtonEvent e ) { gui.mouse(e); } }; int main() { cy::run<MyApp,ConsoleLogger>(640, 480, "testing editor"); }
28.440678
109
0.546782
cyrilcode
1238246444b1e6a69dd23a19a4a5c6434680c633
5,567
cpp
C++
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
2
2015-04-02T21:45:49.000Z
2018-09-19T01:59:02.000Z
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
SLAM/kalmanSLAM.cpp
Exadios/Bayes-
a1cd9efe2e840506d887bec9b246fd936f2b71e5
[ "MIT" ]
null
null
null
/* * Bayes++ the Bayesian Filtering Library * Copyright (c) 2004 Michael Stevens * See accompanying Bayes++.htm for terms and conditions of use. * * $Id$ */ /* * SLAM : Simultaneous Locatization and Mapping * Kalman filter representing representation of SLAM */ // Bayes++ Bayesian filtering schemes #include "BayesFilter/bayesFlt.hpp" // Bayes++ SLAM #include "SLAM.hpp" #include "kalmanSLAM.hpp" #include <iostream> #include <boost/numeric/ublas/io.hpp> namespace SLAM_filter { template <class Base> inline void zero(FM::ublas::matrix_range<Base> A) // Zero a matrix_range { // Note A cannot be a reference typedef typename Base::value_type Base_value_type; FM::noalias(A) = FM::ublas::scalar_matrix<Base_value_type>(A.size1(),A.size2(), Base_value_type()); } Kalman_SLAM::Kalman_SLAM( Kalman_filter_generator& filter_generator ) : SLAM(), fgenerator(filter_generator), loc(0), full(0) { nL = 0; nM = 0; } Kalman_SLAM::~Kalman_SLAM() { fgenerator.dispose (loc); fgenerator.dispose (full); } void Kalman_SLAM::init_kalman (const FM::Vec& x, const FM::SymMatrix& X) { // TODO maintain map states nL = x.size(); nM = 0; if (loc) fgenerator.dispose (loc); if (full) fgenerator.dispose (full); // generate a location filter for prediction loc = fgenerator.generate(nL); // generate full filter full = fgenerator.generate(nL); // initialise location states full->x.sub_range(0,nL) = x; full->X.sub_matrix(0,nL,0,nL) = X; full->init(); } void Kalman_SLAM::predict( BF::Linrz_predict_model& lpred ) { // extract location part of full loc->x = full->x.sub_range(0,nL); loc->X = full->X.sub_matrix(0,nL,0,nL); // predict location, independent of map loc->init(); loc->predict (lpred); loc->update(); // return location to full full->x.sub_range(0,nL) = loc->x; full->X.sub_matrix(0,nL,0,nL) = loc->X; full->init(); } void Kalman_SLAM::observe( unsigned feature, const Feature_observe& fom, const FM::Vec& z ) { // Assume features added sequentially if (feature >= nM) { error (BF::Logic_exception("Observe non existing feature")); return; } // TODO Implement nonlinear form // Create a augmented sparse observe model for full states BF::Linear_uncorrelated_observe_model fullm(full->x.size(), 1); fullm.Hx.clear(); fullm.Hx.sub_matrix(0,nL, 0,nL) = fom.Hx.sub_matrix(0,nL, 0,nL); fullm.Hx(0,nL+feature) = fom.Hx(0,nL); fullm.Zv = fom.Zv; full->observe(fullm, z); } void Kalman_SLAM::observe_new( unsigned feature, const Feature_observe_inverse& fom, const FM::Vec& z ) // fom: must have a the special form required for SLAM::obeserve_new { // size consistency, single state feature if (fom.Hx.size1() != 1) error (BF::Logic_exception("observation and model size inconsistent")); // make new filter with additional (uninitialized) feature state if (feature >= nM) { nM = feature+1; Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+nM); FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x; FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X; fgenerator.dispose(full); full = nf; } // build augmented location and observation FM::Vec sz(nL+z.size()); sz.sub_range(0,nL) = full->x.sub_range(0,nL); sz.sub_range(nL,nL+z.size() )= z; // TODO use named references rather then explict Ha Hb FM::Matrix Ha (fom.Hx.sub_matrix(0,1, 0,nL) ); FM::Matrix Hb (fom.Hx.sub_matrix(0,1, nL,nL+z.size()) ); FM::Matrix tempHa (1,nL); FM::Matrix tempHb (1,sz.size()); // feature covariance with existing location and features // X+ = [0 Ha] X [0 Ha]' + Hb Z Hb' // - zero existing feature covariance zero( full->X.sub_matrix(0,full->X.size1(), nL+feature,nL+feature+1) ); full->X.sub_matrix(nL+feature,nL+feature+1,0,nL+nM) = FM::prod(Ha,full->X.sub_matrix(0,nL, 0,nL+nM) ); // feature state and variance full->x[nL+feature] = fom.h(sz)[0]; full->X(nL+feature,nL+feature) = ( FM::prod_SPD(Ha,full->X.sub_matrix(0,nL, 0,nL),tempHa) + FM::prod_SPD(Hb,fom.Zv,tempHb) ) (0,0); full->init (); } void Kalman_SLAM::observe_new( unsigned feature, const FM::Float& t, const FM::Float& T ) { // Make space in scheme for feature, requires the scheme can deal with resized state if (feature >= nM) { Kalman_filter_generator::Filter_type* nf = fgenerator.generate(nL+feature+1); FM::noalias(nf->x.sub_range(0,full->x.size())) = full->x; FM::noalias(nf->X.sub_matrix(0,full->x.size(),0,full->x.size())) = full->X; zero( nf->X.sub_matrix(0,nf->X.size1(), nL+nM,nf->X.size2()) ); nf->x[nL+feature] = t; nf->X(nL+feature,nL+feature) = T; nf->init (); fgenerator.dispose(full); full = nf; nM = feature+1; } else { full->x[nL+feature] = t; full->X(nL+feature,nL+feature) = T; full->init (); } } void Kalman_SLAM::forget( unsigned feature, bool must_exist ) { full->x[nL+feature] = 0.; // ISSUE uBLAS has problems accessing the lower symmetry via a sub_matrix proxy, there two two parts seperately zero( full->X.sub_matrix(0,nL+feature, nL+feature,nL+feature+1) ); zero( full->X.sub_matrix(nL+feature,nL+feature+1, nL+feature,full->X.size1()) ); full->init(); } void Kalman_SLAM::decorrelate( Bayesian_filter::Bayes_base::Float d ) // Reduce correlation by scaling cross-correlation terms { std::size_t i,j; const std::size_t n = full->X.size1(); for (i = 1; i < n; ++i) { FM::SymMatrix::Row Xi(full->X,i); for (j = 0; j < i; ++j) { Xi[j] *= d; } for (j = i+1; j < n; ++j) { Xi[j] *= d; } } full->init(); } }//namespace SLAM
28.548718
114
0.668762
Exadios
72f3015cd3c5e5c58ff6aae96895e781fb045bbe
275
cpp
C++
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
service/src/log.cpp
SibirCTF/2016-service-loogles
0a5a834fc38c6eb8b9a19d780655b377b2c54653
[ "MIT" ]
null
null
null
#include "log.h" #include <iostream> void Log::i(QString tag, QString message){ std::cout << tag.toStdString() << " " << message.toStdString() << "\n"; } void Log::e(QString tag, QString message){ std::cerr << tag.toStdString() << " " << message.toStdString() << "\n"; }
25
72
0.618182
SibirCTF
72fe0f933d4d81e493dcce8390c0bb2d8df81482
7,838
cpp
C++
cpp/tests/strings/chars_types_tests.cpp
IbrahimBRammaha/cudf
57ddd5ed0cd7a24500adfc208a08075843f70979
[ "Apache-2.0" ]
1
2020-04-18T23:47:25.000Z
2020-04-18T23:47:25.000Z
cpp/tests/strings/chars_types_tests.cpp
benfred/cudf
3cd4c9f0602840dddb9a0e247d5a0bcf3d7266e1
[ "Apache-2.0" ]
null
null
null
cpp/tests/strings/chars_types_tests.cpp
benfred/cudf
3cd4c9f0602840dddb9a0e247d5a0bcf3d7266e1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019-2020, NVIDIA 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. */ #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/strings/char_types/char_types.hpp> #include <tests/utilities/base_fixture.hpp> #include <tests/utilities/column_wrapper.hpp> #include <tests/utilities/column_utilities.hpp> #include <tests/strings/utilities.h> #include <vector> struct StringsCharsTest : public cudf::test::BaseFixture {}; class StringsCharsTestTypes : public StringsCharsTest, public testing::WithParamInterface<cudf::strings::string_character_types> {}; TEST_P(StringsCharsTestTypes, AllTypes) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; bool expecteds[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, // decimal 0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0, // numeric 0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0, // digit 1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0, // alpha 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, // space 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, // upper 0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0 }; // lower auto is_parm = GetParam(); cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::all_characters_of_type(strings_view,is_parm); int x = static_cast<int>(is_parm); int index = 0; int strings_count = static_cast<int>(h_strings.size()); while( x >>= 1 ) ++index; bool* sub_expected = &expecteds[index * strings_count]; cudf::test::fixed_width_column_wrapper<bool> expected( sub_expected, sub_expected + strings_count, thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } INSTANTIATE_TEST_CASE_P(StringsCharsTestAllTypes, StringsCharsTestTypes, testing::ValuesIn(std::array<cudf::strings::string_character_types,7> { cudf::strings::string_character_types::DECIMAL, cudf::strings::string_character_types::NUMERIC, cudf::strings::string_character_types::DIGIT, cudf::strings::string_character_types::ALPHA, cudf::strings::string_character_types::SPACE, cudf::strings::string_character_types::UPPER, cudf::strings::string_character_types::LOWER })); TEST_F(StringsCharsTest, LowerUpper) { cudf::test::strings_column_wrapper strings( {"a1","A1","a!","A!","!1","aA"} ); auto strings_view = cudf::strings_column_view(strings); auto verify_types = cudf::strings::string_character_types::LOWER | cudf::strings::string_character_types::UPPER; { auto results = cudf::strings::all_characters_of_type(strings_view, cudf::strings::string_character_types::LOWER, verify_types); cudf::test::fixed_width_column_wrapper<bool> expected( {1,0,1,0,0,0} ); cudf::test::expect_columns_equal(*results,expected); } { auto results = cudf::strings::all_characters_of_type(strings_view, cudf::strings::string_character_types::UPPER, verify_types); cudf::test::fixed_width_column_wrapper<bool> expected( {0,1,0,1,0,0} ); cudf::test::expect_columns_equal(*results,expected); } } TEST_F(StringsCharsTest, Alphanumeric) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::all_characters_of_type(strings_view,cudf::strings::string_character_types::ALPHANUM); std::vector<bool> h_expected{ 1,1,0,1,0,0,0,0,0,1,1,1,0,1,1,0 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, AlphaNumericSpace) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto types = cudf::strings::string_character_types::ALPHANUM | cudf::strings::string_character_types::SPACE; auto results = cudf::strings::all_characters_of_type(strings_view, (cudf::strings::string_character_types)types); std::vector<bool> h_expected{ 1,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, Numerics) { std::vector<const char*> h_strings{ "Héllo", "thesé", nullptr, "HERE", "tést strings", "", "1.75", "-34", "+9.8", "17¼", "x³", "2³", " 12⅝", "1234567890", "de", "\t\r\n\f "}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); auto strings_view = cudf::strings_column_view(strings); auto types = cudf::strings::string_character_types::DIGIT | cudf::strings::string_character_types::DECIMAL | cudf::strings::string_character_types::NUMERIC; auto results = cudf::strings::all_characters_of_type(strings_view, (cudf::strings::string_character_types)types); std::vector<bool> h_expected{ 0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0 }; cudf::test::fixed_width_column_wrapper<bool> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator( h_strings.begin(), [] (auto str) { return str!=nullptr; })); cudf::test::expect_columns_equal(*results,expected); } TEST_F(StringsCharsTest, EmptyStringsColumn) { cudf::column_view zero_size_strings_column( cudf::data_type{cudf::STRING}, 0, nullptr, nullptr, 0); auto strings_view = cudf::strings_column_view(zero_size_strings_column); auto results = cudf::strings::all_characters_of_type(strings_view,cudf::strings::string_character_types::ALPHANUM); auto view = results->view(); EXPECT_EQ(cudf::BOOL8, view.type().id()); EXPECT_EQ(0,view.size()); EXPECT_EQ(0,view.null_count()); EXPECT_EQ(0,view.num_children()); }
47.216867
119
0.666114
IbrahimBRammaha
f40922ee3bec89387527ae072474ccee975d5071
33,388
cpp
C++
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
3
2018-09-03T20:55:24.000Z
2020-10-04T04:36:30.000Z
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
4
2018-09-06T04:12:41.000Z
2020-10-06T14:43:14.000Z
app_skeleton_shadow.cpp
blu/hello-chromeos-gles2
6ab863b734e053eef3b0185d17951353a49db359
[ "MIT" ]
null
null
null
#if PLATFORM_GL #include <GL/gl.h> #include <GL/glext.h> #include "gles_gl_mapping.hpp" #else #include <EGL/egl.h> #include <GLES3/gl3.h> #include "gles_ext.h" #if GL_OES_depth_texture == 0 #error Missing required extension GL_OES_depth_texture. #endif #if GL_OES_depth24 == 0 #error Missing required extension GL_OES_depth24. #endif #if GL_OES_packed_depth_stencil == 0 #error Missing required extension GL_OES_packed_depth_stencil. #endif #endif // PLATFORM_GL #include <unistd.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <cmath> #include <string> #include <sstream> #include "scoped.hpp" #include "stream.hpp" #include "vectsimd.hpp" #include "rendIndexedTrilist.hpp" #include "rendSkeleton.hpp" #include "util_tex.hpp" #include "util_misc.hpp" #include "pure_macro.hpp" #include "rendVertAttr.hpp" using util::scoped_ptr; using util::scoped_functor; using util::deinit_resources_t; namespace sk { #define SETUP_VERTEX_ATTR_POINTERS_MASK ( \ SETUP_VERTEX_ATTR_POINTERS_MASK_vertex | \ SETUP_VERTEX_ATTR_POINTERS_MASK_normal | \ SETUP_VERTEX_ATTR_POINTERS_MASK_blendw | \ SETUP_VERTEX_ATTR_POINTERS_MASK_tcoord) #include "rendVertAttr_setupVertAttrPointers.hpp" #undef SETUP_VERTEX_ATTR_POINTERS_MASK struct Vertex { GLfloat pos[3]; GLfloat bon[4]; GLfloat nrm[3]; GLfloat txc[2]; }; } // namespace sk namespace st { #define SETUP_VERTEX_ATTR_POINTERS_MASK ( \ SETUP_VERTEX_ATTR_POINTERS_MASK_vertex) #include "rendVertAttr_setupVertAttrPointers.hpp" #undef SETUP_VERTEX_ATTR_POINTERS_MASK struct Vertex { GLfloat pos[3]; }; } // namespace st #define DRAW_SKELETON 0 #define DEPTH_PRECISION_24 0 namespace { // anonymous const char arg_prefix[] = "-"; const char arg_app[] = "app"; const char arg_normal[] = "normal_map"; const char arg_albedo[] = "albedo_map"; const char arg_anim_step[] = "anim_step"; const char arg_shadow_res[] = "shadow_res"; struct TexDesc { const char* filename; unsigned w; unsigned h; }; TexDesc g_normal = { "asset/texture/unperturbed_normal.raw", 8, 8 }; TexDesc g_albedo = { "none", 16, 16 }; float g_anim_step = .0125f; simd::matx4 g_matx_fit; const unsigned fbo_default_res = 2048; GLsizei g_fbo_res = fbo_default_res; enum { BONE_CAPACITY = 32 }; unsigned g_bone_count; rend::Bone g_bone[BONE_CAPACITY + 1]; rend::Bone* g_root_bone = g_bone + BONE_CAPACITY; rend::dense_matx4 g_bone_mat[BONE_CAPACITY]; std::vector< std::vector< rend::Track > > g_animations; std::vector< float > g_durations; } // namespace namespace anim { static std::vector< std::vector< rend::Track > >::const_iterator at; static std::vector< float >::const_iterator dt; static float animTime; static float duration; } // namespace anim namespace { // anonymous #if DRAW_SKELETON st::Vertex g_stick[BONE_CAPACITY][2]; #endif #if PLATFORM_EGL EGLDisplay g_display = EGL_NO_DISPLAY; EGLContext g_context = EGL_NO_CONTEXT; #endif enum { TEX_NORMAL, TEX_ALBEDO, TEX_SHADOW, TEX_COUNT, TEX_FORCE_UINT = -1U }; enum { PROG_SKIN, PROG_SKEL, PROG_SHADOW, PROG_COUNT, PROG_FORCE_UINT = -1U }; enum { UNI_SAMPLER_NORMAL, UNI_SAMPLER_ALBEDO, UNI_SAMPLER_SHADOW, UNI_LP_OBJ, UNI_VP_OBJ, UNI_SOLID_COLOR, UNI_BONE, UNI_MVP, UNI_MVP_LIT, UNI_COUNT, UNI_FORCE_UINT = -1U }; enum { MESH_SKIN, MESH_COUNT, MESH_FORCE_UINT = -1U }; enum { VBO_SKIN_VTX, VBO_SKIN_IDX, VBO_SKEL_VTX, /* VBO_SKEL_IDX not required */ VBO_COUNT, VBO_FORCE_UINT = -1U }; GLint g_uni[PROG_COUNT][UNI_COUNT]; #if PLATFORM_GL_OES_vertex_array_object GLuint g_vao[PROG_COUNT]; #endif GLuint g_fbo; // single GLuint g_tex[TEX_COUNT]; GLuint g_vbo[VBO_COUNT]; GLuint g_shader_vert[PROG_COUNT]; GLuint g_shader_frag[PROG_COUNT]; GLuint g_shader_prog[PROG_COUNT]; unsigned g_num_faces[MESH_COUNT]; GLenum g_index_type; rend::ActiveAttrSemantics g_active_attr_semantics[PROG_COUNT]; } // namespace bool hook::set_num_drawcalls( const unsigned) { return false; } unsigned hook::get_num_drawcalls() { return 1; } bool hook::requires_depth() { return true; } static bool parse_cli( const unsigned argc, const char* const* argv) { bool cli_err = false; const unsigned prefix_len = strlen(arg_prefix); for (unsigned i = 1; i < argc && !cli_err; ++i) { if (strncmp(argv[i], arg_prefix, prefix_len) || strcmp(argv[i] + prefix_len, arg_app)) { continue; } if (++i < argc) { if (i + 3 < argc && !strcmp(argv[i], arg_normal)) { if (1 == sscanf(argv[i + 2], "%u", &g_normal.w) && 1 == sscanf(argv[i + 3], "%u", &g_normal.h)) { g_normal.filename = argv[i + 1]; i += 3; continue; } } else if (i + 3 < argc && !strcmp(argv[i], arg_albedo)) { if (1 == sscanf(argv[i + 2], "%u", &g_albedo.w) && 1 == sscanf(argv[i + 3], "%u", &g_albedo.h)) { g_albedo.filename = argv[i + 1]; i += 3; continue; } } else if (i + 1 < argc && !strcmp(argv[i], arg_anim_step)) { if (1 == sscanf(argv[i + 1], "%f", &g_anim_step) && 0.f < g_anim_step) { i += 1; continue; } } else if (i + 1 < argc && !strcmp(argv[i], arg_shadow_res)) { if (1 == sscanf(argv[i + 1], "%u", &g_fbo_res) && 0 == (g_fbo_res & g_fbo_res - 1)) { i += 1; continue; } } } cli_err = true; } if (cli_err) { stream::cerr << "app options:\n" "\t" << arg_prefix << arg_app << " " << arg_normal << " <filename> <width> <height>\t: use specified raw file and dimensions as source of normal map\n" "\t" << arg_prefix << arg_app << " " << arg_albedo << " <filename> <width> <height>\t: use specified raw file and dimensions as source of albedo map\n" "\t" << arg_prefix << arg_app << " " << arg_anim_step << " <step>\t\t\t\t: use specified animation step; entire animation is 1.0\n" "\t" << arg_prefix << arg_app << " " << arg_shadow_res << " <pot>\t\t\t\t: use specified shadow buffer resolution (POT); default is " << fbo_default_res << "\n\n"; } return !cli_err; } namespace { // anonymous template < unsigned PROG_T > inline bool bindVertexBuffersAndPointers() { assert(false); return false; } template <> inline bool bindVertexBuffersAndPointers< PROG_SKIN >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKIN_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_vbo[VBO_SKIN_IDX]); DEBUG_GL_ERR() return sk::setupVertexAttrPointers< sk::Vertex >(g_active_attr_semantics[PROG_SKIN]); } #if DRAW_SKELETON template <> inline bool bindVertexBuffersAndPointers< PROG_SKEL >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); DEBUG_GL_ERR() return st::setupVertexAttrPointers< st::Vertex >(g_active_attr_semantics[PROG_SKEL]); } #endif // DRAW_SKELETON template <> inline bool bindVertexBuffersAndPointers< PROG_SHADOW >() { glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKIN_VTX]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_vbo[VBO_SKIN_IDX]); DEBUG_GL_ERR() return sk::setupVertexAttrPointers< sk::Vertex >(g_active_attr_semantics[PROG_SHADOW]); } bool check_context( const char* prefix) { bool context_correct = true; #if PLATFORM_EGL if (g_display != eglGetCurrentDisplay()) { stream::cerr << prefix << " encountered foreign display\n"; context_correct = false; } if (g_context != eglGetCurrentContext()) { stream::cerr << prefix << " encountered foreign context\n"; context_correct = false; } #endif return context_correct; } } // namespace bool hook::deinit_resources() { if (!check_context(__FUNCTION__)) return false; for (unsigned i = 0; i < sizeof(g_shader_prog) / sizeof(g_shader_prog[0]); ++i) { glDeleteProgram(g_shader_prog[i]); g_shader_prog[i] = 0; } for (unsigned i = 0; i < sizeof(g_shader_vert) / sizeof(g_shader_vert[0]); ++i) { glDeleteShader(g_shader_vert[i]); g_shader_vert[i] = 0; } for (unsigned i = 0; i < sizeof(g_shader_frag) / sizeof(g_shader_frag[0]); ++i) { glDeleteShader(g_shader_frag[i]); g_shader_frag[i] = 0; } glDeleteFramebuffers(1, &g_fbo); g_fbo = 0; glDeleteTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex); memset(g_tex, 0, sizeof(g_tex)); #if PLATFORM_GL_OES_vertex_array_object glDeleteVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao); memset(g_vao, 0, sizeof(g_vao)); #endif glDeleteBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo); memset(g_vbo, 0, sizeof(g_vbo)); #if PLATFORM_EGL g_display = EGL_NO_DISPLAY; g_context = EGL_NO_CONTEXT; #endif return true; } namespace { // anonymous #if DEBUG && PLATFORM_GL_KHR_debug void debugProc( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { fprintf(stderr, "log: %s\n", message); } #endif } // namespace bool hook::init_resources( const unsigned argc, const char* const * argv) { if (!parse_cli(argc, argv)) return false; #if DEBUG && PLATFORM_GL_KHR_debug glDebugMessageCallbackKHR(debugProc, NULL); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR); glEnable(GL_DEBUG_OUTPUT_KHR); DEBUG_GL_ERR() glDebugMessageInsertKHR( GL_DEBUG_SOURCE_APPLICATION_KHR, GL_DEBUG_TYPE_OTHER_KHR, GLuint(42), GL_DEBUG_SEVERITY_HIGH_KHR, GLint(-1), "testing 1, 2, 3"); DEBUG_GL_ERR() #endif #if PLATFORM_EGL g_display = eglGetCurrentDisplay(); if (EGL_NO_DISPLAY == g_display) { stream::cerr << __FUNCTION__ << " encountered nil display\n"; return false; } g_context = eglGetCurrentContext(); if (EGL_NO_CONTEXT == g_context) { stream::cerr << __FUNCTION__ << " encountered nil context\n"; return false; } #endif scoped_ptr< deinit_resources_t, scoped_functor > on_error(deinit_resources); ///////////////////////////////////////////////////////////////// // set up various patches to the shaders std::ostringstream patch_res[2]; patch_res[0] << "const float shadow_res = " << fbo_default_res << ".0;"; patch_res[1] << "const float shadow_res = " << g_fbo_res << ".0;"; const std::string patch[] = { patch_res[0].str(), patch_res[1].str() }; ///////////////////////////////////////////////////////////////// // set up misc control bits and values glEnable(GL_CULL_FACE); const GLclampf red = 0.f; const GLclampf green = 0.f; const GLclampf blue = 0.f; const GLclampf alpha = 0.f; glClearColor(red, green, blue, alpha); glClearDepthf(1.f); // for shadow map generation: push back by 64 ULPs glPolygonOffset(1.f, 64.f); ///////////////////////////////////////////////////////////////// // reserve all necessary texture objects glGenTextures(sizeof(g_tex) / sizeof(g_tex[0]), g_tex); for (unsigned i = 0; i < sizeof(g_tex) / sizeof(g_tex[0]); ++i) assert(g_tex[i]); ///////////////////////////////////////////////////////////////// // load textures if (!util::setupTexture2D(g_tex[TEX_NORMAL], g_normal.filename, g_normal.w, g_normal.h)) { stream::cerr << __FUNCTION__ << " failed at setupTexture2D\n"; return false; } if (!util::setupTexture2D(g_tex[TEX_ALBEDO], g_albedo.filename, g_albedo.w, g_albedo.h)) { stream::cerr << __FUNCTION__ << " failed at setupTexture2D\n"; return false; } ///////////////////////////////////////////////////////////////// // init the program/uniforms matrix to all empty for (unsigned i = 0; i < PROG_COUNT; ++i) for (unsigned j = 0; j < UNI_COUNT; ++j) g_uni[i][j] = -1; ///////////////////////////////////////////////////////////////// // create shader program SKIN from two shaders g_shader_vert[PROG_SKIN] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SKIN]); if (!util::setupShader(g_shader_vert[PROG_SKIN], "asset/shader/blinn_shadow_skinning.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SKIN] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SKIN]); if (!util::setupShaderWithPatch(g_shader_frag[PROG_SKIN], "asset/shader/blinn_shadow.glslf", sizeof(patch) / sizeof(patch[0]) / 2, patch)) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SKIN] = glCreateProgram(); assert(g_shader_prog[PROG_SKIN]); if (!util::setupProgram( g_shader_prog[PROG_SKIN], g_shader_vert[PROG_SKIN], g_shader_frag[PROG_SKIN])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SKIN][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "mvp"); g_uni[PROG_SKIN][UNI_MVP_LIT] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "mvp_lit"); g_uni[PROG_SKIN][UNI_BONE] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "bone"); g_uni[PROG_SKIN][UNI_LP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "lp_obj"); g_uni[PROG_SKIN][UNI_VP_OBJ] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "vp_obj"); g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "normal_map"); g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "albedo_map"); g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW] = glGetUniformLocation(g_shader_prog[PROG_SKIN], "shadow_map"); g_active_attr_semantics[PROG_SKIN].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Vertex")); g_active_attr_semantics[PROG_SKIN].registerNormalAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Normal")); g_active_attr_semantics[PROG_SKIN].registerBlendWAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_Weight")); g_active_attr_semantics[PROG_SKIN].registerTCoordAttr(glGetAttribLocation(g_shader_prog[PROG_SKIN], "at_MultiTexCoord0")); ///////////////////////////////////////////////////////////////// // create shader program SKEL from two shaders g_shader_vert[PROG_SKEL] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SKEL]); if (!util::setupShader(g_shader_vert[PROG_SKEL], "asset/shader/mvp.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SKEL] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SKEL]); if (!util::setupShader(g_shader_frag[PROG_SKEL], "asset/shader/basic.glslf")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SKEL] = glCreateProgram(); assert(g_shader_prog[PROG_SKEL]); if (!util::setupProgram( g_shader_prog[PROG_SKEL], g_shader_vert[PROG_SKEL], g_shader_frag[PROG_SKEL])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SKEL][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SKEL], "mvp"); g_uni[PROG_SKEL][UNI_SOLID_COLOR] = glGetUniformLocation(g_shader_prog[PROG_SKEL], "solid_color"); g_active_attr_semantics[PROG_SKEL].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SKEL], "at_Vertex")); ///////////////////////////////////////////////////////////////// // create shader program SHADOW from two shaders g_shader_vert[PROG_SHADOW] = glCreateShader(GL_VERTEX_SHADER); assert(g_shader_vert[PROG_SHADOW]); if (!util::setupShader(g_shader_vert[PROG_SHADOW], "asset/shader/mvp_skinning.glslv")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_frag[PROG_SHADOW] = glCreateShader(GL_FRAGMENT_SHADER); assert(g_shader_frag[PROG_SHADOW]); if (!util::setupShader(g_shader_frag[PROG_SHADOW], "asset/shader/depth.glslf")) { stream::cerr << __FUNCTION__ << " failed at setupShader\n"; return false; } g_shader_prog[PROG_SHADOW] = glCreateProgram(); assert(g_shader_prog[PROG_SHADOW]); if (!util::setupProgram( g_shader_prog[PROG_SHADOW], g_shader_vert[PROG_SHADOW], g_shader_frag[PROG_SHADOW])) { stream::cerr << __FUNCTION__ << " failed at setupProgram\n"; return false; } ///////////////////////////////////////////////////////////////// // query the program about known uniform vars and vertex attribs g_uni[PROG_SHADOW][UNI_MVP] = glGetUniformLocation(g_shader_prog[PROG_SHADOW], "mvp"); g_uni[PROG_SHADOW][UNI_BONE] = glGetUniformLocation(g_shader_prog[PROG_SHADOW], "bone"); g_active_attr_semantics[PROG_SHADOW].registerVertexAttr(glGetAttribLocation(g_shader_prog[PROG_SHADOW], "at_Vertex")); g_active_attr_semantics[PROG_SHADOW].registerBlendWAttr(glGetAttribLocation(g_shader_prog[PROG_SHADOW], "at_Weight")); ///////////////////////////////////////////////////////////////// // load the skeleton for the main geometric asset g_bone_count = BONE_CAPACITY; const char* const skeleton_filename = "asset/mesh/Ahmed_GEO.skeleton"; if (!rend::loadSkeletonAnimationABE(skeleton_filename, &g_bone_count, g_bone_mat, g_bone, g_animations, g_durations)) { stream::cerr << __FUNCTION__ << " failed to load skeleton file " << skeleton_filename << '\n'; return false; } assert(g_animations.size()); assert(g_durations.size()); anim::at = g_animations.begin(); anim::dt = g_durations.begin(); anim::animTime = 0.f; anim::duration = *anim::dt; ///////////////////////////////////////////////////////////////// // reserve VAO (if available) and all necessary VBOs #if PLATFORM_GL_OES_vertex_array_object glGenVertexArraysOES(sizeof(g_vao) / sizeof(g_vao[0]), g_vao); for (unsigned i = 0; i < sizeof(g_vao) / sizeof(g_vao[0]); ++i) assert(g_vao[i]); #endif glGenBuffers(sizeof(g_vbo) / sizeof(g_vbo[0]), g_vbo); for (unsigned i = 0; i < sizeof(g_vbo) / sizeof(g_vbo[0]); ++i) assert(g_vbo[i]); ///////////////////////////////////////////////////////////////// // load the main geometric asset float bbox_min[3]; float bbox_max[3]; const uintptr_t semantics_offset[4] = { offsetof(sk::Vertex, pos), offsetof(sk::Vertex, bon), offsetof(sk::Vertex, nrm), offsetof(sk::Vertex, txc) }; const char* const mesh_filename = "asset/mesh/Ahmed_GEO.mesh"; if (!util::fill_indexed_trilist_from_file_ABE( mesh_filename, g_vbo[VBO_SKIN_VTX], g_vbo[VBO_SKIN_IDX], semantics_offset, g_num_faces[MESH_SKIN], g_index_type, bbox_min, bbox_max)) { stream::cerr << __FUNCTION__ << " failed at fill_indexed_trilist_from_file_ABE\n"; return false; } const float centre[3] = { (bbox_min[0] + bbox_max[0]) * .5f, (bbox_min[1] + bbox_max[1]) * .5f, (bbox_min[2] + bbox_max[2]) * .5f }; const float extent[3] = { (bbox_max[0] - bbox_min[0]) * .5f, (bbox_max[1] - bbox_min[1]) * .5f, (bbox_max[2] - bbox_min[2]) * .5f }; const float rcp_extent = 1.f / fmaxf(fmaxf(extent[0], extent[1]), extent[2]); g_matx_fit = simd::matx4( rcp_extent, 0.f, 0.f, 0.f, 0.f, rcp_extent, 0.f, 0.f, 0.f, 0.f, rcp_extent, 0.f, -centre[0] * rcp_extent, -centre[1] * rcp_extent, -centre[2] * rcp_extent, 1.f); #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // forward-declare VBO_SKEL_VTX; dynamically updated per frame glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBufferData(GL_ARRAY_BUFFER, sizeof(g_stick[0]) * g_bone_count, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); #endif #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKIN]); if (!bindVertexBuffersAndPointers< PROG_SKIN >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SKIN\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #if DRAW_SKELETON glBindVertexArrayOES(g_vao[PROG_SKEL]); if (!bindVertexBuffersAndPointers< PROG_SKEL >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SKEL\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif glBindVertexArrayOES(g_vao[PROG_SHADOW]); if (!bindVertexBuffersAndPointers< PROG_SHADOW >() || (DEBUG_LITERAL && util::reportGLError())) { stream::cerr << __FUNCTION__ << "failed at bindVertexBuffersAndPointers for PROG_SHADOW\n"; return false; } for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() glBindVertexArrayOES(0); #endif ///////////////////////////////////////////////////////////////// // set up the texture to be used as depth in the single FBO glBindTexture(GL_TEXTURE_2D, g_tex[TEX_SHADOW]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #if DEPTH_PRECISION_24 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_OES, g_fbo_res, g_fbo_res, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, 0); #else glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, g_fbo_res, g_fbo_res, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0); #endif if (util::reportGLError()) { stream::cerr << __FUNCTION__ << " failed at shadow texture setup\n"; return false; } glBindTexture(GL_TEXTURE_2D, 0); ///////////////////////////////////////////////////////////////// // set up the single FBO glGenFramebuffers(1, &g_fbo); assert(g_fbo); glBindFramebuffer(GL_FRAMEBUFFER, g_fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, g_tex[TEX_SHADOW], 0); #if DEPTH_PRECISION_24 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, g_tex[TEX_SHADOW], 0); #endif const GLenum fbo_success = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (GL_FRAMEBUFFER_COMPLETE != fbo_success) { stream::cerr << __FUNCTION__ << " failed at glCheckFramebufferStatus\n"; return false; } glDrawBuffers(0, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, 0); on_error.reset(); return true; } class matx4_ortho : public simd::matx4 { matx4_ortho(); matx4_ortho(const matx4_ortho&); public: matx4_ortho( const float l, const float r, const float b, const float t, const float n, const float f) { static_cast< simd::matx4& >(*this) = simd::matx4( 2.f / (r - l), 0.f, 0.f, 0.f, 0.f, 2.f / (t - b), 0.f, 0.f, 0.f, 0.f, 2.f / (n - f), 0.f, (r + l) / (l - r), (t + b) / (b - t), (f + n) / (n - f), 1.f); } }; class matx4_persp : public simd::matx4 { matx4_persp(); matx4_persp(const matx4_persp&); public: matx4_persp( const float l, const float r, const float b, const float t, const float n, const float f) { static_cast< simd::matx4& >(*this) = simd::matx4( 2.f * n / (r - l), 0.f, 0.f, 0.f, 0.f, 2.f * n / (t - b), 0.f, 0.f, (r + l) / (r - l), (t + b) / (t - b), (f + n) / (n - f), -1.f, 0.f, 0.f, 2.f * f * n / (n - f), 0.f); } }; bool hook::render_frame(GLuint primary_fbo) { if (!check_context(__FUNCTION__)) return false; ///////////////////////////////////////////////////////////////// // fast-forward the skeleton animation to current time while (anim::duration <= anim::animTime) { if (g_animations.end() == ++anim::at) anim::at = g_animations.begin(); if (g_durations.end() == ++anim::dt) anim::dt = g_durations.begin(); anim::animTime -= anim::duration; anim::duration = *anim::dt; rend::resetSkeletonAnimProgress(*anim::at); } rend::animateSkeleton(g_bone_count, g_bone_mat, g_bone, *anim::at, anim::animTime, g_root_bone); anim::animTime += g_anim_step; #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // produce line segments from the bones of the animated skeleton assert(255 == g_bone[0].parent_idx); for (unsigned i = 1; i < g_bone_count; ++i) { const unsigned j = g_bone[i].parent_idx; const simd::vect4::basetype& pos0 = 255 != j ? g_bone[j].to_model[3] : g_root_bone->to_model[3]; // accommodate multi-root skeletons const simd::vect4::basetype& pos1 = g_bone[i].to_model[3]; g_stick[i][0].pos[0] = pos0[0]; g_stick[i][0].pos[1] = pos0[1]; g_stick[i][0].pos[2] = pos0[2]; g_stick[i][1].pos[0] = pos1[0]; g_stick[i][1].pos[1] = pos1[1]; g_stick[i][1].pos[2] = pos1[2]; } #endif ///////////////////////////////////////////////////////////////// // compute two MVPs: one for screen space and one for light space const float z_offset = -2.125f; const float shadow_extent = 1.5f; const simd::vect4 translate(0.f, 0.f, z_offset, 0.f); simd::matx4 mv = simd::matx4().mul(g_root_bone->to_model, g_matx_fit); mv.set(3, simd::vect4().add(mv[3], translate)); const float l = -.5f; const float r = .5f; const float b = -.5f; const float t = .5f; const float n = 1.f; const float f = 4.f; const matx4_persp proj(l, r, b, t, n, f); const matx4_ortho proj_lit( -shadow_extent, shadow_extent, -shadow_extent, shadow_extent, 0.f, 4.f); // light-space basis vectors const simd::vect3 x_lit(0.707107, 0.0, -0.707107); // x-axis rotated at pi/4 around y-axis const simd::vect3 y_lit(0.0, 1.0, 0.0); // y-axis const simd::vect3 z_lit(0.707107, 0.0, 0.707107); // z-axis rotated at pi/4 around y-axis const simd::matx4 world_lit( x_lit[0], x_lit[1], x_lit[2], 0.f, y_lit[0], y_lit[1], y_lit[2], 0.f, z_lit[0], z_lit[1], z_lit[2], 0.f, z_lit[0] * 2.f, z_lit[1] * 2.f, z_lit[2] * 2.f + z_offset, 1.f); const simd::matx4 local_lit = simd::matx4().inverse(world_lit); const simd::matx4 viewproj_lit = simd::matx4().mul(local_lit, proj_lit); const float depth_compensation = 1.f / 1024.f; // slope-invariant compensation const simd::matx4 bias( .5f, 0.f, 0.f, 0.f, 0.f, .5f, 0.f, 0.f, 0.f, 0.f, .5f, 0.f, .5f, .5f, .5f - depth_compensation, 1.f); const simd::matx4 mvp = simd::matx4().mul(mv, proj); const simd::matx4 mvp_lit = simd::matx4().mul(mv, viewproj_lit); const simd::matx4 biased_lit = simd::matx4().mul(mv, viewproj_lit).mulr(bias); const simd::vect3 lp_obj = simd::vect3( mv[0][0] + mv[0][2], mv[1][0] + mv[1][2], mv[2][0] + mv[2][2]).normalise(); GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); const float aspect = float(vp[3]) / vp[2]; const rend::dense_matx4 dense_mvp = rend::dense_matx4( mvp[0][0] * aspect, mvp[0][1], mvp[0][2], mvp[0][3], mvp[1][0] * aspect, mvp[1][1], mvp[1][2], mvp[1][3], mvp[2][0] * aspect, mvp[2][1], mvp[2][2], mvp[2][3], mvp[3][0] * aspect, mvp[3][1], mvp[3][2], mvp[3][3]); const rend::dense_matx4 dense_mvp_lit = rend::dense_matx4( mvp_lit[0][0], mvp_lit[0][1], mvp_lit[0][2], mvp_lit[0][3], mvp_lit[1][0], mvp_lit[1][1], mvp_lit[1][2], mvp_lit[1][3], mvp_lit[2][0], mvp_lit[2][1], mvp_lit[2][2], mvp_lit[2][3], mvp_lit[3][0], mvp_lit[3][1], mvp_lit[3][2], mvp_lit[3][3]); const rend::dense_matx4 dense_biased_lit = rend::dense_matx4( biased_lit[0][0], biased_lit[0][1], biased_lit[0][2], biased_lit[0][3], biased_lit[1][0], biased_lit[1][1], biased_lit[1][2], biased_lit[1][3], biased_lit[2][0], biased_lit[2][1], biased_lit[2][2], biased_lit[2][3], biased_lit[3][0], biased_lit[3][1], biased_lit[3][2], biased_lit[3][3]); ///////////////////////////////////////////////////////////////// // render the shadow of the geometric asset into the FBO glBindFramebuffer(GL_FRAMEBUFFER, g_fbo); glViewport(0, 0, g_fbo_res, g_fbo_res); DEBUG_GL_ERR() glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_FILL); glClear(GL_DEPTH_BUFFER_BIT); glUseProgram(g_shader_prog[PROG_SHADOW]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SHADOW][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SHADOW][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp_lit)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SHADOW][UNI_BONE]) { glUniformMatrix4fv(g_uni[PROG_SHADOW][UNI_BONE], g_bone_count, GL_FALSE, static_cast< const GLfloat* >(g_bone_mat[0])); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SHADOW]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SHADOW >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() #endif glDrawElements(GL_TRIANGLES, g_num_faces[MESH_SKIN] * 3, g_index_type, 0); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SHADOW].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SHADOW].active_attr[i]); DEBUG_GL_ERR() #endif ///////////////////////////////////////////////////////////////// // render the geometric asset into the main framebuffer glBindFramebuffer(GL_FRAMEBUFFER, primary_fbo); glViewport(vp[0], vp[1], vp[2], vp[3]); DEBUG_GL_ERR() glDisable(GL_POLYGON_OFFSET_FILL); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(g_shader_prog[PROG_SKIN]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SKIN][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_MVP_LIT]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_MVP_LIT], 1, GL_FALSE, static_cast< const GLfloat* >(dense_biased_lit)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_BONE]) { glUniformMatrix4fv(g_uni[PROG_SKIN][UNI_BONE], g_bone_count, GL_FALSE, static_cast< const GLfloat* >(g_bone_mat[0])); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_LP_OBJ]) { const GLfloat nonlocal_light[4] = { lp_obj[0], lp_obj[1], lp_obj[2], 0.f }; glUniform4fv(g_uni[PROG_SKIN][UNI_LP_OBJ], 1, nonlocal_light); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKIN][UNI_VP_OBJ]) { const GLfloat nonlocal_viewer[4] = { mv[0][2], mv[1][2], mv[2][2], 0.f }; glUniform4fv(g_uni[PROG_SKIN][UNI_VP_OBJ], 1, nonlocal_viewer); DEBUG_GL_ERR() } if (0 != g_tex[TEX_NORMAL] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_NORMAL]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_NORMAL], 0); DEBUG_GL_ERR() } if (0 != g_tex[TEX_ALBEDO] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO]) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_ALBEDO]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_ALBEDO], 1); DEBUG_GL_ERR() } if (0 != g_tex[TEX_SHADOW] && -1 != g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW]) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_tex[TEX_SHADOW]); glUniform1i(g_uni[PROG_SKIN][UNI_SAMPLER_SHADOW], 2); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKIN]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SKIN >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #endif glDrawElements(GL_TRIANGLES, g_num_faces[MESH_SKIN] * 3, g_index_type, 0); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKIN].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SKIN].active_attr[i]); DEBUG_GL_ERR() #endif #if DRAW_SKELETON ///////////////////////////////////////////////////////////////// // render the skeleton into the main framebuffer glDisable(GL_DEPTH_TEST); glUseProgram(g_shader_prog[PROG_SKEL]); DEBUG_GL_ERR() if (-1 != g_uni[PROG_SKEL][UNI_MVP]) { glUniformMatrix4fv(g_uni[PROG_SKEL][UNI_MVP], 1, GL_FALSE, static_cast< const GLfloat* >(dense_mvp)); DEBUG_GL_ERR() } if (-1 != g_uni[PROG_SKEL][UNI_SOLID_COLOR]) { const GLfloat solid_color[4] = { 0.f, 1.f, 0.f, 1.f }; glUniform4fv(g_uni[PROG_SKEL][UNI_SOLID_COLOR], 1, solid_color); DEBUG_GL_ERR() } #if PLATFORM_GL_OES_vertex_array_object glBindVertexArrayOES(g_vao[PROG_SKEL]); DEBUG_GL_ERR() #else if (!bindVertexBuffersAndPointers< PROG_SKEL >()) return false; for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glEnableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif glBindBuffer(GL_ARRAY_BUFFER, g_vbo[VBO_SKEL_VTX]); glBufferSubData(GL_ARRAY_BUFFER, GLintptr(0), sizeof(g_stick[0]) * g_bone_count, g_stick); DEBUG_GL_ERR() glDrawArrays(GL_LINES, 0, g_bone_count * 2); DEBUG_GL_ERR() #if PLATFORM_GL_OES_vertex_array_object == 0 for (unsigned i = 0; i < g_active_attr_semantics[PROG_SKEL].num_active_attr; ++i) glDisableVertexAttribArray(g_active_attr_semantics[PROG_SKEL].active_attr[i]); DEBUG_GL_ERR() #endif #endif // DRAW_SKELETON return true; }
26.689049
134
0.674614
blu
f40a05ac70e14bd8959617d5aad8327fb48c28d6
4,066
hpp
C++
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
7
2015-10-16T20:49:20.000Z
2019-04-17T09:34:35.000Z
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
source/Euclid/Numerics/Matrix.Inverse.hpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
// // Matrix.Inverse.h // Euclid // // Created by Samuel Williams on 27/11/12. // Copyright (c) 2012 Samuel Williams. All rights reserved. // #ifndef _EUCLID_NUMERICS_MATRIX_INVERSE_H #define _EUCLID_NUMERICS_MATRIX_INVERSE_H #include "Matrix.hpp" namespace Euclid { namespace Numerics { template <typename NumericT> void invert_matrix_4x4 (const NumericT * mat, NumericT * dst) { // Temp array for pairs NumericT tmp[12]; // Array of transpose source matrix NumericT src[16]; // Determinant NumericT det; // transpose matrix for (int i = 0; i < 4; i++) { src[i] = mat[i*4]; src[i + 4] = mat[i*4 + 1]; src[i + 8] = mat[i*4 + 2]; src[i + 12] = mat[i*4 + 3]; } // calculate pairs for first 8 elements (cofactors) tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // calculate first 8 elements (cofactors) dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7]; dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7]; dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7]; dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7]; dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7]; dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7]; dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6]; dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6]; dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3]; dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3]; dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3]; dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3]; dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3]; dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3]; dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2]; dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2]*src[7]; tmp[1] = src[3]*src[6]; tmp[2] = src[1]*src[7]; tmp[3] = src[3]*src[5]; tmp[4] = src[1]*src[6]; tmp[5] = src[2]*src[5]; tmp[6] = src[0]*src[7]; tmp[7] = src[3]*src[4]; tmp[8] = src[0]*src[6]; tmp[9] = src[2]*src[4]; tmp[10] = src[0]*src[5]; tmp[11] = src[1]*src[4]; // calculate second 8 elements (cofactors) dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15]; dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15]; dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15]; dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15]; dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15]; dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15]; dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14]; dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14]; dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9]; dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10]; dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10]; dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8]; dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8]; dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9]; dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9]; dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8]; // calculate determinant det = src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3]; // calculate matrix inverse det = 1.0/det; for (int j = 0; j < 16; j++) dst[j] *= det; } template <typename NumericT> Matrix<4, 4, NumericT> inverse (const Matrix<4, 4, NumericT> & source) { Matrix<4, 4, NumericT> result; invert_matrix_4x4(source.data(), result.data()); return result; } } } #endif
33.603306
72
0.522873
kurocha
f40db6282a73b8a62b79be6856c0180e3e15b08e
25
cpp
C++
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
Projects/engine/helpers/hcs_helpers.cpp
Octdoc/SevenDeities
648324b6b9fb907df93fdf2dfab7379369bdfe9e
[ "MIT" ]
null
null
null
#include "hcs_helpers.h"
12.5
24
0.76
Octdoc
f40f2f5135a7008195368cd891aeb07bfe50573a
4,098
cpp
C++
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_Spawner_HoverSkiff_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPAllowCrafting // (Native, Event, NetResponse, Static, MulticastDelegate, Public, Private, Delegate, NetClient, BlueprintPure, Const, NetValidate) // Parameters: // class AShooterPlayerController** ForPC (Parm, ZeroConstructor, IsPlainOldData) // class FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) class FString UPrimalItem_Spawner_HoverSkiff_C::STATIC_BPAllowCrafting(class AShooterPlayerController** ForPC) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPAllowCrafting"); UPrimalItem_Spawner_HoverSkiff_C_BPAllowCrafting_Params params; params.ForPC = ForPC; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.GetValidSpawnTransform // (NetRequest, Native, NetMulticast, MulticastDelegate, Public, Private, Delegate, NetClient, BlueprintPure, Const, NetValidate) // Parameters: // struct UObject_FTransform SpawnTransform (Parm, OutParm, IsPlainOldData) // bool SpawnValid (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UPrimalItem_Spawner_HoverSkiff_C::GetValidSpawnTransform(struct UObject_FTransform* SpawnTransform, bool* SpawnValid) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.GetValidSpawnTransform"); UPrimalItem_Spawner_HoverSkiff_C_GetValidSpawnTransform_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (SpawnTransform != nullptr) *SpawnTransform = params.SpawnTransform; if (SpawnValid != nullptr) *SpawnValid = params.SpawnValid; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPCrafted // () void UPrimalItem_Spawner_HoverSkiff_C::BPCrafted() { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.BPCrafted"); UPrimalItem_Spawner_HoverSkiff_C_BPCrafted_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.SpawnCraftedSkiff // () void UPrimalItem_Spawner_HoverSkiff_C::SpawnCraftedSkiff() { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.SpawnCraftedSkiff"); UPrimalItem_Spawner_HoverSkiff_C_SpawnCraftedSkiff_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItem_Spawner_HoverSkiff_C::ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_Spawner_HoverSkiff.PrimalItem_Spawner_HoverSkiff_C.ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff"); UPrimalItem_Spawner_HoverSkiff_C_ExecuteUbergraph_PrimalItem_Spawner_HoverSkiff_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
33.048387
170
0.756467
2bite
f4145c53e429367e61c94cfa6f344dc2276b91be
751
hpp
C++
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
3
2020-05-24T16:29:42.000Z
2021-09-10T13:33:15.000Z
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
source/cppx-core-language/bit-level/Bit_width.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
#pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi"). #include <cppx-core-language/assert-cpp/is-c++17-or-later.hpp> #include <cppx-core-language/bit-level/bits_per_.hpp> // cppx::bits_per_ namespace cppx::_ { struct Bit_width{ enum Enum { _8 = 8, _16 = 16, _32 = 32, _64 = 64, _128 = 128, system = bits_per_<void*> }; }; static_assert( Bit_width::system == 16 or Bit_width::system == 32 or Bit_width::system == 64 or Bit_width::system == 128 ); } // namespace cppx::_ // Exporting namespaces: namespace cppx { namespace bit_level { using _::Bit_width; } // namespace bit_level using namespace bit_level; } // namespace cppx
27.814815
83
0.612517
alf-p-steinbach
f414c2ac74d2c1baf8725351082e81ddb361e112
5,319
hpp
C++
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
7
2020-05-04T16:43:08.000Z
2022-01-13T16:31:17.000Z
example/gmres/KokkosSparse_MatrixPrec.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Jennifer Loe (jloe@sandia.gov) // // ************************************************************************ //@HEADER */ /// @file KokkosKernels_MatrixPrec.hpp #ifndef KK_MATRIX_PREC_HPP #define KK_MATRIX_PREC_HPP #include<KokkosSparse_Preconditioner.hpp> #include<Kokkos_Core.hpp> #include<KokkosBlas.hpp> #include<KokkosSparse_spmv.hpp> namespace KokkosSparse{ namespace Experimental{ /// \class MatrixPrec /// \brief This is a simple class to use if one /// already has a matrix representation of their /// preconditioner M. The class applies an /// SpMV with M as the preconditioning step. /// \tparam ScalarType Type of the matrix's entries /// \tparam Layout Kokkos layout of vectors X and Y to which /// the preconditioner is applied /// \tparam EXSP Execution space for the preconditioner apply /// \tparam Ordinal Type of the matrix's indices; /// /// Preconditioner provides the following methods /// - initialize() Does nothing; Matrix initialized upon object construction. /// - isInitialized() returns true /// - compute() Does nothing; Matrix initialized upon object construction. /// - isComputed() returns true /// template< class ScalarType, class Layout, class EXSP, class OrdinalType = int > class MatrixPrec : virtual public KokkosSparse::Experimental::Preconditioner<ScalarType, Layout, EXSP, OrdinalType> { private: using crsMat_t = KokkosSparse::CrsMatrix<ScalarType, OrdinalType, EXSP>; crsMat_t A; bool isInitialized_ = true; bool isComputed_ = true; public: //! Constructor: MatrixPrec<ScalarType, Layout, EXSP, OrdinalType> (const KokkosSparse::CrsMatrix<ScalarType, OrdinalType, EXSP> &mat) : A(mat) {} //! Destructor. virtual ~MatrixPrec(){} ///// \brief Apply the preconditioner to X, putting the result in Y. ///// ///// \tparam XViewType Input vector, as a 1-D Kokkos::View ///// \tparam YViewType Output vector, as a nonconst 1-D Kokkos::View ///// ///// \param transM [in] "N" for non-transpose, "T" for transpose, "C" ///// for conjugate transpose. All characters after the first are ///// ignored. This works just like the BLAS routines. ///// \param alpha [in] Input coefficient of M*x ///// \param beta [in] Input coefficient of Y ///// ///// If the result of applying this preconditioner to a vector X is ///// \f$M \cdot X\f$, then this method computes \f$Y = \beta Y + \alpha M \cdot X\f$. ///// The typical case is \f$\beta = 0\f$ and \f$\alpha = 1\f$. // void apply (const Kokkos::View<ScalarType*, Layout, EXSP> &X, Kokkos::View<ScalarType*, Layout, EXSP> &Y, const char transM[] = "N", ScalarType alpha = Kokkos::Details::ArithTraits<ScalarType>::one(), ScalarType beta = Kokkos::Details::ArithTraits<ScalarType>::zero()) const { KokkosSparse::spmv(transM, alpha, A, X, beta, Y); }; //@} //! Set this preconditioner's parameters. void setParameters () {} void initialize() { } //! True if the preconditioner has been successfully initialized, else false. bool isInitialized() const { return isInitialized_;} void compute(){ } //! True if the preconditioner has been successfully computed, else false. bool isComputed() const {return isComputed_;} //! True if the preconditioner implements a transpose operator apply. bool hasTransposeApply() const { return true; } }; } //End Experimental } //End namespace KokkosSparse #endif
38.266187
122
0.686595
NexGenAnalytics
f4159273b922c3fe27b033cb6da52b8575f29052
1,013
hpp
C++
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/rucksack/include/sge/rucksack/axis_policy2.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RUCKSACK_AXIS_POLICY2_HPP_INCLUDED #define SGE_RUCKSACK_AXIS_POLICY2_HPP_INCLUDED #include <sge/rucksack/axis_fwd.hpp> #include <sge/rucksack/axis_policy.hpp> #include <sge/rucksack/axis_policy2_fwd.hpp> #include <sge/rucksack/detail/symbol.hpp> namespace sge::rucksack { class axis_policy2 { public: SGE_RUCKSACK_DETAIL_SYMBOL axis_policy2(sge::rucksack::axis_policy const &, sge::rucksack::axis_policy const &); [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const &x() const; [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const &y() const; [[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy const & operator[](sge::rucksack::axis) const; private: sge::rucksack::axis_policy x_, y_; }; } #endif
27.378378
87
0.757157
cpreh
f41820289cc4554b54692b66b714c05a14cf0815
1,733
cc
C++
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
2
2018-11-14T11:18:49.000Z
2018-11-17T05:13:52.000Z
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
ProSupplementalData.cc
hiqsol/reclient
02c2f0c21a4378a5dbcc058f468d98c34e1d1190
[ "BSD-3-Clause" ]
null
null
null
#include "ProSupplementalData.h" using namespace std; using namespace domtools; using namespace eppobject::epp; epp_string ProSupplementalData::toXML() { domtools::xml_string_output xmltext; xmltext.setWhitespace(false); xmltext.beginTag("supplementalData:"+(*m_op)); xmltext.putAttribute("xmlns:supplementalData","urn:afilias:params:xml:ns:supplementalData-1.0"); //xmltext.putAttribute("xsi:schemaLocation","urn:afilias:params:xml:ns:supplementalData-1.0 supplementalData-1.0.xsd"); epp_string json = "{"+ quoted("profession") + ": " + quoted(*m_profession) + ", " + quoted("authorityName") + ": " + quoted(*m_authorityName) + ", " + quoted("authorityUrl") + ": " + quoted(*m_authorityUrl) + ", " + quoted("licenseNumber") + ": " + quoted(*m_licenseNumber) + "}"; xmltext.beginTag("supplementalData:value"); xmltext.putCDATA(json); /// XXX xmltext.endTag("supplementalData:value"); xmltext.endTag("supplementalData:"+(*m_op)); printf("EXT XML: %s\n",xmltext.getString().c_str()); return xmltext.getString(); }; epp_string ProSupplementalData::quoted (const epp_string & str) { return "\""+str+"\""; } void ProSupplementalData::fromXML (const epp_string & xml) { printf("fromXML: %s",xml.c_str()); DOM_Document doc = createDOM_Document(xml); DOM_Node dataNode = domtools::getSingleTag(doc, "supplementalData:infData"); if (!dataNode.isNull()) { string nodeValue; DOM_Node valueNode = domtools::getSingleTag(doc, "supplementalData:value"); if (!valueNode.isNull()) { getNodeData(valueNode, nodeValue); m_profession.ref(new epp_string(nodeValue)); }; }; };
32.092593
123
0.661281
hiqsol
f419dab890a8d3c824b32aa5b2db4bf503e94e88
436
cpp
C++
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
1
2020-12-04T13:36:03.000Z
2020-12-04T13:36:03.000Z
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
null
null
null
PathTracer/src/platform/opengl/rendering/pipeline/GLPipeline.cpp
Andrispowq/PathTracer
8965ddf5c70f55740955e24242981633f000a354
[ "Apache-2.0" ]
null
null
null
#include "Includes.hpp" #include "GLPipeline.h" namespace Prehistoric { GLPipeline::GLPipeline(Window* window, AssetManager* manager, ShaderHandle shader) : Pipeline(window, manager, shader) { } void GLPipeline::BindPipeline(CommandBuffer* buffer) const { this->buffer = buffer; shader->Bind(buffer); } void GLPipeline::RenderPipeline() const { } void GLPipeline::UnbindPipeline() const { shader->Unbind(); } };
16.769231
83
0.715596
Andrispowq
f41d2ebfcd0b9298fbc806df961d0606b68acc6b
2,321
cpp
C++
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
null
null
null
src/tests/mkdarts.cpp
lzzgeo/NLP
2c9e02d62b900d8729a60d3fc68d5954b4d6e3f9
[ "MIT" ]
1
2018-05-18T17:17:35.000Z
2018-05-18T17:17:35.000Z
/* Darts -- Double-ARray Trie System $Id: mkdarts.cpp 1674 2008-03-22 11:21:34Z taku $; Copyright(C) 2001-2007 Taku Kudo <taku@chasen.org> All rights reserved. */ #include <darts.h> #include <cstdio> #include <fstream> #include <iostream> #include <vector> #include <string> #include <set> using namespace std; int progress_bar(size_t current, size_t total) { static char bar[] = "*******************************************"; static int scale = sizeof(bar) - 1; static int prev = 0; int cur_percentage = static_cast<int>(100.0 * current/total); int bar_len = static_cast<int>(1.0 * current*scale/total); if (prev != cur_percentage) { printf("Making Double Array: %3d%% |%.*s%*s| ", cur_percentage, bar_len, bar, scale - bar_len, ""); if (cur_percentage == 100) printf("\n"); else printf("\r"); fflush(stdout); } prev = cur_percentage; return 1; }; int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " File Index" << std::endl; return -1; } std::string file = argv[argc-2]; std::string index = argv[argc-1]; Darts::DoubleArray da; //Darts::DoubleArrayUint16 da2; std::vector<const char *> key; std::istream *is; if (file == "-") { is = &std::cin; } else { is = new std::ifstream(file.c_str()); } if (!*is) { std::cerr << "Cannot Open: " << file << std::endl; return -1; } set<string> keyset; std::string line; while (std::getline(*is, line)) { keyset.insert(line); } if (file != "-") delete is; printf("vector size: %zu\n", keyset.size()); set<string>::iterator itr = keyset.begin(); set<string>::iterator itrEnd= keyset.end(); while (itr!=itrEnd) { char *tmp = new char[itr->size()+1]; std::strcpy(tmp, itr->c_str()); key.push_back(tmp); printf("%s\n", itr->c_str()); itr++; } if (da.build(key.size(), &key[0], 0, 0, &progress_bar) != 0 || da.save(index.c_str()) != 0) { std::cerr << "Error: cannot build double array " << file << std::endl; return -1; }; for (unsigned int i = 0; i < key.size(); i++) delete [] key[i]; std::cout << "Done!, Compression Ratio: " << 100.0 * da.nonzero_size() / da.size() << " %" << std::endl; return 0; }
22.533981
75
0.559673
lzzgeo
f41f552ef840bfc505608ad093bcab39b1b2860c
4,975
cpp
C++
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
67
2018-01-17T17:18:37.000Z
2020-08-24T23:45:56.000Z
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
emoon/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
132
2018-01-17T17:43:25.000Z
2020-09-01T07:41:17.000Z
src/plugins/playback/adplug/adplug_lib/src/raw.cpp
HippoPlayer/HippoPlayer
a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6
[ "Apache-2.0", "MIT" ]
5
2021-02-12T15:23:31.000Z
2022-01-09T15:16:21.000Z
/* * Adplug - Replayer for many OPL2/OPL3 audio file formats. * Copyright (C) 1999 - 2005 Simon Peter, <dn.tlp@gmx.net>, et al. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * raw.c - RAW Player by Simon Peter <dn.tlp@gmx.net> */ /* * Copyright (c) 2015 - 2017 Wraithverge <liam82067@yahoo.com> * - Preliminary support for displaying arbitrary Tag data. (2015) * - Realigned to Tabs. (2017) * - Added Member pointers. (2017) * - Finalized Tag support. (2017) */ #include <cstring> #include "raw.h" /*** public methods *************************************/ CPlayer *CrawPlayer::factory(Copl *newopl) { return new CrawPlayer(newopl); } bool CrawPlayer::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if (!f) return false; char id[8]; unsigned long i = 0; // file validation section f->readString(id, 8); if (strncmp(id,"RAWADATA",8)) { fp.close (f); return false; } // load section this->clock = f->readInt(2); // clock speed this->length = fp.filesize(f); if (this->length <= 10) { fp.close (f); return false; } this->length = (this->length - 10) / 2; // Wraithverge: total data-size. this->data = new Tdata [this->length]; bool tagdata = false; title[0] = 0; author[0] = 0; desc[0] = 0; for (i = 0; i < this->length; i++) { // Do not store tag data in track data. this->data[i].param = (tagdata ? 0xFF : f->readInt(1)); this->data[i].command = (tagdata ? 0xFF : f->readInt(1)); // Continue trying to stop at the RAW EOF data marker. if (!tagdata && this->data[i].param == 0xFF && this->data[i].command == 0xFF) { unsigned char tagCode = f->readInt(1); if (tagCode == 0x1A) { // Tag marker found. tagdata = true; } else if (tagCode == 0) { // Old comment (music archive 2004) f->readString(desc, 1023, 0); } else { // This is not tag marker, revert. f->seek(-1, binio::Add); } } } if (tagdata) { // The arbitrary Tag Data section begins here. // "title" is maximum 40 characters long. f->readString(title, 40, 0); // Skip "author" if Tag marker byte is missing. if (f->readInt(1) != 0x1B) { f->seek(-1, binio::Add); // Check for older version tag (e.g. stunts.raw) if (f->readInt(1) >= 0x20) { f->seek(-1, binio::Add); f->readString(author, 60, 0); f->readString(desc, 1023, 0); goto end_section; } else f->seek(-1, binio::Add); goto desc_section; } // "author" is maximum 40 characters long. f->readString(author, 40, 0); desc_section: // Skip "desc" if Tag marker byte is missing. if (f->readInt(1) != 0x1C) { goto end_section; } // "desc" is now maximum 1023 characters long (it was 140). f->readString(desc, 1023, 0); } end_section: fp.close(f); rewind(0); return true; } bool CrawPlayer::update() { bool setspeed = 0; if (this->pos >= this->length) return false; if (this->del) { del--; return !songend; } do { setspeed = false; if (this->pos >= this->length) return false; switch(this->data[this->pos].command) { case 0: this->del = this->data[this->pos].param - 1; break; case 2: if (!this->data[this->pos].param) { pos++; if (this->pos >= this->length) return false; this->speed = this->data[this->pos].param + (this->data[this->pos].command << 8); setspeed = true; } else opl->setchip(this->data[this->pos].param - 1); break; case 0xff: if (this->data[this->pos].param == 0xff) { rewind(0); // auto-rewind song songend = true; return !songend; } break; default: opl->write(this->data[this->pos].command, this->data[this->pos].param); break; } } while (this->data[this->pos++].command || setspeed); return !songend; } void CrawPlayer::rewind(int subsong) { pos = del = 0; speed = clock; songend = false; opl->init(); opl->write(1, 32); // go to 9 channel mode } float CrawPlayer::getrefresh() { // timer oscillator speed / wait register = clock frequency return 1193180.0 / (speed ? speed : 0xffff); }
27.185792
89
0.602211
emoon
f421240c152d166a0e6e1371ea7c5f68e3181aba
333
cpp
C++
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
PS_I_2.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; long taskOfPairing(vector<long> freq) { long ans(0),temp(0); for(long i=0;i<freq.size();i++) { ans += freq[i]/2; temp += freq[i]%2; if(temp==2) { ans++; temp=0; } } return ans; }
15.136364
39
0.417417
prameetu
f421db30335dc6621ce478e934a26609a36b2a70
6,624
cpp
C++
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
GlobalIllumination/ObjLoader.cpp
wzchua/graphic
71d154b56a268cce6a1b06e275083210e205aa60
[ "Apache-2.0" ]
null
null
null
#include "ObjLoader.h" static bool fileExists(const std::string & fileName) { struct stat info; int ret = -1; ret = stat(fileName.c_str(), &info); return 0 == ret; } bool ObjLoader::loadObj(const std::string & path, SceneMaterialManager & sceneMatManager, glm::vec3 & min, glm::vec3 & max) { tinyobj::attrib_t attrib; min = glm::vec3(std::numeric_limits<float>::max()); max = -min; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto lastIndex = path.find_last_of('/'); std::string baseDir = path.substr(0, lastIndex + 1); std::cout << baseDir << '\n'; stbi_set_flip_vertically_on_load(true); bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, path.c_str(), baseDir.c_str()); if (!err.empty()) { std::cerr << err << std::endl; } if (!ret) { std::cerr << "Load failed: " << path << std::endl; return false; } printf("# of vertices = %d\n", (int)(attrib.vertices.size()) / 3); printf("# of normals = %d\n", (int)(attrib.normals.size()) / 3); printf("# of texcoords = %d\n", (int)(attrib.texcoords.size()) / 2); printf("# of materials = %d\n", (int)materials.size()); printf("# of shapes = %d\n", (int)shapes.size()); materials.push_back(tinyobj::material_t()); for (size_t i = 0; i < materials.size(); i++) { printf("material[%d].diffuse_texname = %s\n", int(i), materials[i].diffuse_texname.c_str()); } std::cout << baseDir << "\n"; for (auto const& m : materials) { printf("material name: %s\n", m.name.c_str()); if (m.ambient_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.ambient_texname, baseDir); } if (m.diffuse_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.diffuse_texname, baseDir); } if (m.bump_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.bump_texname, baseDir); } if (m.alpha_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.alpha_texname, baseDir); } if (m.specular_texname.length() > 0) { loadTexture(sceneMatManager.textureMap, m.specular_texname, baseDir); } } for (auto const& shape : shapes) { std::vector<tinyobj::material_t> matList; std::map<int, size_t> matMap; if (shape.mesh.material_ids.size() == 0) { matList.push_back(materials[materials.size() - 1]); } else { for (auto const & id : shape.mesh.material_ids) { if (matMap.find(id) == matMap.end()) { matMap[id] = matList.size(); matList.push_back(materials[id]); } } } if (matList.size() > 1) { // break different material faces into different shapes std::vector<tinyobj::shape_t> newShapes; newShapes.reserve(matList.size()); for (int i = 0; i < matList.size(); i++) { newShapes.push_back(tinyobj::shape_t()); newShapes[i].name = shape.name; } for (int i = 0; i < shape.mesh.material_ids.size(); i++) { int id = shape.mesh.material_ids[i]; size_t index = matMap[id]; newShapes[index].mesh.material_ids.push_back(shape.mesh.material_ids[i]); newShapes[index].mesh.num_face_vertices.push_back(shape.mesh.num_face_vertices[i]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 0]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 1]); newShapes[index].mesh.indices.push_back(shape.mesh.indices[i * 3 + 2]); } for (int i = 0; i < matList.size(); i++) { GLuint64 texAmbient, texDiffuse, texAlpha, texHeight; sceneMatManager.getTextureHandles(matList[i], texAmbient, texDiffuse, texAlpha, texHeight); GLuint64 texHandles[4] = { texAmbient, texDiffuse, texAlpha, texHeight }; sceneMatManager.addMaterialShapeGroup(newShapes[i], attrib, matList[i], texHandles); } } else { GLuint64 texAmbient, texDiffuse, texAlpha, texHeight; sceneMatManager.getTextureHandles(matList[0], texAmbient, texDiffuse, texAlpha, texHeight); GLuint64 texHandles[4] = { texAmbient, texDiffuse, texAlpha, texHeight }; sceneMatManager.addMaterialShapeGroup(shape, attrib, matList[0], texHandles); } } return true; } void ObjLoader::loadTexture(std::map<std::string, GLuint>& textureMap, const std::string & textureFilename, const std::string & baseDir) { //load if not loaded if (textureMap.find(textureFilename) == textureMap.end()) { GLuint texture_id; int w, h; int comp; std::string texture_filename = baseDir + textureFilename; if (!fileExists(texture_filename)) { std::cerr << "Unable to find file " << textureFilename << std::endl; exit(-1); } unsigned char* image = stbi_load(texture_filename.c_str(), &w, &h, &comp, STBI_default); if (!image) { std::cerr << "Unable to load texture: " << texture_filename << std::endl; exit(1); } std::cout << "Loaded texture: " << texture_filename << ", w = " << w << ", h = " << h << ", comp = " << comp << std::endl; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (comp == 1) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, image); } else if (comp == 2) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RG, w, h, 0, GL_RG, GL_UNSIGNED_BYTE, image); } else if (comp == 3) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image); } else if (comp == 4) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } else { assert(0); // TODO } glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); stbi_image_free(image); textureMap.insert(std::make_pair(textureFilename, texture_id)); } }
40.638037
136
0.581824
wzchua
f422ca1e05962361f69734a30a796b7f17fbfcf5
4,762
cpp
C++
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
src/he_plain_tensor.cpp
jopasserat/he-transformer
d2865be507d2e20568ca5289513925c813aa59e6
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2019 Intel 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. //***************************************************************************** #include <cstring> #include "he_plain_tensor.hpp" #include "seal/he_seal_backend.hpp" ngraph::he::HEPlainTensor::HEPlainTensor(const element::Type& element_type, const Shape& shape, const HESealBackend* he_seal_backend, const bool batched, const std::string& name) : ngraph::he::HETensor(element_type, shape, he_seal_backend, batched, name) { m_num_elements = m_descriptor->get_tensor_layout()->get_size() / m_batch_size; m_plaintexts.resize(m_num_elements); } void ngraph::he::HEPlainTensor::write(const void* source, size_t tensor_offset, size_t n) { check_io_bounds(source, tensor_offset, n / m_batch_size); const element::Type& element_type = get_tensor_layout()->get_element_type(); size_t type_byte_size = element_type.size(); size_t dst_start_idx = tensor_offset / type_byte_size; size_t num_elements_to_write = n / (type_byte_size * m_batch_size); if (num_elements_to_write == 1) { const void* src_with_offset = (void*)((char*)source); size_t dst_idx = dst_start_idx; if (m_batch_size > 1 && is_batched()) { std::vector<float> values(m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { const void* src = (void*)((char*)source + type_byte_size * (j * num_elements_to_write)); float val = *(float*)(src); values[j] = val; } m_plaintexts[dst_idx].set_values(values); } else { float f = *(float*)(src_with_offset); m_plaintexts[dst_idx].set_values({f}); } } else { #pragma omp parallel for for (size_t i = 0; i < num_elements_to_write; ++i) { const void* src_with_offset = (void*)((char*)source + i * type_byte_size); size_t dst_idx = dst_start_idx + i; if (m_batch_size > 1) { std::vector<float> values(m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { const void* src = (void*)((char*)source + type_byte_size * (i + j * num_elements_to_write)); float val = *(float*)(src); values[j] = val; } m_plaintexts[dst_idx].set_values(values); } else { float f = *(float*)(src_with_offset); m_plaintexts[dst_idx].set_values({f}); } } } } void ngraph::he::HEPlainTensor::read(void* target, size_t tensor_offset, size_t n) const { NGRAPH_CHECK(tensor_offset == 0, "Only support reading from beginning of tensor"); check_io_bounds(target, tensor_offset, n); const element::Type& element_type = get_tensor_layout()->get_element_type(); NGRAPH_CHECK(element_type == element::f32, "Only support float32"); size_t type_byte_size = element_type.size(); size_t src_start_idx = tensor_offset / type_byte_size; size_t num_elements_to_read = n / (type_byte_size * m_batch_size); if (num_elements_to_read == 1) { void* dst_with_offset = (void*)((char*)target); size_t src_idx = src_start_idx; std::vector<float> values = m_plaintexts[src_idx].get_values(); memcpy(dst_with_offset, &values[0], type_byte_size * m_batch_size); } else { #pragma omp parallel for for (size_t i = 0; i < num_elements_to_read; ++i) { size_t src_idx = src_start_idx + i; std::vector<float> values = m_plaintexts[src_idx].get_values(); NGRAPH_CHECK(values.size() >= m_batch_size, "values size ", values.size(), " is smaller than batch size ", m_batch_size); for (size_t j = 0; j < m_batch_size; ++j) { void* dst_with_offset = (void*)((char*)target + type_byte_size * (i + j * num_elements_to_read)); const void* src = (void*)(&values[j]); memcpy(dst_with_offset, src, type_byte_size); } } } }
39.032787
80
0.599748
jopasserat
f4251b865ebba9a3180847e83af578779e06ce52
924
hpp
C++
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
include/luabind/register_lib.hpp
nfluxgb/luabind
1cb41ff15766b50d3ae09eb805a7087c1bca7738
[ "MIT" ]
null
null
null
#pragma once #include "method_definition.hpp" #include <lua.hpp> #include <vector> #include <tuple> #include <iostream> namespace luabind { namespace detail { template<typename CallbackT> struct definition_helper { public: typedef void result_type; definition_helper(std::vector<luaL_Reg>& definitions) : definitions_(definitions) {} void operator()() { definitions_.push_back(luaL_Reg{0, 0}); } template<typename Md, typename... Args> void operator()(Md, Args... defs) { definitions_.push_back(luaL_Reg{Md::name(), &CallbackT::template handle<Md>}); (*this)(defs...); } std::vector<luaL_Reg>& definitions_; }; } template<typename CallbackT, typename TupleT> void register_lib(lua_State* L, char const* name, TupleT dummy) { std::vector<luaL_Reg> definitions; detail::definition_helper<CallbackT> helper(definitions); std::apply(helper, dummy); luaL_register(L, name, definitions.data()); } }
20.533333
80
0.730519
nfluxgb
f426f608fb2b70cfd0b22993d0f1801305246e76
1,671
cpp
C++
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
1
2022-03-04T16:06:41.000Z
2022-03-04T16:06:41.000Z
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
Leetcode/res/Design Tic-Tac-Toe/2.cpp
AllanNozomu/CompetitiveProgramming
ac560ab5784d2e2861016434a97e6dcc44e26dc8
[ "MIT" ]
null
null
null
\* Author: allannozomu Runtime: 960 ms Memory: 20 MB*\ class TicTacToe { private: vector<vector<int>> grid; int size; public: /** Initialize your data structure here. */ TicTacToe(int n) { grid = vector<vector<int>>(n, vector<int>(n)); size = n; } int win(int player){ for (int r = 0 ; r < size; ++r){ int counter = 0; int counter2 = 0; for (int c= 0 ; c < size; ++c){ if (grid[r,c] == player) counter++; if (grid[c,r] == player) counter2++; } if (counter == size || counter2 == size) return player; } int diagonal1 = 0; int diagonal2 = 0; for (int r = 0 ; r < size; ++r){ if (grid[r,r] == player) diagonal1++; if (grid[r,size - r - 1] == player) diagonal2++; } if (diagonal1 == size || diagonal2 == size) return player; return 0; } /** Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. */ int move(int row, int col, int player) { grid[row,col] = player; if (win(player)){ return player; } return 0; } }; /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe* obj = new TicTacToe(n); * int param_1 = obj->move(row,col,player); */
27.85
67
0.495512
AllanNozomu
f4275a3221fe9f700acd759050a4d35b4a04ce9f
1,689
hh
C++
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
inc/Rt.hh
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
#ifndef RT_RT_HH #define RT_RT_HH #include "Camera.hh" #include "LightModel.hh" #include "Math.hh" #include "SceneObj.hh" #include <SFML/System.hpp> #include <memory> #include <utility> struct InterData { Vector ray; Vector normal; Position vecPos; Position impact; double k; std::shared_ptr<SceneObj> obj; InterData(const Vector &ray, const Position &pos, std::shared_ptr<SceneObj> obj, double k) : ray(ray), vecPos(pos), obj(obj), k(k) {} void calcImpact() { impact.x = vecPos.x + k * ray.x; impact.y = vecPos.y + k * ray.y; impact.z = vecPos.z + k * ray.z; } }; class Rt { public: Rt(const Camera &camera, const std::vector<std::shared_ptr<SceneObj>> &objects, const std::vector<std::shared_ptr<Light>> &lights); ~Rt() = default; Rt(const Rt &other) = default; Rt(Rt &&other) = default; Rt &operator=(const Rt &other) = default; Rt &operator=(Rt &&other) = default; unsigned int computePixelColor(const Vector &rayVec); void computeRayVec(Vector &rayVec, int x, int y, sf::Vector2i screenSize) const; private: std::pair<std::shared_ptr<SceneObj>, double> getClosestObj(const auto &rayVec, const Camera &camera); Color ComputeObjectColor(const InterData &origRay, InterData ray, int pass); Color getReflectedColor(const InterData &origRay, InterData ray, int pass); Color getRefractedColor(const InterData &origRay, InterData ray, int pass); private: static constexpr unsigned int Dist = 1000; private: const Camera &camera; const std::vector<std::shared_ptr<SceneObj>> &objects; LightModel lightModel; Math math; }; #endif /* end of include guard: RT_RT_HH */
25.984615
78
0.683245
Tastyep
f42762b5aa553ee5f9951dc37bd23689204b0a58
1,165
cpp
C++
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
tests/Test_Assert_Enabled.cpp
planar-foundry/PF_Debug
99208f11db21b0624a1fd8d44c62ac2d687c93a1
[ "MIT" ]
null
null
null
#include <PF_Test/UnitTest.hpp> #include <PF_Debug/Assert.hpp> #include <string.h> using namespace pf::debug; PFTEST_CREATE(Assert_Enabled) { static bool s_in_assert = false; static const char* s_condition; static const char* s_message; set_assert_handler([](const char* condition, const char*, int, const char* message) { s_in_assert = true; s_condition = condition; s_message = message; }); PFDEBUG_ASSERT(false); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(strcmp(s_condition, "false") == 0); s_in_assert = false; PFDEBUG_ASSERT(true); PFTEST_EXPECT(!s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_MSG(false, ""); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(strcmp(s_condition, "false") == 0); PFTEST_EXPECT(*s_message == '\0'); s_in_assert = false; PFDEBUG_ASSERT_MSG(true, ""); PFTEST_EXPECT(!s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_FAIL(); PFTEST_EXPECT(s_in_assert); s_in_assert = false; PFDEBUG_ASSERT_FAIL_MSG(""); PFTEST_EXPECT(s_in_assert); PFTEST_EXPECT(*s_message == '\0'); s_in_assert = false; }
23.77551
87
0.672961
planar-foundry
f42919927011cd787d4cc94f180db478649222c5
702
cpp
C++
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
D3D11_ColorFilter/src/main.cpp
ProjectAsura/D3D11Samples
fb715afc4718cbb657b5fb2f0885304b1967f55e
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // File : main.cpp // Desc : Main Entry Point. // Copyright(c) Project Asura. All right reserved. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <App.h> //----------------------------------------------------------------------------- // メインエントリーポイントです. //----------------------------------------------------------------------------- int main(int argc, char** argv) { App().Run(); return 0; }
33.428571
80
0.192308
ProjectAsura
f42bd0434943cfebef8687e5da991c62a42f66ac
44
hpp
C++
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_advance.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/advance.hpp>
22
43
0.795455
miathedev
f42f3172f6ab385c2c34bedcaa7d40875335d458
7,461
hpp
C++
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
src/rectangle_base_cover.hpp
phillip-keldenich/circlecover-triangles
f4f0a9ebb30a6e0851410fc4b011471101886869
[ "MIT" ]
null
null
null
/* * Copyright 2022 Phillip Keldenich, Algorithms Department, TU Braunschweig * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "constraint.hpp" template<typename VariableSet> struct RectangleBaseRectangleCoverLemma4 : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with RC Lemma 4"; } IBool satisfied(const VariableSet& vars) override { IDouble r1 = vars.get_r1(), r2 = vars.get_r2(), r3 = vars.get_r3(); IDouble r1sq = ivarp::square(r1), r2sq = ivarp::square(r2), r3sq = ivarp::square(r3); IDouble remaining_weight = vars.weight; IDouble remaining_weight2 = vars.weight - r1sq; IDouble remaining_weight3 = remaining_weight2 - r2sq; IBool w3 = works_with(vars, r3, r3sq, remaining_weight3); if(definitely(w3)) { return {false, false}; } IBool w2 = works_with(vars, r2, r3sq, remaining_weight2); if(definitely(w2)) { return {false, false}; } return !w3 && !w2 && !works_with(vars, r1, r3sq, remaining_weight); } static IDouble inverse_lemma4_coefficient() noexcept { return {1.6393442622950817888494157159584574401378631591796875, // 1.63934426229508196721311475... // 1/0.61 1.63934426229508201089402064098976552486419677734375}; } static IDouble lemma4_coefficient() noexcept { return {0.60999999999999998667732370449812151491641998291015625, 0.6100000000000000976996261670137755572795867919921875}; } IBool works_with(const VariableSet& vars, IDouble largest_rect_disk, IDouble additional_weight, IDouble remaining_weight) { IDouble lambda_4_min = largest_rect_disk / 0.375; IDouble h4 = (ivarp::max)(IDouble(1.0), lambda_4_min); IDouble h4rc4 = lemma4_coefficient() * h4; IDouble width4plus = lambda_4_min + additional_weight / h4rc4; IDouble weight4plus = h4rc4 * lambda_4_min + additional_weight; IBool enough_weight = (weight4plus <= remaining_weight); IDouble efficiency = inverse_lemma4_coefficient() * (1.0 - width4plus * vars.tan_alpha_half); return enough_weight && efficiency >= vars.goal_efficiency; } }; /*template<typename VariableSet> struct RectangleBaseRectangleCoverLemma3 : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with RC Lemma 3"; } IBool satisfied(const VariableSet& vset) override { const IDouble lambda3_scaling_factor{ 1.0764854636994567460561711413902230560779571533203125, // 1.0764854636994569506... // sqrt(1/sigma_hat) 1.076485463699456968100776066421531140804290771484375 }; double lemma3_weight_per_area = 195.0 / 256; IDouble alpha = vset.get_alpha(); IDouble r1 = vset.get_r1(); IDouble r2 = vset.get_r2(); IDouble r2sq = ivarp::square(r2); IDouble lambda3min = r2 * lambda3_scaling_factor; IDouble lambda3max = lambda3min + r2sq / lemma3_weight_per_area; IDouble lemma3weight = lambda3max * lemma3_weight_per_area; IBool enough_without_r1 = (lemma3weight <= vset.weight - ivarp::square(r1)); if(!possibly(enough_without_r1)) { return {true, true}; } IDouble triangle_area_covered = lambda3max - vset.tan_alpha_half * ivarp::square(lambda3max); IDouble area_per_weight = triangle_area_covered / lemma3weight; return !enough_without_r1 || area_per_weight < vset.goal_efficiency; } }; */ template<typename VariableSet> struct R1R2RectangleBaseCover : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with r_1 and r_2"; } IBool satisfied(const VariableSet& vset) override { const IDouble alpha = vset.get_alpha(), r1 = vset.get_r1(), r2 = vset.get_r2(); IDouble r1sq = ivarp::square(r1); IDouble r2sq = ivarp::square(r2); IDouble covered_width_sq = -16*(ivarp::square(r1sq) + ivarp::square(r2sq)) + 32*r1sq*r2sq + 8*r1sq + 8*r2sq - 1; IBool can_cover_rect = (covered_width_sq >= 0); if(!possibly(can_cover_rect)) { return {true, true}; } covered_width_sq.restrict_lb(0.0); IDouble covered_width = 0.5 * ivarp::sqrt(covered_width_sq); IDouble rem_triangle_scale = 1.0 - (covered_width / vset.height); IDouble remaining_weight = vset.weight - r1sq - r2sq; IDouble required_weight = vset.weight * ivarp::square(rem_triangle_scale); return !can_cover_rect || remaining_weight < required_weight; } }; template<typename VariableSet> struct R1R2R3RectangleBaseCover : Constraint<VariableSet> { using IBool = ivarp::IBool; using IDouble = ivarp::IDouble; std::string name() const override { return "Cover Base Rectangle with r_1, r_2 and r_3"; } IBool satisfied(const VariableSet& vset) override { IDouble r1 = vset.get_r1(), r2 = vset.get_r2(), r3 = vset.get_r3(); IDouble r1sq = ivarp::square(r1), r2sq = ivarp::square(r2), r3sq = ivarp::square(r3); IDouble remaining_weight = vset.weight - r1sq - r2sq - r3sq; IBool have_weight = (remaining_weight > 0); if(!possibly(have_weight)) { return {true, true}; } remaining_weight.restrict_lb(0.0); IDouble scale_factor = sqrt(remaining_weight / vset.weight); IDouble remaining_cov_height = scale_factor * vset.height; IDouble must_cover_height = vset.height - remaining_cov_height; IDouble mcsq = ivarp::square(must_cover_height); IDouble h3_sq = 4.0 * r3sq - mcsq; IBool h3_can_cover = (h3_sq >= 0); if(!possibly(h3_can_cover)) { return {true, true}; } h3_sq.restrict_lb(0.0); IDouble h2_sq = 4.0 * r2sq - mcsq; h2_sq.restrict_lb(0.0); IDouble h1_sq = 4.0 * r1sq - mcsq; h1_sq.restrict_lb(0.0); IDouble total_width = sqrt(h1_sq) + sqrt(h2_sq) + sqrt(h3_sq); return !h3_can_cover || (total_width < 1.0); } };
45.218182
130
0.67377
phillip-keldenich
f43c048e3700abac665c7a0c80b8c45f9d3cb295
801
cpp
C++
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/intersection.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
#include "intersection.h" // TODO: move this somewhere else static constexpr float SHADOW_EPSILON = 0.0001; Intersection::Intersection(const Point3f &p) : p(p), n(Normal3f()), wo(Vector3f()), time(0), entity(nullptr) { } Ray Intersection::spawn_ray(const Vector3f &d) const { // TODO: OffsetRayOrigin()? return Ray(p, d, INFINITY, time); } Ray Intersection::spawn_ray_to(const Intersection &p1) const { // TODO: improve, two sqrt() done here Vector3f d = normalize(p1.p - p); Point3f p_biased = p + d * SHADOW_EPSILON; float dist = distance(p1.p, p_biased); return Ray(p_biased, d, dist, time); // NOTE: this does not work if p is not biased (OffsetRayOrigin in pbrt). #if 0 Vector3f d = p1.p - p; return Ray(p, d, 1 - SHADOW_EPSILON, time); #endif }
25.03125
77
0.666667
kdbohne
f43d41f668104b3e2054e11f1d5a8ee843f1be9a
4,128
cpp
C++
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
TaoYibo1866/webots_ros2
a72c164825663cebbfd27e0649ea51d3abf9bbed
[ "Apache-2.0" ]
176
2019-09-06T07:02:05.000Z
2022-03-27T12:41:10.000Z
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
harshag37/webots_ros2
08a061e73e3b88d57cc27b662be0f907d8b9f15b
[ "Apache-2.0" ]
308
2019-08-20T12:56:23.000Z
2022-03-29T09:49:22.000Z
webots_ros2_driver/src/plugins/dynamic/Ros2IMU.cpp
omichel/webots_ros2
5b59d0b1fbeff4c3f75a447bd152c10853f4691b
[ "Apache-2.0" ]
67
2019-11-03T00:58:09.000Z
2022-03-18T07:11:28.000Z
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <webots_ros2_driver/plugins/dynamic/Ros2IMU.hpp> #include <webots_ros2_driver/utils/Math.hpp> #include "pluginlib/class_list_macros.hpp" namespace webots_ros2_driver { void Ros2IMU::init(webots_ros2_driver::WebotsNode *node, std::unordered_map<std::string, std::string> &parameters) { Ros2SensorPlugin::init(node, parameters); mIsEnabled = false; mInertialUnit = NULL; mGyro = NULL; mAccelerometer = NULL; if (!parameters.count("inertialUnitName") && !parameters.count("gyroName") && !parameters.count("accelerometerName")) throw std::runtime_error("The IMU plugins has to contain at least of: <inertialUnitName>, <gyroName>, or <accelerometerName>"); if (parameters.count("inertialUnitName")) { mInertialUnit = mNode->robot()->getInertialUnit(parameters["inertialUnitName"]); if (mInertialUnit == NULL) throw std::runtime_error("Cannot find InertialUnit with name " + parameters["inertialUnitName"]); } if (parameters.count("gyroName")) { mGyro = mNode->robot()->getGyro(parameters["gyroName"]); if (mGyro == NULL) throw std::runtime_error("Cannot find Gyro with name " + parameters["gyroName"]); } if (parameters.count("accelerometerName")) { mAccelerometer = mNode->robot()->getAccelerometer(parameters["accelerometerName"]); if (mAccelerometer == NULL) throw std::runtime_error("Cannot find Accelerometer with name " + parameters["accelerometerName"]); } mPublisher = mNode->create_publisher<sensor_msgs::msg::Imu>(mTopicName, rclcpp::SensorDataQoS().reliable()); mMessage.header.frame_id = mFrameName; if (mAlwaysOn) { enable(); mIsEnabled = true; } } void Ros2IMU::enable() { if (mInertialUnit) mInertialUnit->enable(mPublishTimestepSyncedMs); if (mAccelerometer) mAccelerometer->enable(mPublishTimestepSyncedMs); if (mGyro) mGyro->enable(mPublishTimestepSyncedMs); } void Ros2IMU::disable() { if (mInertialUnit) mInertialUnit->disable(); if (mAccelerometer) mAccelerometer->disable(); if (mGyro) mGyro->disable(); } void Ros2IMU::step() { if (!preStep()) return; if (mIsEnabled) publishData(); if (mAlwaysOn) return; // Enable/Disable sensor const bool shouldBeEnabled = mPublisher->get_subscription_count() > 0; if (shouldBeEnabled != mIsEnabled) { if (shouldBeEnabled) enable(); else disable(); mIsEnabled = shouldBeEnabled; } } void Ros2IMU::publishData() { mMessage.header.stamp = mNode->get_clock()->now(); if (mAccelerometer) { const double *values = mAccelerometer->getValues(); mMessage.linear_acceleration.x = values[0]; mMessage.linear_acceleration.y = values[1]; mMessage.linear_acceleration.z = values[2]; } if (mGyro) { const double *values = mGyro->getValues(); mMessage.angular_velocity.x = values[0]; mMessage.angular_velocity.y = values[1]; mMessage.angular_velocity.z = values[2]; } if (mInertialUnit) { const double *values = mInertialUnit->getQuaternion(); mMessage.orientation.x = values[0]; mMessage.orientation.y = values[1]; mMessage.orientation.z = values[2]; mMessage.orientation.w = values[3]; } mPublisher->publish(mMessage); } } PLUGINLIB_EXPORT_CLASS(webots_ros2_driver::Ros2IMU, webots_ros2_driver::PluginInterface)
30.352941
133
0.674903
TaoYibo1866
f43e225c5d556ebd17e803de0f1456df2f0dfca6
447
cpp
C++
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
support_functions.cpp
AVDer/rpi_egl_tests
323d0f7e9926039d8a22f0eb5916d228ba260375
[ "MIT" ]
null
null
null
#include "support_functions.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "logger.h" size_t get_file_size(const std::string& filename) { struct stat file_stat; if (stat(filename.c_str(), &file_stat) == -1) { Logger::error("File: can't stat file %s", filename.c_str()); return 0; } Logger::info("File: File %s has size %d bytes", filename.c_str(), file_stat.st_size); return file_stat.st_size; }
24.833333
87
0.680089
AVDer
f44b43a2412556f681c105ac2156a05b3be638c5
8,058
cpp
C++
src/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
SecurityInnovation/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
35
2015-05-16T06:36:47.000Z
2021-08-31T15:32:09.000Z
src_2_8/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
3
2015-06-18T06:16:51.000Z
2017-11-16T23:23:59.000Z
src_2_8/replacement/Shell32ReplacementLibrary/Shell32ReplacementLibrary.cpp
crypticterminal/Holodeck
54b97675a73b668f8eec8d9c8a8c7733e1a53db3
[ "MIT" ]
10
2015-04-07T14:45:48.000Z
2021-11-14T15:14:45.000Z
//************************************************************************* // Copyright (C) Security Innovation, LLC, 2002-2004 All Rights Reserved. // // FILE: Shell32ReplacementLibrary.cpp // // DESCRIPTION: Contains replacement library functions for shell32.dll // //========================================================================= // Modification History // // Date SCR Name Purpose // ----------- --- ----------- ------------------------------------------ // Generated 04/20/2004 02:48:51 PM //************************************************************************* #include "shell32replacementlibrary.h" //************************************************************************* // Method: ReplacementLibraryAttach // Description: Called when HEAT is attaching // Parameters: None // Return Value: None //************************************************************************* void ReplacementLibraryAttach() { ReplacementLibrary::DisableInterception(); if (library == NULL) { library = new ReplacementLibrary("shell32.dll"); logSender = &commonLogSender; if (!logSender->GetIsSendLogThreadRunning()) logSender->StartSendLogThread(); } ReplacementLibrary::EnableInterception(); } //************************************************************************* // Method: ReplacementLibraryDetach // Description: Called when HEAT is detaching // Parameters: None // Return Value: None //************************************************************************* void ReplacementLibraryDetach() { ReplacementLibrary::DisableInterception(); if (library != NULL) { if ((logSender != NULL) && (logSender->GetIsSendLogThreadRunning())) { logSender->StopSendLogThread(); logSender = NULL; } } ReplacementLibrary::EnableInterception(); } //************************************************************************* // Method: DllMain // Description: Entry point to this dll // Parameters: See MSDN DllMain function parameters // Return Value: See MSDN DllMain return value //************************************************************************* BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { ReplacementLibrary::DisableInterception(); switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: ReplacementLibraryDetach(); delete library; library = NULL; return TRUE; // Don't re-enable intercepts, as we are detaching default: break; } ReplacementLibrary::EnableInterception(); return TRUE; } //************************************************************************* // START OF ORIGINAL FUNCTION CALLER FUNCTIONS // For all functions in this section the following applies // Description: Calls the original function for a replacement function // Parameters: // numParams - the number of parameters in the params array // params - the parameters to pass to the original function // retVal - the return value from the original function // errCode - the error code from the original function // Return Value: true if the correct number of parameters were passed in, // false otherwise //************************************************************************* //************************************************************************* // Method: ShellExecuteACaller - See START OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* bool ShellExecuteACaller(int numParams, void **params, DWORD *retValue, DWORD *errCode) { if (numParams != 6) return false; HINSTANCE tempRetValue = realShellExecuteA(*((HWND *)params[0]), *((SiString *)params[1]), *((SiString *)params[2]), *((SiString *)params[3]), *((SiString *)params[4]), *((int *)params[5])); memcpy(retValue, &tempRetValue, sizeof(DWORD)); *errCode = GetLastError(); return true; } //************************************************************************* // Method: ShellExecuteWCaller - See START OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* bool ShellExecuteWCaller(int numParams, void **params, DWORD *retValue, DWORD *errCode) { if (numParams != 6) return false; HINSTANCE tempRetValue = realShellExecuteW(*((HWND *)params[0]), *((SiString *)params[1]), *((SiString *)params[2]), *((SiString *)params[3]), *((SiString *)params[4]), *((int *)params[5])); memcpy(retValue, &tempRetValue, sizeof(DWORD)); *errCode = GetLastError(); return true; } //************************************************************************* // END OF ORIGINAL FUNCTION CALLER FUNCTIONS //************************************************************************* //************************************************************************* // START OF REPLACEMENT FUNCTIONS //************************************************************************* //************************************************************************* // Method: ShellExecuteAReplacement // Description: See MSDN ShellExecuteA function // Parameters: See MSDN ShellExecuteA parameters // Return Value: See MSDN ShellExecuteA return value //************************************************************************* HINSTANCE STDAPICALLTYPE ShellExecuteAReplacement(HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, int nShowCmd) { const int numParams = 6; char *functionName = "ShellExecuteA"; char *categoryName = "DANGEROUS"; SiString str[] = { (char *)lpOperation, (char *)lpFile, (char *)lpParameters, (char *)lpDirectory }; void *params[numParams] = { &hwnd, &str[0], &str[1], &str[2], &str[3], &nShowCmd }; ParameterType paramTypes[numParams] = { PointerType, StringType, StringType, StringType, StringType, IntegerType }; if (realShellExecuteA == NULL) realShellExecuteA = (ShellExecuteAFunction)library->GetOriginalFunction(functionName); if (realShellExecuteA != NULL) { DWORD errorCode, tempReturnValue = 0; HINSTANCE returnValue; if (library->RunStandardTestsAndGetResults(logSender, ShellExecuteACaller, categoryName, functionName, numParams, params, paramTypes, &tempReturnValue, "HINSTANCE", &errorCode, 0, true)) { } else { } memcpy(&returnValue, &tempReturnValue, sizeof(DWORD)); SetLastError(errorCode); return returnValue; } return 0; } //************************************************************************* // Method: ShellExecuteWReplacement // Description: See MSDN ShellExecuteW function // Parameters: See MSDN ShellExecuteW parameters // Return Value: See MSDN ShellExecuteW return value //************************************************************************* HINSTANCE STDAPICALLTYPE ShellExecuteWReplacement(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, int nShowCmd) { const int numParams = 6; char *functionName = "ShellExecuteW"; char *categoryName = "DANGEROUS"; SiString str[] = { (wchar_t *)lpOperation, (wchar_t *)lpFile, (wchar_t *)lpParameters, (wchar_t *)lpDirectory }; void *params[numParams] = { &hwnd, &str[0], &str[1], &str[2], &str[3], &nShowCmd }; ParameterType paramTypes[numParams] = { PointerType, WideStringType, WideStringType, WideStringType, WideStringType, IntegerType }; if (realShellExecuteW == NULL) realShellExecuteW = (ShellExecuteWFunction)library->GetOriginalFunction(functionName); if (realShellExecuteW != NULL) { DWORD errorCode, tempReturnValue = 0; HINSTANCE returnValue; if (library->RunStandardTestsAndGetResults(logSender, ShellExecuteWCaller, categoryName, functionName, numParams, params, paramTypes, &tempReturnValue, "HINSTANCE", &errorCode, 0, true)) { } else { } memcpy(&returnValue, &tempReturnValue, sizeof(DWORD)); SetLastError(errorCode); return returnValue; } return 0; } //************************************************************************* // END OF REPLACEMENT FUNCTIONS //*************************************************************************
38.740385
191
0.557707
SecurityInnovation
f450a114d249a8b268d08f4a270b3082634e4288
196
cpp
C++
src/noj_am/BOJ_14652.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/noj_am/BOJ_14652.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/noj_am/BOJ_14652.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, m, k; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> n >> m >> k; cout << k / m << ' ' << k % m << '\n'; }
16.333333
40
0.52551
ginami0129g
f45115f9c1ec431a0b9a03f9e2a5e66585a43b7b
6,200
cpp
C++
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/rendercore/SVRenderer.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVRenderer.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVRenderer.h" #include "../app/SVInst.h" #include "../work/SVTdCore.h" #include "../mtl/SVTexMgr.h" #include "../mtl/SVTexture.h" #include "../mtl/SVTextureIOS.h" #include "SVRenderMgr.h" #include "SVRenderTarget.h" #include "SVRenderTexture.h" #include "SVRObjBase.h" #include "SVRenderState.h" SVRenderer::SVRenderer(SVInstPtr _app) :SVGBaseEx(_app) ,m_pRenderTex(nullptr) ,m_pRState(nullptr) ,m_inWidth(256) ,m_inHeight(256) ,m_outWidth(256) ,m_outHeight(256){ m_resLock = MakeSharedPtr<SVLock>(); for(s32 i=E_TEX_MAIN ;i<E_TEX_END;i++) { m_svTex[i] = nullptr; } } SVRenderer::~SVRenderer(){ m_resLock = nullptr; } void SVRenderer::init(s32 _w,s32 _h){ m_inWidth = _w; m_inHeight = _h; } void SVRenderer::destroy(){ m_pRenderTex = nullptr; for(s32 i=E_TEX_MAIN ;i<E_TEX_END;i++) { m_svTex[i] = nullptr; } clearRes(); m_stack_proj.destroy(); m_stack_view.destroy(); m_stack_vp.destroy(); m_resLock = nullptr; } // void SVRenderer::renderBegin() { } // void SVRenderer::renderEnd() { clearMatStack(); } //获取状态 SVRenderStatePtr SVRenderer::getState(){ return m_pRState; } //重置状态 void SVRenderer::resetState() { if(m_pRState){ m_pRState->resetState(); } } void SVRenderer::resize(s32 _w,s32 _) { } void SVRenderer::clearRes() { m_resLock->lock(); for(s32 i=0;i<m_robjList.size();i++) { SVRObjBasePtr t_robj = m_robjList[i]; t_robj->destroy(nullptr); } m_robjList.destroy(); m_resLock->unlock(); } void SVRenderer::addRes(SVRObjBasePtr _res) { m_resLock->lock(); m_robjList.append(_res); m_resLock->unlock(); } void SVRenderer::removeRes(SVRObjBasePtr _res) { m_resLock->lock(); for(s32 i=0;i<m_robjList.size();i++) { SVRObjBasePtr t_robj = m_robjList[i]; if(t_robj == _res) { t_robj->destroy(nullptr); m_robjList.removeForce(i); break; } } m_resLock->unlock(); } //移除不使用的资源 void SVRenderer::removeUnuseRes() { m_resLock->lock(); //小心复值引用计数会加 1!!!!!!!!!!!!!! 晓帆。。 for(s32 i=0;i<m_robjList.size();) { if(m_robjList[i].use_count() == 1) { m_robjList[i]->destroy(nullptr); m_robjList.remove(i); }else{ i++; } } m_robjList.reserveForce(m_robjList.size()); m_resLock->unlock(); } SVRenderTexturePtr SVRenderer::getRenderTexture() { return m_pRenderTex; } SVTexturePtr SVRenderer::getSVTex(SVTEXTYPE _type){ if(E_TEX_END == _type) { return nullptr; } return m_svTex[_type]; } bool SVRenderer::hasSVTex(SVTEXTYPE _type) { if( m_svTex[_type] ) return true; return false; } //创建内置纹理 有问题后期删掉 SVTexturePtr SVRenderer::createSVTex(SVTEXTYPE _type,s32 _w,s32 _h,s32 _formate, bool _enableMipMap) { // SVTexturePtr t_tex = MakeSharedPtr<SVTexture>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // #if defined(SV_ANDROID) // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_RGBA,_enableMipMap); // #else // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_BGRA,_enableMipMap); // #endif // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; return nullptr; } //创建内置纹理 有问题后期删掉 SVTexturePtr SVRenderer::createSVTex(SVTEXTYPE _type,s32 _w,s32 _h,s32 _informate,s32 _daformate, bool _enableMipMap) { // SVTexturePtr t_tex = MakeSharedPtr<SVTexture>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, _informate, _daformate,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; return nullptr; } //创建内置纹理 IOS SVTexturePtr SVRenderer::createSVTexIOS(SVTEXTYPE _type,s32 _w,s32 _h,s32 _formate, bool _enableMipMap) { #if defined( SV_IOS ) // SVTexturePtr t_tex = MakeSharedPtr<SVTextureIOS>(mApp);; // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, GL_RGBA, GL_BGRA,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; #endif return nullptr; } SVTexturePtr SVRenderer::createSVTexIOS(SVTEXTYPE _type,s32 _w,s32 _h,s32 _informate,s32 _daformate, bool _enableMipMap) { #if defined( SV_IOS ) // SVTexturePtr t_tex = MakeSharedPtr<SVTextureIOS>(mApp); // SVString t_str(""); // t_str.printf("intexture_%d",s32(_type)); // t_tex->init(t_str.c_str(), GL_TEXTURE_2D, _w, _h, _informate, _daformate,_enableMipMap); // mApp->getRenderMgr()->pushRCmdCreate(t_tex); // m_svTex[_type] = t_tex; // return m_svTex[_type]; #endif return nullptr; } // void SVRenderer::destroySVTex(SVTEXTYPE _type) { m_svTex[_type] = nullptr; } //视口 void SVRenderer::svPushViewPort(u32 _x,u32 _y,u32 _w,u32 _h) { VPParam t_pm; t_pm.m_x = _x; t_pm.m_y = _y; t_pm.m_width = _w; t_pm.m_height = _h; m_vpStack.push(t_pm); } //退出视口 void SVRenderer::svPopViewPort() { m_vpStack.pop(); } // void SVRenderer::pushProjMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_proj.push(mat4); } FMat4 SVRenderer::getProjMat(){ FMat4 mat4Proj = m_stack_proj.top(); return mat4Proj; } void SVRenderer::popProjMat(){ m_stack_proj.pop(); } // void SVRenderer::pushViewMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_view.push(mat4); } FMat4 SVRenderer::getViewMat(){ FMat4 mat4View = m_stack_view.top();; return mat4View; } void SVRenderer::popViewMat(){ m_stack_view.pop(); } // void SVRenderer::pushVPMat(FMat4 _mat){ FMat4 mat4 = _mat; m_stack_vp.push(mat4); } FMat4 SVRenderer::getVPMat(){ FMat4 mat4VP = m_stack_vp.top();; return mat4VP; } void SVRenderer::popVPMat(){ m_stack_vp.pop(); } void SVRenderer::clearMatStack(){ m_stack_proj.clear(); m_stack_view.clear(); m_stack_vp.clear(); }
24.124514
122
0.659516
SVEChina
f45d57365119bcd630de4c8b05560130ca575bc5
3,172
cpp
C++
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.cpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#include "Engine/Renderer/SpriteRenderer/ParticleSystem/ParticleEmitter2D.hpp" //--------------------------------------------------------------------------------------------------------------------------- //STRUCTORS //--------------------------------------------------------------------------------------------------------------------------- ParticleEmitter2D::ParticleEmitter2D(ParticleEmitterDefinition2D* emitterDef, const String& layerName, const Vector2& position) : m_emitterDef(emitterDef) , m_layerName(layerName) , m_isPlaying(true) , m_currNumParticles(0) , m_age(0.f) , m_position(position) { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { m_particles[i] = nullptr; } SpawnParticles(); } ParticleEmitter2D::~ParticleEmitter2D() { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (m_particles[i]) { delete m_particles[i]; m_particles[i] = nullptr; } } } //--------------------------------------------------------------------------------------------------------------------------- //UPDATE //--------------------------------------------------------------------------------------------------------------------------- void ParticleEmitter2D::Update(float deltaSeconds) { m_age += deltaSeconds; if (m_emitterDef->m_spawnRate == 0.f && m_currNumParticles == 0) { m_isPlaying = false; } UpdateParticles(deltaSeconds); DestroyParticles(); if (m_isPlaying) { SpawnParticles(); } } //--------------------------------------------------------------------------------------------------------------------------- //PRIVATE UPDATES //--------------------------------------------------------------------------------------------------------------------------- void ParticleEmitter2D::SpawnParticles() { if (m_age != 0.f && m_emitterDef->m_spawnRate == 0.f) return; uint numToSpawn = m_emitterDef->m_initialSpawnCount.Roll(); for (uint i = 0; i < numToSpawn; i++) { Vector2 startingVel = m_emitterDef->m_startVelocity.Roll() * m_emitterDef->m_velocityStrength.Roll(); Vector2 accel = m_emitterDef->m_acceleration.Roll(); float life = m_emitterDef->m_life.Roll(); float scale = m_emitterDef->m_initialScale.Roll(); Particle2D* particle = new Particle2D(m_emitterDef->m_resourceName, m_layerName, m_position, startingVel, accel, life, Vector2(scale, scale), m_emitterDef->m_tint); AddParticleToArray(particle); } } void ParticleEmitter2D::UpdateParticles(float deltaSeconds) { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if(m_particles[i]) m_particles[i]->Update(deltaSeconds); } } void ParticleEmitter2D::DestroyParticles() { for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (m_particles[i] && !m_particles[i]->m_isAlive) { delete m_particles[i]; m_particles[i] = nullptr; m_currNumParticles--; } } } void ParticleEmitter2D::AddParticleToArray(Particle2D* particle) { bool foundASpot = false; for (uint i = 0; i < MAX_NUM_EMITTER_PARTICLES; i++) { if (!m_particles[i]) { m_particles[i] = particle; m_currNumParticles++; foundASpot = true; break; } } ASSERT_OR_DIE(foundASpot, "ERROR: Particle buffer too small to add particle"); }
32.367347
166
0.546974
ntaylorbishop
f46045c8cd0a5d9e8c8ffe7ece82652884d27dcc
2,164
hpp
C++
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
Logger/include/Logger/sink/log_sink.hpp
tmiguelf/Logger
7cf568a97711480a7ba23d5f6adeb49d05cd6f78
[ "MIT" ]
null
null
null
//======== ======== ======== ======== ======== ======== ======== ======== /// \file /// /// \copyright /// Copyright (c) 2020 Tiago Miguel Oliveira Freire /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. //======== ======== ======== ======== ======== ======== ======== ======== #pragma once #include <cstdint> #include <string_view> #include <CoreLib/Core_Time.hpp> #include <CoreLib/Core_Thread.hpp> #include <CoreLib/string/core_os_string.hpp> #include <Logger/log_level.hpp> namespace logger { /// \brief Holds the Logging data information struct log_data { core::os_string_view m_file; std::u8string_view m_line; std::u8string_view m_column; std::u8string_view m_date; std::u8string_view m_time; std::u8string_view m_thread; std::u8string_view m_level; std::u8string_view m_message; core::DateTime m_timeStruct; core::thread_id_t m_threadId; uint32_t m_lineNumber; uint32_t m_columnNumber; Level m_levelNumber; }; /// \brief Created to do Logging streams class log_sink { public: virtual void output(const log_data& p_logData) = 0; }; } // namespace simLog
32.298507
83
0.692699
tmiguelf
f464332a6ff3c22a903eee8dc0556f596c8578a1
988
hpp
C++
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
1
2018-10-27T05:07:05.000Z
2018-10-27T05:07:05.000Z
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
null
null
null
tests/app/src/opengl2/mordaren/OpenGL2Renderer.hpp
Mactor2018/morda
7194f973783b4472b8671fbb52e8c96e8c972b90
[ "MIT" ]
null
null
null
#pragma once #include <GL/glew.h> #include <morda/render/Renderer.hpp> #include "OpenGL2Factory.hpp" namespace mordaren{ class OpenGL2Renderer : public morda::Renderer{ GLuint defaultFramebuffer; public: OpenGL2Renderer(std::unique_ptr<OpenGL2Factory> factory = utki::makeUnique<OpenGL2Factory>()); OpenGL2Renderer(const OpenGL2Renderer& orig) = delete; OpenGL2Renderer& operator=(const OpenGL2Renderer& orig) = delete; void setFramebufferInternal(morda::FrameBuffer* fb) override; void clearFramebuffer()override; bool isScissorEnabled() const override; void setScissorEnabled(bool enabled) override; kolme::Recti getScissorRect() const override; void setScissorRect(kolme::Recti r) override; kolme::Recti getViewport()const override; void setViewport(kolme::Recti r) override; void setBlendEnabled(bool enable) override; void setBlendFunc(BlendFactor_e srcClr, BlendFactor_e dstClr, BlendFactor_e srcAlpha, BlendFactor_e dstAlpha) override; }; }
23.52381
120
0.783401
Mactor2018
f46455af60b3482d696ecb4c42ed31fd0639761d
16,398
hh
C++
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
null
null
null
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
null
null
null
src/cpu/kvm/base.hh
joerocklin/gem5
bc199672491f16e678c35d2187917738c24d6628
[ "BSD-3-Clause" ]
2
2018-11-06T18:41:38.000Z
2019-01-30T00:51:40.000Z
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Andreas Sandberg */ #ifndef __CPU_KVM_BASE_HH__ #define __CPU_KVM_BASE_HH__ #include <memory> #include "base/statistics.hh" #include "cpu/kvm/perfevent.hh" #include "cpu/kvm/timer.hh" #include "cpu/kvm/vm.hh" #include "cpu/base.hh" #include "cpu/simple_thread.hh" /** Signal to use to trigger time-based exits from KVM */ #define KVM_TIMER_SIGNAL SIGRTMIN // forward declarations class ThreadContext; struct BaseKvmCPUParams; /** * Base class for KVM based CPU models * * All architecture specific KVM implementation should inherit from * this class. The most basic CPU models only need to override the * updateKvmState() and updateThreadContext() methods to implement * state synchronization between gem5 and KVM. * * The architecture specific implementation is also responsible for * delivering interrupts into the VM. This is typically done by * overriding tick() and checking the thread context before entering * into the VM. In order to deliver an interrupt, the implementation * then calls KvmVM::setIRQLine() or BaseKvmCPU::kvmInterrupt() * depending on the specifics of the underlying hardware/drivers. */ class BaseKvmCPU : public BaseCPU { public: BaseKvmCPU(BaseKvmCPUParams *params); virtual ~BaseKvmCPU(); void init(); void startup(); void regStats(); void serializeThread(std::ostream &os, ThreadID tid); void unserializeThread(Checkpoint *cp, const std::string &section, ThreadID tid); unsigned int drain(DrainManager *dm); void drainResume(); void switchOut(); void takeOverFrom(BaseCPU *cpu); void verifyMemoryMode() const; CpuPort &getDataPort() { return dataPort; } CpuPort &getInstPort() { return instPort; } void wakeup(); void activateContext(ThreadID thread_num, Cycles delay); void suspendContext(ThreadID thread_num); void deallocateContext(ThreadID thread_num); void haltContext(ThreadID thread_num); ThreadContext *getContext(int tn); Counter totalInsts() const; Counter totalOps() const; /** Dump the internal state to the terminal. */ virtual void dump(); /** * A cached copy of a thread's state in the form of a SimpleThread * object. * * Normally the actual thread state is stored in the KVM vCPU. If KVM has * been running this copy is will be out of date. If we recently handled * some events within gem5 that required state to be updated this could be * the most up-to-date copy. When getContext() or updateThreadContext() is * called this copy gets updated. The method syncThreadContext can * be used within a KVM CPU to update the thread context if the * KVM state is dirty (i.e., the vCPU has been run since the last * update). */ SimpleThread *thread; /** ThreadContext object, provides an interface for external * objects to modify this thread's state. */ ThreadContext *tc; KvmVM &vm; protected: enum Status { /** Context not scheduled in KVM */ Idle, /** Running normally */ Running, }; /** CPU run state */ Status _status; /** * Execute the CPU until the next event in the main event queue or * until the guest needs service from gem5. * * @note This method is virtual in order to allow implementations * to check for architecture specific events (e.g., interrupts) * before entering the VM. */ virtual void tick(); /** * Request KVM to run the guest for a given number of ticks. The * method returns the approximate number of ticks executed. * * @note The returned number of ticks can be both larger or * smaller than the requested number of ticks. A smaller number * can, for example, occur when the guest executes MMIO. A larger * number is typically due to performance counter inaccuracies. * * @param ticks Number of ticks to execute * @return Number of ticks executed (see note) */ Tick kvmRun(Tick ticks); /** * Get a pointer to the kvm_run structure containing all the input * and output parameters from kvmRun(). */ struct kvm_run *getKvmRunState() { return _kvmRun; }; /** * Retrieve a pointer to guest data stored at the end of the * kvm_run structure. This is mainly used for PIO operations * (KVM_EXIT_IO). * * @param offset Offset as specified by the kvm_run structure * @return Pointer to guest data */ uint8_t *getGuestData(uint64_t offset) const { return (uint8_t *)_kvmRun + offset; }; /** * @addtogroup KvmInterrupts * @{ */ /** * Send a non-maskable interrupt to the guest * * @note The presence of this call depends on Kvm::capUserNMI(). */ void kvmNonMaskableInterrupt(); /** * Send a normal interrupt to the guest * * @note Make sure that ready_for_interrupt_injection in kvm_run * is set prior to calling this function. If not, an interrupt * window must be requested by setting request_interrupt_window in * kvm_run to 1 and restarting the guest. * * @param interrupt Structure describing the interrupt to send */ void kvmInterrupt(const struct kvm_interrupt &interrupt); /** @} */ /** @{ */ /** * Get/Set the register state of the guest vCPU * * KVM has two different interfaces for accessing the state of the * guest CPU. One interface updates 'normal' registers and one * updates 'special' registers. The distinction between special * and normal registers isn't very clear and is architecture * dependent. */ void getRegisters(struct kvm_regs &regs) const; void setRegisters(const struct kvm_regs &regs); void getSpecialRegisters(struct kvm_sregs &regs) const; void setSpecialRegisters(const struct kvm_sregs &regs); /** @} */ /** @{ */ /** * Get/Set the guest FPU/vector state */ void getFPUState(struct kvm_fpu &state) const; void setFPUState(const struct kvm_fpu &state); /** @} */ /** @{ */ /** * Get/Set single register using the KVM_(SET|GET)_ONE_REG API. * * @note The presence of this call depends on Kvm::capOneReg(). */ void setOneReg(uint64_t id, const void *addr); void setOneReg(uint64_t id, uint64_t value) { setOneReg(id, &value); } void setOneReg(uint64_t id, uint32_t value) { setOneReg(id, &value); } void getOneReg(uint64_t id, void *addr) const; uint64_t getOneRegU64(uint64_t id) const { uint64_t value; getOneReg(id, &value); return value; } uint32_t getOneRegU32(uint64_t id) const { uint32_t value; getOneReg(id, &value); return value; } /** @} */ /** * Get and format one register for printout. * * This function call getOneReg() to retrieve the contents of one * register and automatically formats it for printing. * * @note The presence of this call depends on Kvm::capOneReg(). */ std::string getAndFormatOneReg(uint64_t id) const; /** @{ */ /** * Update the KVM state from the current thread context * * The base CPU calls this method before starting the guest CPU * when the contextDirty flag is set. The architecture dependent * CPU implementation is expected to update all guest state * (registers, special registers, and FPU state). */ virtual void updateKvmState() = 0; /** * Update the current thread context with the KVM state * * The base CPU after the guest updates any of the KVM state. In * practice, this happens after kvmRun is called. The architecture * dependent code is expected to read the state of the guest CPU * and update gem5's thread state. */ virtual void updateThreadContext() = 0; /** * Update a thread context if the KVM state is dirty with respect * to the cached thread context. */ void syncThreadContext(); /** * Update the KVM if the thread context is dirty. */ void syncKvmState(); /** @} */ /** @{ */ /** * Main kvmRun exit handler, calls the relevant handleKvmExit* * depending on exit type. * * @return Number of ticks spent servicing the exit request */ virtual Tick handleKvmExit(); /** * The guest performed a legacy IO request (out/inp on x86) * * @return Number of ticks spent servicing the IO request */ virtual Tick handleKvmExitIO(); /** * The guest requested a monitor service using a hypercall * * @return Number of ticks spent servicing the hypercall */ virtual Tick handleKvmExitHypercall(); /** * The guest exited because an interrupt window was requested * * The guest exited because an interrupt window was requested * (request_interrupt_window in the kvm_run structure was set to 1 * before calling kvmRun) and it is now ready to receive * * @return Number of ticks spent servicing the IRQ */ virtual Tick handleKvmExitIRQWindowOpen(); /** * An unknown architecture dependent error occurred when starting * the vCPU * * The kvm_run data structure contains the hardware error * code. The defaults behavior of this method just prints the HW * error code and panics. Architecture dependent implementations * may want to override this method to provide better, * hardware-aware, error messages. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitUnknown(); /** * An unhandled virtualization exception occured * * Some KVM virtualization drivers return unhandled exceptions to * the user-space monitor. This interface is currently only used * by the Intel VMX KVM driver. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitException(); /** * KVM failed to start the virtualized CPU * * The kvm_run data structure contains the hardware-specific error * code. * * @return Number of ticks delay the next CPU tick */ virtual Tick handleKvmExitFailEntry(); /** @} */ /** * Inject a memory mapped IO request into gem5 * * @param paddr Physical address * @param data Pointer to the source/destination buffer * @param size Memory access size * @param write True if write, False if read * @return Number of ticks spent servicing the memory access */ Tick doMMIOAccess(Addr paddr, void *data, int size, bool write); /** * @addtogroup KvmIoctl * @{ */ /** * vCPU ioctl interface. * * @param request KVM vCPU request * @param p1 Optional request parameter * * @return -1 on error (error number in errno), ioctl dependent * value otherwise. */ int ioctl(int request, long p1) const; int ioctl(int request, void *p1) const { return ioctl(request, (long)p1); } int ioctl(int request) const { return ioctl(request, 0L); } /** @} */ /** Port for data requests */ CpuPort dataPort; /** Unused dummy port for the instruction interface */ CpuPort instPort; /** Pre-allocated MMIO memory request */ Request mmio_req; /** * Is the gem5 context dirty? Set to true to force an update of * the KVM vCPU state upon the next call to kvmRun(). */ bool threadContextDirty; /** * Is the KVM state dirty? Set to true to force an update of * the KVM vCPU state upon the next call to kvmRun(). */ bool kvmStateDirty; /** KVM internal ID of the vCPU */ const long vcpuID; private: struct TickEvent : public Event { BaseKvmCPU &cpu; TickEvent(BaseKvmCPU &c) : Event(CPU_Tick_Pri), cpu(c) {} void process() { cpu.tick(); } const char *description() const { return "BaseKvmCPU tick"; } }; /** * Service MMIO requests in the mmioRing. * * * @return Number of ticks spent servicing the MMIO requests in * the MMIO ring buffer */ Tick flushCoalescedMMIO(); /** * Setup a signal handler to catch the timer signal used to * switch back to the monitor. */ void setupSignalHandler(); /** Setup hardware performance counters */ void setupCounters(); /** KVM vCPU file descriptor */ int vcpuFD; /** Size of MMAPed kvm_run area */ int vcpuMMapSize; /** * Pointer to the kvm_run structure used to communicate parameters * with KVM. * * @note This is the base pointer of the MMAPed KVM region. The * first page contains the kvm_run structure. Subsequent pages may * contain other data such as the MMIO ring buffer. */ struct kvm_run *_kvmRun; /** * Coalesced MMIO ring buffer. NULL if coalesced MMIO is not * supported. */ struct kvm_coalesced_mmio_ring *mmioRing; /** Cached page size of the host */ const long pageSize; TickEvent tickEvent; /** @{ */ /** Guest performance counters */ PerfKvmCounter hwCycles; PerfKvmCounter hwInstructions; /** @} */ /** * Does the runTimer control the performance counters? * * The run timer will automatically enable and disable performance * counters if a PerfEvent-based timer is used to control KVM * exits. */ bool perfControlledByTimer; /** * Timer used to force execution into the monitor after a * specified number of simulation tick equivalents have executed * in the guest. This counter generates the signal specified by * KVM_TIMER_SIGNAL. */ std::unique_ptr<BaseKvmTimer> runTimer; float hostFactor; public: /* @{ */ Stats::Scalar numInsts; Stats::Scalar numVMExits; Stats::Scalar numMMIO; Stats::Scalar numCoalescedMMIO; Stats::Scalar numIO; Stats::Scalar numHalt; Stats::Scalar numInterrupts; Stats::Scalar numHypercalls; /* @} */ }; #endif
31.234286
78
0.664715
joerocklin
f467177ede885e9e945e308fb4afbee637655127
1,392
hpp
C++
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/op/PostRecofrienderV1RegistrationsByNetwork.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_op.hpp" #include <functional> #include "../def/RecofrienderUrlResource.hpp" namespace lol { template<typename T> inline Result<RecofrienderUrlResource> PostRecofrienderV1RegistrationsByNetwork(T& _client, const std::string& network) { try { return ToResult<RecofrienderUrlResource>(_client.https.request("post", "/recofriender/v1/registrations/"+to_string(network)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }))); } catch(const SimpleWeb::system_error &e) { return ToResult<RecofrienderUrlResource>(e.code()); } } template<typename T> inline void PostRecofrienderV1RegistrationsByNetwork(T& _client, const std::string& network, std::function<void(T&, const Result<RecofrienderUrlResource>&)> cb) { _client.httpsa.request("post", "/recofriender/v1/registrations/"+to_string(network)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }),[cb,&_client](std::shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &e) { if(e) cb(_client, ToResult<RecofrienderUrlResource>(e)); else cb(_client, ToResult<RecofrienderUrlResource>(response)); }); } }
42.181818
162
0.66523
Maufeat
c2e551d860206d075ffe8d70b56002208d5c2a5f
13,781
cpp
C++
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mx/core/elements/ArticulationsChoice.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mx/core/elements/ArticulationsChoice.h" #include "mx/core/FromXElement.h" #include "mx/core/elements/Accent.h" #include "mx/core/elements/BreathMark.h" #include "mx/core/elements/Caesura.h" #include "mx/core/elements/DetachedLegato.h" #include "mx/core/elements/Doit.h" #include "mx/core/elements/Falloff.h" #include "mx/core/elements/OtherArticulation.h" #include "mx/core/elements/Plop.h" #include "mx/core/elements/Scoop.h" #include "mx/core/elements/Spiccato.h" #include "mx/core/elements/Staccatissimo.h" #include "mx/core/elements/Staccato.h" #include "mx/core/elements/Stress.h" #include "mx/core/elements/StrongAccent.h" #include "mx/core/elements/Tenuto.h" #include "mx/core/elements/Unstress.h" #include <iostream> namespace mx { namespace core { ArticulationsChoice::ArticulationsChoice() :myChoice( Choice::accent ) ,myAccent( makeAccent() ) ,myStrongAccent( makeStrongAccent() ) ,myStaccato( makeStaccato() ) ,myTenuto( makeTenuto() ) ,myDetachedLegato( makeDetachedLegato() ) ,myStaccatissimo( makeStaccatissimo() ) ,mySpiccato( makeSpiccato() ) ,myScoop( makeScoop() ) ,myPlop( makePlop() ) ,myDoit( makeDoit() ) ,myFalloff( makeFalloff() ) ,myBreathMark( makeBreathMark() ) ,myCaesura( makeCaesura() ) ,myStress( makeStress() ) ,myUnstress( makeUnstress() ) ,myOtherArticulation( makeOtherArticulation() ) {} bool ArticulationsChoice::hasAttributes() const { return false; } std::ostream& ArticulationsChoice::streamAttributes( std::ostream& os ) const { return os; } std::ostream& ArticulationsChoice::streamName( std::ostream& os ) const { os << "articulations"; return os; } bool ArticulationsChoice::hasContents() const { return true; } std::ostream& ArticulationsChoice::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const { MX_UNUSED( isOneLineOnly ); switch ( myChoice ) { case Choice::accent: { myAccent->toStream( os, indentLevel ); } break; case Choice::strongAccent: { myStrongAccent->toStream( os, indentLevel ); } break; case Choice::staccato: { myStaccato->toStream( os, indentLevel ); } break; case Choice::tenuto: { myTenuto->toStream( os, indentLevel ); } break; case Choice::detachedLegato: { myDetachedLegato->toStream( os, indentLevel ); } break; case Choice::staccatissimo: { myStaccatissimo->toStream( os, indentLevel ); } break; case Choice::spiccato: { mySpiccato->toStream( os, indentLevel ); } break; case Choice::scoop: { myScoop->toStream( os, indentLevel ); } break; case Choice::plop: { myPlop->toStream( os, indentLevel ); } break; case Choice::doit: { myDoit->toStream( os, indentLevel ); } break; case Choice::falloff: { myFalloff->toStream( os, indentLevel ); } break; case Choice::breathMark: { myBreathMark->toStream( os, indentLevel ); } break; case Choice::caesura: { myCaesura->toStream( os, indentLevel ); } break; case Choice::stress: { myStress->toStream( os, indentLevel ); } break; case Choice::unstress: { myUnstress->toStream( os, indentLevel ); } break; case Choice::otherArticulation: { myOtherArticulation->toStream( os, indentLevel ); } break; default: break; } return os; } ArticulationsChoice::Choice ArticulationsChoice::getChoice() const { return myChoice; } void ArticulationsChoice::setChoice( const ArticulationsChoice::Choice value ) { myChoice = value; } AccentPtr ArticulationsChoice::getAccent() const { return myAccent; } void ArticulationsChoice::setAccent( const AccentPtr& value ) { if( value ) { myAccent = value; } } StrongAccentPtr ArticulationsChoice::getStrongAccent() const { return myStrongAccent; } void ArticulationsChoice::setStrongAccent( const StrongAccentPtr& value ) { if( value ) { myStrongAccent = value; } } StaccatoPtr ArticulationsChoice::getStaccato() const { return myStaccato; } void ArticulationsChoice::setStaccato( const StaccatoPtr& value ) { if( value ) { myStaccato = value; } } TenutoPtr ArticulationsChoice::getTenuto() const { return myTenuto; } void ArticulationsChoice::setTenuto( const TenutoPtr& value ) { if( value ) { myTenuto = value; } } DetachedLegatoPtr ArticulationsChoice::getDetachedLegato() const { return myDetachedLegato; } void ArticulationsChoice::setDetachedLegato( const DetachedLegatoPtr& value ) { if( value ) { myDetachedLegato = value; } } StaccatissimoPtr ArticulationsChoice::getStaccatissimo() const { return myStaccatissimo; } void ArticulationsChoice::setStaccatissimo( const StaccatissimoPtr& value ) { if( value ) { myStaccatissimo = value; } } SpiccatoPtr ArticulationsChoice::getSpiccato() const { return mySpiccato; } void ArticulationsChoice::setSpiccato( const SpiccatoPtr& value ) { if( value ) { mySpiccato = value; } } ScoopPtr ArticulationsChoice::getScoop() const { return myScoop; } void ArticulationsChoice::setScoop( const ScoopPtr& value ) { if( value ) { myScoop = value; } } PlopPtr ArticulationsChoice::getPlop() const { return myPlop; } void ArticulationsChoice::setPlop( const PlopPtr& value ) { if( value ) { myPlop = value; } } DoitPtr ArticulationsChoice::getDoit() const { return myDoit; } void ArticulationsChoice::setDoit( const DoitPtr& value ) { if( value ) { myDoit = value; } } FalloffPtr ArticulationsChoice::getFalloff() const { return myFalloff; } void ArticulationsChoice::setFalloff( const FalloffPtr& value ) { if( value ) { myFalloff = value; } } BreathMarkPtr ArticulationsChoice::getBreathMark() const { return myBreathMark; } void ArticulationsChoice::setBreathMark( const BreathMarkPtr& value ) { if( value ) { myBreathMark = value; } } CaesuraPtr ArticulationsChoice::getCaesura() const { return myCaesura; } void ArticulationsChoice::setCaesura( const CaesuraPtr& value ) { if( value ) { myCaesura = value; } } StressPtr ArticulationsChoice::getStress() const { return myStress; } void ArticulationsChoice::setStress( const StressPtr& value ) { if( value ) { myStress = value; } } UnstressPtr ArticulationsChoice::getUnstress() const { return myUnstress; } void ArticulationsChoice::setUnstress( const UnstressPtr& value ) { if( value ) { myUnstress = value; } } OtherArticulationPtr ArticulationsChoice::getOtherArticulation() const { return myOtherArticulation; } void ArticulationsChoice::setOtherArticulation( const OtherArticulationPtr& value ) { if( value ) { myOtherArticulation = value; } } bool ArticulationsChoice::fromXElementImpl( std::ostream& message, xml::XElement& xelement ) { if( xelement.getName() == "accent" ) { myChoice = Choice::accent; return getAccent()->fromXElement( message, xelement ); } if( xelement.getName() == "strong-accent" ) { myChoice = Choice::strongAccent; return getStrongAccent()->fromXElement( message, xelement ); } if( xelement.getName() == "staccato" ) { myChoice = Choice::staccato; return getStaccato()->fromXElement( message, xelement ); } if( xelement.getName() == "tenuto" ) { myChoice = Choice::tenuto; return getTenuto()->fromXElement( message, xelement ); } if( xelement.getName() == "detached-legato" ) { myChoice = Choice::detachedLegato; return getDetachedLegato()->fromXElement( message, xelement ); } if( xelement.getName() == "staccatissimo" ) { myChoice = Choice::staccatissimo; return getStaccatissimo()->fromXElement( message, xelement ); } if( xelement.getName() == "spiccato" ) { myChoice = Choice::spiccato; return getSpiccato()->fromXElement( message, xelement ); } if( xelement.getName() == "scoop" ) { myChoice = Choice::scoop; return getScoop()->fromXElement( message, xelement ); } if( xelement.getName() == "plop" ) { myChoice = Choice::plop; return getPlop()->fromXElement( message, xelement ); } if( xelement.getName() == "doit" ) { myChoice = Choice::doit; return getDoit()->fromXElement( message, xelement ); } if( xelement.getName() == "falloff" ) { myChoice = Choice::falloff; return getFalloff()->fromXElement( message, xelement ); } if( xelement.getName() == "breath-mark" ) { myChoice = Choice::breathMark; return getBreathMark()->fromXElement( message, xelement ); } if( xelement.getName() == "caesura" ) { myChoice = Choice::caesura; return getCaesura()->fromXElement( message, xelement ); } if( xelement.getName() == "stress" ) { myChoice = Choice::stress; return getStress()->fromXElement( message, xelement ); } if( xelement.getName() == "unstress" ) { myChoice = Choice::unstress; return getUnstress()->fromXElement( message, xelement ); } if( xelement.getName() == "other-articulation" ) { myChoice = Choice::otherArticulation; return getOtherArticulation()->fromXElement( message, xelement ); } message << "ArticulationsChoice: '" << xelement.getName() << "' is not allowed" << std::endl; return false; } } }
26.299618
127
0.465641
diskzero
c2e6174a44630e91dd32c8319bd19c32d7fff6fd
3,750
cpp
C++
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
src/PA02/MedianFiltering.cpp
pateldeev/cs474
4aeb7c6a5317256e9e1f517d614a83b5b52f9f52
[ "Xnet", "X11" ]
null
null
null
#include "PA02/HelperFunctions.h" #include "ReadWrite.h" #include <iostream> #include <ctime> #include <string> #include <algorithm> #include <sstream> // Corrupt the image with salt and pepper void saltPepperCorruption(const ImageType &, ImageType &, int); // Median filtering function void medianMask(const ImageType &, ImageType &, int); int main(int argc, char * argv[]){ if (argc != 3) { std::cout << "Incorrect number of arguments provided" << std::endl << "Please provide the image file and mask size in that order" << std::endl; return 0; } // Check to make sure argument is valid number std::istringstream ss(argv[2]); int medianFilterSize; if(!(ss >> medianFilterSize)){ std::cerr << "Invalid number\n"; return 0; } else if(!(ss.eof())){ std::cerr << "Trailing characters after number\n"; return 0; } //---------------------------------------------------------------------------- // Start reading image in int M, N, Q; // M = Columns, N = Rows, Q = Levels bool type; // P5 or P6 // Read header for image information readImageHeader(argv[1], N, M, Q, type); // Allocate memory for image ImageType image(N, M, Q); // Read in image information readImage(argv[1], image); //---------------------------------------------------------------------------- // Corrupt the image first ImageType corrupted_30(N, M, Q), corrupted_50(N, M, Q); saltPepperCorruption(image, corrupted_30, 30); std::string imageOutputName = "images/PA02/median/corrupted_30.pgm"; writeImage(imageOutputName.c_str(), corrupted_30); saltPepperCorruption(image, corrupted_50, 50); imageOutputName = "images/PA02/median/corrupted_50.pgm"; writeImage(imageOutputName.c_str(), corrupted_50); // Applying median filter to corrupted images ImageType medianFix_30(N, M, Q), medianFix_50(N, M, Q); medianMask(corrupted_30, medianFix_30, medianFilterSize); imageOutputName = "images/PA02/median/medianFix_30.pgm"; writeImage(imageOutputName.c_str(), medianFix_30); medianMask(corrupted_50, medianFix_50, medianFilterSize); imageOutputName = "images/PA02/median/medianFix_50.pgm"; writeImage(imageOutputName.c_str(), medianFix_50); return 0; } void saltPepperCorruption(const ImageType &og_image, ImageType &new_image, int percentage){ int numRows, numCols, numLevels, roll, tmpVal; og_image.getImageInfo(numRows, numCols, numLevels); srand(time(NULL)); for(int i = 0; i < numRows; ++i){ for(int j = 0; j < numCols; ++j){ roll = rand() % 100; if(roll < (percentage / 2)){ // Make it white new_image.setPixelVal(i, j, 255); } else if(roll > (percentage / 2) && roll < percentage){ // Make it black new_image.setPixelVal(i, j, 0); } else{ og_image.getPixelVal(i, j, tmpVal); new_image.setPixelVal(i, j, tmpVal); } } } } void medianMask(const ImageType &og_image, ImageType &new_image, int maskSize){ int values[maskSize * maskSize]; int imgRows, imgCols, imgLevels, valuesCounter = 0; int rowOffset, colOffset, rowLoc, colLoc, sortedMedianValue; og_image.getImageInfo(imgRows, imgCols, imgLevels); for(int i = 0; i < imgRows; ++i){ for(int j = 0; j < imgCols; ++j){ for(int k = 0; k < maskSize; ++k){ for(int l = 0; l < maskSize; ++l){ rowOffset = l - (maskSize / 2); colOffset = k - (maskSize / 2); rowLoc = i + rowOffset; colLoc = j + colOffset; if(rowLoc >= 0 && rowLoc < imgRows && colLoc >= 0 && colLoc < imgCols){ og_image.getPixelVal(rowLoc, colLoc, values[valuesCounter]); } valuesCounter++; } } std::sort(values, values + (maskSize * maskSize)); sortedMedianValue = values[(maskSize * maskSize) / 2]; new_image.setPixelVal(i, j, sortedMedianValue); valuesCounter = 0; } } }
29.296875
91
0.652
pateldeev
c2e80a0a4dd13a5aabb43f1b3dfc06f9b7c51670
5,233
cpp
C++
utils/wikistat-loader/main.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
3
2016-12-30T14:19:47.000Z
2021-11-13T06:58:32.000Z
utils/wikistat-loader/main.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
utils/wikistat-loader/main.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2021-02-07T16:00:54.000Z
2021-02-07T16:00:54.000Z
#include <boost/program_options.hpp> #include <DB/IO/ReadBuffer.h> #include <DB/IO/WriteBuffer.h> #include <DB/IO/ReadHelpers.h> #include <DB/IO/WriteHelpers.h> #include <DB/IO/ReadBufferFromFileDescriptor.h> #include <DB/IO/WriteBufferFromFileDescriptor.h> /** Reads uncompressed wikistat data from stdin, * and writes transformed data in tsv format, * ready to be loaded into ClickHouse. * * Input data has format: * * aa Wikipedia 1 17224 * aa.b Main_Page 2 21163 * * project, optional subproject, path, hits, total size in bytes. */ template <bool break_at_dot> static void readString(std::string & s, DB::ReadBuffer & buf) { s.clear(); while (!buf.eof()) { const char * next_pos; if (break_at_dot) next_pos = find_first_symbols<' ', '\n', '.'>(buf.position(), buf.buffer().end()); else next_pos = find_first_symbols<' ', '\n'>(buf.position(), buf.buffer().end()); s.append(buf.position(), next_pos - buf.position()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == ' ' || *buf.position() == '\n' || (break_at_dot && *buf.position() == '.')) return; } } /** Reads path before whitespace and decodes %xx sequences (to more compact and handy representation), * except %2F '/', %26 '&', %3D '=', %3F '?', %23 '#' (to not break structure of URL). */ static void readPath(std::string & s, DB::ReadBuffer & buf) { s.clear(); while (!buf.eof()) { const char * next_pos = find_first_symbols<' ', '\n', '%'>(buf.position(), buf.buffer().end()); s.append(buf.position(), next_pos - buf.position()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == ' ' || *buf.position() == '\n') return; if (*buf.position() == '%') { ++buf.position(); char c1; char c2; if (buf.eof() || *buf.position() == ' ') break; DB::readChar(c1, buf); if (buf.eof() || *buf.position() == ' ') break; DB::readChar(c2, buf); if ((c1 == '2' && (c2 == 'f' || c2 == '6' || c2 == '3' || c2 == 'F')) || (c1 == '3' && (c2 == 'd' || c2 == 'f' || c2 == 'D' || c2 == 'F'))) { s += '%'; s += c1; s += c2; } else s += static_cast<char>(static_cast<UInt8>(DB::unhex(c1)) * 16 + static_cast<UInt8>(DB::unhex(c2))); } } } static void skipUntilNewline(DB::ReadBuffer & buf) { while (!buf.eof()) { const char * next_pos = find_first_symbols<'\n'>(buf.position(), buf.buffer().end()); buf.position() += next_pos - buf.position(); if (!buf.hasPendingData()) continue; if (*buf.position() == '\n') { ++buf.position(); return; } } } namespace DB { namespace ErrorCodes { extern const int CANNOT_PARSE_INPUT_ASSERTION_FAILED; } } int main(int argc, char ** argv) try { boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("time", boost::program_options::value<std::string>()->required(), "time of data in YYYY-MM-DD hh:mm:ss form") ; boost::program_options::variables_map options; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), options); if (options.count("help")) { std::cout << "Reads uncompressed wikistat data from stdin and writes transformed data in tsv format." << std::endl; std::cout << "Usage: " << argv[0] << " --time='YYYY-MM-DD hh:00:00' < in > out" << std::endl; std::cout << desc << std::endl; return 1; } std::string time_str = options.at("time").as<std::string>(); LocalDateTime time(time_str); LocalDate date(time); DB::ReadBufferFromFileDescriptor in(STDIN_FILENO); DB::WriteBufferFromFileDescriptor out(STDOUT_FILENO); std::string project; std::string subproject; std::string path; UInt64 hits = 0; UInt64 size = 0; size_t row_num = 0; while (!in.eof()) { try { ++row_num; readString<true>(project, in); if (in.eof()) break; if (*in.position() == '.') readString<false>(subproject, in); else subproject.clear(); DB::assertChar(' ', in); readPath(path, in); DB::assertChar(' ', in); DB::readIntText(hits, in); DB::assertChar(' ', in); DB::readIntText(size, in); DB::assertChar('\n', in); } catch (const DB::Exception & e) { /// Sometimes, input data has errors. For example, look at first lines in pagecounts-20130210-130000.gz /// To save rest of data, just skip lines with errors. if (e.code() == DB::ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED) { std::cerr << "At row " << row_num << ": " << DB::getCurrentExceptionMessage(false) << '\n'; skipUntilNewline(in); continue; } else throw; } DB::writeText(date, out); DB::writeChar('\t', out); DB::writeText(time, out); DB::writeChar('\t', out); DB::writeText(project, out); DB::writeChar('\t', out); DB::writeText(subproject, out); DB::writeChar('\t', out); DB::writeText(path, out); DB::writeChar('\t', out); DB::writeText(hits, out); DB::writeChar('\t', out); DB::writeText(size, out); DB::writeChar('\n', out); } return 0; } catch (...) { std::cerr << DB::getCurrentExceptionMessage(true) << '\n'; throw; }
23.257778
117
0.611504
rudneff
c2ea6e86714e98c2dd15582c5eaf0de13f51164c
782
cpp
C++
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
7
2015-08-24T17:01:00.000Z
2021-03-30T09:30:40.000Z
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
1
2016-01-17T17:49:05.000Z
2016-01-17T17:49:05.000Z
libraries/physics/src/ContactInfo.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
1
2021-12-07T23:16:45.000Z
2021-12-07T23:16:45.000Z
// // ContactEvent.cpp // libraries/physcis/src // // Created by Andrew Meadows 2015.01.20 // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ContactInfo.h" void ContactInfo::update(uint32_t currentStep, const btManifoldPoint& p) { _lastStep = currentStep; ++_numSteps; positionWorldOnB = p.m_positionWorldOnB; normalWorldOnB = p.m_normalWorldOnB; distance = p.m_distance1; } ContactEventType ContactInfo::computeType(uint32_t thisStep) { if (_lastStep != thisStep) { return CONTACT_EVENT_TYPE_END; } return (_numSteps == 1) ? CONTACT_EVENT_TYPE_START : CONTACT_EVENT_TYPE_CONTINUE; }
27.928571
88
0.721228
stojce
c2eacebb56e52cde22eef90af868baf2404fa613
66
cpp
C++
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
src/array/destructor.cpp
violador/catalyst
40d5c1dd04269a0764a9804711354a474bc43c15
[ "Unlicense" ]
null
null
null
// // // inline ~array() { #pragma omp master delete[] data; };
7.333333
19
0.545455
violador
c2eda66913ce0805dfc4de582df933966e0a15e4
5,524
cpp
C++
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
Source/Core/Pipeline.cpp
milkru/foton
cf16abf02db80677ae22ff527aff5ef1c3702140
[ "MIT" ]
null
null
null
#include "Pipeline.h" #include "Device.h" #include "Swapchain.h" #include "DescriptorSet.h" #include "Shader.h" FT_BEGIN_NAMESPACE static void CreatePipelineLayout(const VkDevice inDevice, const VkDescriptorSetLayout inDescriptorSetLayout, VkPipelineLayout& outPipelineLayout) { VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{}; pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutCreateInfo.setLayoutCount = 1; pipelineLayoutCreateInfo.pSetLayouts = &inDescriptorSetLayout; FT_VK_CALL(vkCreatePipelineLayout(inDevice, &pipelineLayoutCreateInfo, nullptr, &outPipelineLayout)); } static void CreateGraphicsPipeline(const VkDevice inDevice, const Swapchain* inSwapchain, const Shader* inVertexShader, const Shader* inFragmentShader, const VkPipelineLayout inPipelineLayout, VkPipeline& outPraphicsPipeline) { VkPipelineShaderStageCreateInfo shaderStageCreateInfos[] = { inVertexShader->GetVkPipelineStageInfo(), inFragmentShader->GetVkPipelineStageInfo() }; VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo{}; vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo{}; inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE; VkViewport viewport{}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = static_cast<float>(inSwapchain->GetExtent().width); viewport.height = static_cast<float>(inSwapchain->GetExtent().height); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor{}; scissor.offset = { 0, 0 }; scissor.extent = inSwapchain->GetExtent(); VkPipelineViewportStateCreateInfo viewportStateCreateInfo{}; viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportStateCreateInfo.viewportCount = 1; viewportStateCreateInfo.pViewports = &viewport; viewportStateCreateInfo.scissorCount = 1; viewportStateCreateInfo.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizationStateCreateInfo{}; rasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizationStateCreateInfo.depthClampEnable = VK_FALSE; rasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE; rasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL; rasterizationStateCreateInfo.lineWidth = 1.0f; rasterizationStateCreateInfo.cullMode = VK_CULL_MODE_FRONT_BIT; rasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationStateCreateInfo.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampleStateCreateInfo{}; multisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampleStateCreateInfo.sampleShadingEnable = VK_FALSE; multisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlendStateCreateInfo{}; colorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlendStateCreateInfo.logicOpEnable = VK_FALSE; colorBlendStateCreateInfo.logicOp = VK_LOGIC_OP_COPY; colorBlendStateCreateInfo.attachmentCount = 1; colorBlendStateCreateInfo.pAttachments = &colorBlendAttachment; colorBlendStateCreateInfo.blendConstants[0] = 0.0f; colorBlendStateCreateInfo.blendConstants[1] = 0.0f; colorBlendStateCreateInfo.blendConstants[2] = 0.0f; colorBlendStateCreateInfo.blendConstants[3] = 0.0f; VkGraphicsPipelineCreateInfo pipelineCreateInfo{}; pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineCreateInfo.stageCount = 2; pipelineCreateInfo.pStages = shaderStageCreateInfos; pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo; pipelineCreateInfo.pViewportState = &viewportStateCreateInfo; pipelineCreateInfo.pRasterizationState = &rasterizationStateCreateInfo; pipelineCreateInfo.pMultisampleState = &multisampleStateCreateInfo; pipelineCreateInfo.pColorBlendState = &colorBlendStateCreateInfo; pipelineCreateInfo.layout = inPipelineLayout; pipelineCreateInfo.renderPass = inSwapchain->GetRenderPass(); pipelineCreateInfo.subpass = 0; pipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE; FT_VK_CALL(vkCreateGraphicsPipelines(inDevice, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &outPraphicsPipeline)); } Pipeline::Pipeline(const Device* inDevice, const Swapchain* inSwapchain, const DescriptorSet* inDescriptorSet, const Shader* inVertexShader, const Shader* inFragmentShader) : m_Device(inDevice) { CreatePipelineLayout(m_Device->GetDevice(), inDescriptorSet->GetDescriptorSetLayout(), m_PipelineLayout); CreateGraphicsPipeline(m_Device->GetDevice(), inSwapchain, inVertexShader, inFragmentShader, m_PipelineLayout, m_GraphicsPipeline); } Pipeline::~Pipeline() { vkDestroyPipeline(m_Device->GetDevice(), m_GraphicsPipeline, nullptr); vkDestroyPipelineLayout(m_Device->GetDevice(), m_PipelineLayout, nullptr); } FT_END_NAMESPACE
49.321429
225
0.857169
milkru
c2ee0f2a77e78dfb631f1695270fa8781d8cc0c2
1,903
cpp
C++
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
9
2018-03-05T15:07:44.000Z
2019-12-07T10:15:00.000Z
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
null
null
null
MerdogRT/interpreter/source/word_record.cpp
HttoHu/MerdogUWP
4d823f1c95b655151f8d972018d6caed33e187ee
[ "MIT" ]
1
2019-11-14T08:09:19.000Z
2019-11-14T08:09:19.000Z
/* * MIT License * Copyright (c) 2019 Htto Hu */ #include "../include/word_record.hpp" #include "../include/function.hpp" using namespace Mer; std::map<type_code_index, std::map<std::string, type_code_index>> type_op_type_map; void Mer::SymbolTable::end_block() { for (auto& a : data.front()) _rem_vec.push_back(a.second); data.pop_front(); } WordRecorder* Mer::SymbolTable::find(std::string id) { for (size_t i = 0; i < data.size(); i++) { auto result = data[i].find(id); if (result != data[i].end()) { return result->second; } } return nullptr; } void Mer::SymbolTable::push_glo(std::string id, WordRecorder* wr) { if (data.back().find(id) != data.back().end()) throw Error("id " + id + " redefined!"); data.back().insert({ id,wr }); } void Mer::SymbolTable::push(std::string id, WordRecorder* wr) { if (data.front().find(id) != data.front().end()) throw Error("id " + id + " redefined!"); data.front().insert({ id,wr }); } void Mer::SymbolTable::print() { for (const auto& a : data) { for (const auto& b : a) { std::cout << "ID:" << b.first << " TYPE:" << b.second->get_type() << std::endl;; } std::cout << "=================================\n"; } std::cout << "#########################################\n\n\n"; } Mer::SymbolTable::~SymbolTable() { for (auto a : _rem_vec) { delete a; } for (auto& a : data) { for (auto& b : a) { delete b.second; } } } FunctionBase* Mer::FuncIdRecorder::find(const std::vector<type_code_index>& pf) { if (dnt_check) return functions[std::vector<type_code_index>()]; if (functions.find(pf) == functions.end()) return nullptr; return functions[pf]; } Mer::FuncIdRecorder::FuncIdRecorder(FunctionBase* fb) :WordRecorder(ESymbol::SFUN, fb->get_type()), functions(compare_param_feature) {} Mer::FuncIdRecorder::~FuncIdRecorder() { for (auto& a : functions) { rem_functions.insert(a.second); } }
22.127907
135
0.612191
HttoHu
c2f216b53cbfc352125ed7c8d871df234488669a
376
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Serialization; // <Snippet1> public ref class Car { public: [XmlAttributeAttribute(Namespace="Make")] String^ MakerName; [XmlAttributeAttribute(Namespace="Model")] String^ ModelName; }; // </Snippet1>
16.347826
46
0.680851
hamarb123
c2f6288e1724985eb2d9ed4dc4e5350fa3115709
14,977
cpp
C++
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
11
2020-03-10T02:06:00.000Z
2022-02-17T19:59:50.000Z
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
null
null
null
Windows/WReformatRectifyDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
5
2020-05-30T00:59:22.000Z
2021-12-06T01:37:05.000Z
// MultiSpec // // Copyright 1988-2020 Purdue Research Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at: https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. // // MultiSpec is curated by the Laboratory for Applications of Remote Sensing at // Purdue University in West Lafayette, IN and licensed by Larry Biehl. // // File: WReformatRectifyDialog.cpp : implementation file // // Authors: Larry L. Biehl // // Revision date: 01/04/2018 // // Language: C++ // // System: Windows Operating System // // Brief description: This file contains functions that relate to the // CMReformatRectifyDlg class. // //------------------------------------------------------------------------------------ #include "SMultiSpec.h" #include "WReformatRectifyDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP (CMReformatRectifyDlg, CMDialog) //{{AFX_MSG_MAP (CMReformatRectifyDlg) ON_BN_CLICKED (IDC_ReprojectToRadio, OnBnClickedReprojectToRadio) ON_BN_CLICKED (IDC_TranslateScaleRotateRadio, OnBnClickedTranslateScaleRotateRadio) ON_BN_CLICKED (IDC_UseMapOrientationAngle, OnBnClickedUsemaporientationangle) ON_BN_CLICKED (IDEntireImage, ToEntireImage) ON_BN_CLICKED (IDSelectedImage, ToSelectedImage) ON_CBN_SELENDOK (IDC_ReferenceFileList, OnCbnSelendokTargetcombo) ON_CBN_SELENDOK (IDC_ResampleMethod, &CMReformatRectifyDlg::OnCbnSelendokResamplemethod) ON_EN_CHANGE (IDC_RotationClockwise, OnEnChangeRotationclockwise) //}}AFX_MSG_MAP END_MESSAGE_MAP () CMReformatRectifyDlg::CMReformatRectifyDlg ( CWnd* pParent /*=NULL*/) : CMDialog (CMReformatRectifyDlg::IDD, pParent) { //{{AFX_DATA_INIT (CMReformatRectifyDlg) m_backgroundValue = 0; m_lineShift = 0; m_columnShift = 0; m_columnScaleFactor = 0.0; m_lineScaleFactor = 0.0; m_rotationAngle = 0.0; m_blankOutsideSelectedAreaFlag = FALSE; m_headerListSelection = -1; m_channelSelection = -1; m_useMapOrientationAngleFlag = FALSE; m_procedureCode = 0; m_fileNamesSelection = -1; m_resampleSelection = 0; //}}AFX_DATA_INIT m_referenceWindowInfoHandle = NULL; m_initializedFlag = CMDialog::m_initializedFlag; } // end "CMReformatRectifyDlg" void CMReformatRectifyDlg::DoDataExchange ( CDataExchange* pDX) { CDialog::DoDataExchange (pDX); //{{AFX_DATA_MAP (CMReformatRectifyDlg) DDX_Text (pDX, IDC_ColumnEnd, m_ColumnEnd); DDV_MinMaxLong (pDX, m_ColumnEnd, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_ColumnStart, m_ColumnStart); DDV_MinMaxLong (pDX, m_ColumnStart, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_LineEnd, m_LineEnd); DDV_MinMaxLong (pDX, m_LineEnd, 1, m_maxNumberLines); DDX_Text (pDX, IDC_LineStart, m_LineStart); DDV_MinMaxLong (pDX, m_LineStart, 1, m_maxNumberLines); DDX_Text2 (pDX, IDC_BackgroundValue, m_backgroundValue); DDV_MinMaxDouble (pDX, m_backgroundValue, m_minBackgroundValue, m_maxBackgroundValue); DDX_Text (pDX, IDC_LineOffset, m_lineShift); DDV_MinMaxLong (pDX, m_lineShift, -100, 100); DDX_Text (pDX, IDC_ColumnOffset, m_columnShift); DDV_MinMaxLong (pDX, m_columnShift, -100, 100); DDX_Text2 (pDX, IDC_ColumnScale, m_columnScaleFactor); DDX_Text2 (pDX, IDC_LineScale, m_lineScaleFactor); DDX_Text2 (pDX, IDC_RotationClockwise, m_rotationAngle); DDV_MinMaxDouble (pDX, m_rotationAngle, -180., 180.); DDX_Check (pDX, IDC_NonSelectedPixels, m_blankOutsideSelectedAreaFlag); DDX_CBIndex (pDX, IDC_Header, m_headerListSelection); DDX_CBIndex (pDX, IDC_OutChannels, m_channelSelection); DDX_Check (pDX, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); DDX_Radio (pDX, IDC_TranslateScaleRotateRadio, m_procedureCode); DDX_CBIndex (pDX, IDC_ReferenceFileList, m_fileNamesSelection); DDX_CBIndex (pDX, IDC_ResampleMethod, m_resampleSelection); //}}AFX_DATA_MAP // Verify that the line and column values make sense VerifyLineColumnStartEndValues (pDX); if (pDX->m_bSaveAndValidate) { CComboBox* comboBoxPtr; comboBoxPtr = (CComboBox*)GetDlgItem (IDC_Header); m_headerOptionsSelection = (SInt16)(comboBoxPtr->GetItemData (m_headerListSelection)); comboBoxPtr = (CComboBox*)GetDlgItem (IDC_ResampleMethod); m_resampleMethodCode = (SInt16)comboBoxPtr->GetItemData (m_resampleSelection); } // end "if (pDX->m_bSaveAndValidate)" } // end "DoDataExchange" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void DoDialog // // Software purpose: The purpose of this routine is to present the reformat rectify // image specification dialog box to the user and copy the // revised information back to the reformat rectify specification // structure if the user selected OK. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 04/29/2005 // Revised By: Larry L. Biehl Date: 03/26/2006 Boolean CMReformatRectifyDlg::DoDialog ( FileInfoPtr outFileInfoPtr, FileInfoPtr fileInfoPtr, WindowInfoPtr imageWindowInfoPtr, LayerInfoPtr imageLayerInfoPtr, ReformatOptionsPtr reformatOptionsPtr, double minBackgroundValue, double maxBackgroundValue) { SInt64 returnCode; Boolean continueFlag = FALSE; // Make sure intialization has been completed. if (!m_initializedFlag) return (FALSE); m_outputFileInfoPtr = outFileInfoPtr; m_fileInfoPtr = fileInfoPtr; m_imageWindowInfoPtr = imageWindowInfoPtr; m_imageLayerInfoPtr = imageLayerInfoPtr; m_reformatOptionsPtr = reformatOptionsPtr; m_minBackgroundValue = minBackgroundValue; m_maxBackgroundValue = maxBackgroundValue; // Selected area for output file. m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.lineInterval = m_LineInterval; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; m_dialogSelectArea.columnInterval = m_ColumnInterval; returnCode = DoModal (); if (returnCode == IDOK) { continueFlag = TRUE; m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.lineInterval = 1; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; m_dialogSelectArea.columnInterval = 1; RectifyImageDialogOK (this, m_outputFileInfoPtr, m_fileInfoPtr, m_imageWindowInfoPtr, m_imageLayerInfoPtr, &m_dialogSelectArea, m_reformatOptionsPtr, (SInt16)m_headerOptionsSelection, (Boolean)m_blankOutsideSelectedAreaFlag, (SInt16)m_channelSelection, m_backgroundValue, (SInt16)(m_procedureCode+1), (SInt16)m_resampleMethodCode, m_referenceWindowInfoHandle, m_lineShift, m_columnShift, m_lineScaleFactor, m_columnScaleFactor, m_rotationAngle); } // end "if (returnCode == IDOK)" return (continueFlag); } // end "DoDialog" void CMReformatRectifyDlg::OnBnClickedReprojectToRadio () { m_procedureCode = kReprojectToReferenceImage - 1; UpdateProcedureItems (IDC_LineStart, TRUE); } // end "OnBnClickedReprojectToRadio" void CMReformatRectifyDlg::OnBnClickedTranslateScaleRotateRadio () { m_procedureCode = kTranslateScaleRotate - 1; UpdateProcedureItems (IDC_LineOffset, m_blankOutsideSelectedAreaFlag); } // end "OnBnClickedTranslateScaleRotateRadio" void CMReformatRectifyDlg::OnBnClickedUsemaporientationangle () { // Add your control notification handler code here DDX_Check (m_dialogFromPtr, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); m_rotationAngle = 0.; if (m_useMapOrientationAngleFlag) m_rotationAngle = m_mapOrientationAngle; DDX_Text2 (m_dialogToPtr, IDC_RotationClockwise, m_rotationAngle); } // end "OnBnClickedUsemaporientationangle" void CMReformatRectifyDlg::OnCbnSelendokResamplemethod () { SInt16 savedResampleSelection; // Select resampling method popup box if (m_resampleSelection >= 0) { savedResampleSelection = m_resampleSelection; DDX_CBIndex (m_dialogFromPtr, IDC_ResampleMethod, m_resampleSelection); } // end "if (m_resampleSelection >= 0)" } // end "OnCbnSelendokResamplemethod" void CMReformatRectifyDlg::OnCbnSelendokTargetcombo () { SInt16 savedFileNamesSelection; // Reference image to register against popup box if (m_fileNamesSelection >= 0) { savedFileNamesSelection = m_fileNamesSelection; DDX_CBIndex (m_dialogFromPtr, IDC_ReferenceFileList, m_fileNamesSelection); if (savedFileNamesSelection != m_fileNamesSelection) RectifyImageDialogOnReferenceFile (this, m_procedureCode+1, m_fileNamesSelection+1, &m_referenceWindowInfoHandle, &m_dialogSelectArea); } // end "if (m_fileNamesSelection >= 0)" } // end "OnCbnSelendokTargetcombo" void CMReformatRectifyDlg::OnEnChangeRotationclockwise () { // If this is a RICHEDIT control, the control will not // send this notification unless you override the CMDialog::OnInitDialog () // function and call CRichEditCtrl ().SetEventMask () // with the ENM_CHANGE flag ORed into the mask. // Add your control notification handler code here if (m_mapOrientationAngle != 0) { DDX_Text2 (m_dialogFromPtr, IDC_RotationClockwise, m_rotationAngle); if (m_rotationAngle == m_mapOrientationAngle) m_useMapOrientationAngleFlag = TRUE; else // m_rotationAngle != m_mapOrientationAngle m_useMapOrientationAngleFlag = FALSE; DDX_Check (m_dialogToPtr, IDC_UseMapOrientationAngle, m_useMapOrientationAngleFlag); } // end "if (m_mapOrientationAngle != 0)" } // end "OnEnChangeRotationclockwise" BOOL CMReformatRectifyDlg::OnInitDialog () { CComboBox* comboBoxPtr; SInt16 channelSelection, fileNamesSelection, procedureCode, resampleMethodCode; Boolean blankOutsideSelectedAreaFlag, mapInfoExistsFlag; CDialog::OnInitDialog (); // Add extra initialization here // Make sure that we have the bitmaps for the entire image buttons. VERIFY (toEntireButton.AutoLoad (IDEntireImage, this)); VERIFY (toSelectedButton.AutoLoad (IDSelectedImage, this)); RectifyImageDialogInitialize (this, m_fileInfoPtr, &m_dialogSelectArea, m_reformatOptionsPtr, &m_headerOptionsSelection, &channelSelection, &blankOutsideSelectedAreaFlag, &m_backgroundValue, &procedureCode, &resampleMethodCode, &fileNamesSelection, &m_referenceWindowInfoHandle, &m_lineShift, &m_columnShift, &m_lineScaleFactor, &m_columnScaleFactor, &m_rotationAngle, &m_mapOrientationAngle); m_LineStart = m_reformatOptionsPtr->lineStart; m_LineEnd = m_reformatOptionsPtr->lineEnd; m_ColumnStart = m_reformatOptionsPtr->columnStart; m_ColumnEnd = m_reformatOptionsPtr->columnEnd; m_blankOutsideSelectedAreaFlag = blankOutsideSelectedAreaFlag; m_procedureCode = procedureCode - 1; m_resampleMethodCode = resampleMethodCode; // Get the resample method list selection that matches the input // resample method code. m_resampleSelection = GetComboListSelection (IDC_ResampleMethod, m_resampleMethodCode); if (m_resampleSelection == -1) m_resampleSelection = 0; m_fileNamesSelection = fileNamesSelection - 1; // Set text indicating whether the output file format could be // GeoTIFF or TIFF. mapInfoExistsFlag = FindIfMapInformationExists (gImageWindowInfoPtr); comboBoxPtr = (CComboBox*)(GetDlgItem (IDC_Header)); comboBoxPtr->DeleteString (kTIFFGeoTIFFMenuItem); if (mapInfoExistsFlag) comboBoxPtr->InsertString (kTIFFGeoTIFFMenuItem, (LPCTSTR)_T("GeoTIFF format")); else // !mapInfoExistsFlag comboBoxPtr->InsertString (kTIFFGeoTIFFMenuItem, (LPCTSTR)_T("TIFF format")); comboBoxPtr->SetItemData (0, kNoneMenuItem); comboBoxPtr->SetItemData (1, kArcViewMenuItem); comboBoxPtr->SetItemData (2, kERDAS74MenuItem); comboBoxPtr->SetItemData (3, kGAIAMenuItem); comboBoxPtr->SetItemData (4, kTIFFGeoTIFFMenuItem); comboBoxPtr->SetItemData (5, kMatlabMenuItem); // Remove Matlab and ArcView options. comboBoxPtr->DeleteString (kMatlabMenuItem); comboBoxPtr->DeleteString (kGAIAMenuItem); m_headerListSelection = GetComboListSelection (IDC_Header, m_headerOptionsSelection); m_channelSelection = channelSelection; if (UpdateData (FALSE)) PositionDialogWindow (); // Set default text selection to first edit text item SelectDialogItemText (this, IDC_LineOffset, 0, SInt16_MAX); return FALSE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // end "OnInitDialog" void CMReformatRectifyDlg::UpdateProcedureItems ( int selectItemNumber, Boolean blankOutsideSelectedAreaFlag) { DDX_Radio (m_dialogToPtr, IDC_TranslateScaleRotateRadio, m_procedureCode); RectifyImageDialogOnRectifyCode (this, m_procedureCode+1, blankOutsideSelectedAreaFlag, m_mapOrientationAngle); RectifyImageDialogOnReferenceFile (this, m_procedureCode+1, m_fileNamesSelection+1, &m_referenceWindowInfoHandle, &m_dialogSelectArea); // Set default text selection to first edit text item SelectDialogItemText (this, selectItemNumber, 0, SInt16_MAX); } // end "OnCbnSelendokTargetcombo"
30.880412
89
0.700007
cas-nctu
c2f7051af23e47299601f57e987c6ad7ce511145
1,068
cpp
C++
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
1
2021-05-25T08:18:14.000Z
2021-05-25T08:18:14.000Z
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
7
2021-01-11T09:24:16.000Z
2021-05-25T16:04:19.000Z
libz80emu/iManager/iManager.cpp
Benji377/Z80Emu
cc0d12a267e16e1c03c7cc8ef35b70ef9b582e54
[ "Apache-2.0" ]
2
2021-01-19T14:53:55.000Z
2021-05-25T08:23:27.000Z
#include "iManager.h" IManager::IManager(Z80* z80){ FUN(); this->z80 = z80; this->iSet = new ISet(this->z80); } IManager::~IManager(){ FUN(); delete this->iSet; } Z80EmuInstrucion IManager::fetchIS(){ FUN(); if (this->ISLoaded){ LOGW("finalizeIS() was not called! Please call to clean up pointers!"); } //Read the opcode this->opcode = this->z80->readFromPCInc(); Z80EmuInstrucion curZ80EmuInstrucion = this->iSet->fetchZ80EmuInstrucion(this->opcode); return curZ80EmuInstrucion; } void IManager::execIS(Z80EmuInstrucion is){ FUN(); this->iSet->execIS(is); this->z80->addCycles(is.getCycles()); } void IManager::logIS(Z80EmuInstrucion is){ FUN(); uint8_t opcode = is[0]; std::string instruction = "(" + Log::toHexString(opcode) + ")"; for (size_t i = 1; i < is.size(); i++){ instruction += ";" + Log::toHexString(is[i]); } LOGD("Current instruction: " + instruction); } void IManager::finalizeIS(Z80EmuInstrucion is){ FUN(); this->ISLoaded = false; }
22.25
91
0.622659
Benji377
c2fa769dab75c7d73464dda82e4826a14d024651
1,056
hpp
C++
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
1
2018-12-24T07:13:05.000Z
2018-12-24T07:13:05.000Z
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
null
null
null
include/fingera/stream.hpp
fingera/fingera_header
fbda3515859eec269e6a67196276ac18251bdb49
[ "Apache-2.0" ]
null
null
null
/** * @brief 实现基础的Stream * * @file stream.hpp * @author liuyujun@fingera.cn * @date 2018-09-18 */ #pragma once #include <cstdint> #include <cstring> #include <stdexcept> #include <vector> namespace fingera { class write_stream { protected: std::vector<uint8_t> _data; public: write_stream() {} ~write_stream() {} inline void write(const void *data, size_t size) { const uint8_t *ptr = reinterpret_cast<const uint8_t *>(data); _data.insert(_data.end(), ptr, ptr + size); } inline std::vector<uint8_t> &data() { return _data; } }; class read_stream { protected: const std::vector<uint8_t> &_data; size_t _cursor; public: read_stream(const std::vector<uint8_t> &data) : _data(data), _cursor(0) {} ~read_stream() {} inline void read(void *buf, size_t size) { if (_cursor + size > _data.size()) { throw std::overflow_error("read_stream::read"); } memcpy(buf, &_data[_cursor], size); _cursor += size; } inline bool valid() { return _cursor < _data.size(); } }; } // namespace fingera
19.555556
76
0.651515
fingera
c2fdb03ea09747b4f3e5041388a71db3e156c7b7
1,537
hpp
C++
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItemArmor_TekPants_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemArmor_TekPants_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemArmor_TekPants.PrimalItemArmor_TekPants_C.OverrideCrouchingSound struct UPrimalItemArmor_TekPants_C_OverrideCrouchingSound_Params { class USoundBase** InSound; // (Parm, ZeroConstructor, IsPlainOldData) bool* bIsProne; // (Parm, ZeroConstructor, IsPlainOldData) int* soundState; // (Parm, ZeroConstructor, IsPlainOldData) class USoundBase* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PrimalItemArmor_TekPants.PrimalItemArmor_TekPants_C.ExecuteUbergraph_PrimalItemArmor_TekPants struct UPrimalItemArmor_TekPants_C_ExecuteUbergraph_PrimalItemArmor_TekPants_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
41.540541
173
0.50488
2bite
c2feb4e8a5fec1bde3f5acbb3603162c91e14111
4,285
cpp
C++
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
IvyProjects/IvyEngine/dx/DxBuffer.cpp
endy/Ivy
23d5a61d34793c74527ef803bf3693df79291539
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Ivy Engine /// /// Copyright 2010-2011, Brandon Light /// All rights reserved. /// /////////////////////////////////////////////////////////////////////////////////////////////////// #include "DxBuffer.h" #include <d3d11.h> /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::DxBuffer /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer::DxBuffer() { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::~DxBuffer /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer::~DxBuffer() { } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Create /////////////////////////////////////////////////////////////////////////////////////////////////// DxBuffer* DxBuffer::Create( ID3D11Device* pDevice, DxBufferCreateInfo* pCreateInfo) { DxBuffer* pNewBuffer = new DxBuffer(); if (pNewBuffer->Init(pDevice, pCreateInfo) == FALSE) { pNewBuffer->Destroy(); pNewBuffer = NULL; } return pNewBuffer; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Destroy /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::Destroy() { if (m_pDxBuffer) { m_pDxBuffer->Release(); } delete this; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Init /////////////////////////////////////////////////////////////////////////////////////////////////// BOOL DxBuffer::Init( ID3D11Device* pDevice, DxBufferCreateInfo* pCreateInfo) { D3D11_BUFFER_DESC bufferDesc; memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = pCreateInfo->elemSizeBytes; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.MiscFlags = 0; if (pCreateInfo->flags.cpuWriteable) { bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; } D3D11_SUBRESOURCE_DATA bufferInitData; memset(&bufferInitData, 0, sizeof(D3D11_SUBRESOURCE_DATA)); bufferInitData.pSysMem = pCreateInfo->pInitialData; bufferInitData.SysMemPitch = pCreateInfo->initialDataPitch; bufferInitData.SysMemSlicePitch = pCreateInfo->initialDataSlicePitch; pDevice->CreateBuffer(&bufferDesc, &bufferInitData, &m_pDxBuffer); return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Map /////////////////////////////////////////////////////////////////////////////////////////////////// VOID* DxBuffer::Map( ID3D11DeviceContext* pContext) { D3D11_MAPPED_SUBRESOURCE mappedBuffer; pContext->Map(m_pDxBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedBuffer); return mappedBuffer.pData; } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::Unmap /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::Unmap( ID3D11DeviceContext* pContext) { pContext->Unmap(m_pDxBuffer, 0); } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::BindVS /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::BindVS( ID3D11DeviceContext* pContext, UINT slot) { pContext->VSSetConstantBuffers(slot, 1, &m_pDxBuffer); } /////////////////////////////////////////////////////////////////////////////////////////////////// /// DxBuffer::BindPS /////////////////////////////////////////////////////////////////////////////////////////////////// VOID DxBuffer::BindPS( ID3D11DeviceContext* pContext, UINT slot) { pContext->PSSetConstantBuffers(slot, 1, &m_pDxBuffer); }
32.462121
99
0.365228
endy
6c0244634110a1519c681b39070a184245cf2763
860
cpp
C++
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
src/GameOverState.cpp
Natman64/BearAttack
77292fd38b45f3f21fdf4833ae653818f9e1cf00
[ "CC0-1.0" ]
null
null
null
#include "GameOverState.h" #include "GameState.h" namespace bears { GameOverState::GameOverState(Game* game, bool win) : loaded(false), game(game), win(win) { if (win) { text = "Congratulations! You killed all of the children in the name of the LORD."; } else { text = "Game over!"; } } void GameOverState::Update(const unsigned int deltaMS, Input& input) { if (input.IsAnyKeyPressed()) { if (win) game->Quit(); else game->SetState(new GameState(game)); } } void GameOverState::Draw(Graphics& graphics) { if (!loaded) { loaded = true; graphics.RenderText(text); } graphics.DrawText(text, 40, 500); } }
20
94
0.495349
Natman64
6c09dc1bf052e904475ee699ef6138caf8ee3a64
3,985
cpp
C++
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
3
2022-01-05T08:47:51.000Z
2022-01-06T12:42:18.000Z
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
null
null
null
Old/m4a_Plugin/m4aInfoManager.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
1
2022-01-06T16:12:58.000Z
2022-01-06T16:12:58.000Z
#include "stdafx.h" #include "m4ainfomanager.h" #include "mp4ff.h" #include "utils.h" static int GetAACTrack(mp4ff_t *infile) { /* find AAC track */ int i, rc; int numTracks = mp4ff_total_tracks(infile); for (i = 0; i < numTracks; i++) { unsigned char *buff = NULL; int buff_size = 0; mp4AudioSpecificConfig mp4ASC; mp4ff_get_decoder_config(infile, i, &buff, (unsigned int *)&buff_size); if (buff) { rc = NeAACDecAudioSpecificConfig(buff, buff_size, &mp4ASC); free(buff); if (rc < 0) continue; return i; } } /* can't decode this */ return -1; } static uint32_t read_callback(void *user_data, void *buffer, uint32_t length) { return fread(buffer, 1, length, (FILE*)user_data); } static uint32_t seek_callback(void *user_data, uint64_t position) { return fseek((FILE*)user_data, position, SEEK_SET); } static uint32_t write_callback(void *user_data, void *buffer, uint32_t length) { return fwrite(buffer, 1, length, (FILE*)user_data); } static uint32_t truncate_callback(void *user_data) { chsize(fileno((FILE*)user_data), ftell((FILE*)user_data)); return 1; } Cm4aInfoManager::Cm4aInfoManager(void) { } Cm4aInfoManager::~Cm4aInfoManager(void) { } void Cm4aInfoManager::Destroy(void) { delete this; } unsigned long Cm4aInfoManager::GetNumExtensions(void) { return 2; } LPTSTR Cm4aInfoManager::SupportedExtension(unsigned long ulExtentionNum) { static LPTSTR exts[] = { TEXT(".m4a"), TEXT(".mp4") }; return exts[ulExtentionNum]; } bool Cm4aInfoManager::CanHandle(LPTSTR szSource) { if(PathIsURL(szSource)) return(false); for(unsigned int x=0; x<GetNumExtensions(); x++) { if(!StrCmpI(SupportedExtension(x), PathFindExtension(szSource))) { return(true); } } return(false); } bool Cm4aInfoManager::GetInfo(LibraryEntry * libEnt) { char *pVal = NULL; FILE *mp4File; mp4ff_callback_t mp4cb = {0}; mp4ff_t *file; mp4File = _wfopen(libEnt->szURL, TEXT("rbS")); mp4cb.read = read_callback; mp4cb.seek = seek_callback; mp4cb.write = write_callback; mp4cb.truncate = truncate_callback; mp4cb.user_data = mp4File; // put info extraction here! file = mp4ff_open_read(&mp4cb); if (file == NULL) return false; if(mp4ff_meta_get_artist(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szArtist, 128); } if(mp4ff_meta_get_title(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szTitle, 128); } if(mp4ff_meta_get_album(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szAlbum, 128); } if(mp4ff_meta_get_genre(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szGenre, 128); } if(mp4ff_meta_get_comment(file, &pVal)) { MultiByteToWideChar(CP_UTF8, 0, pVal, strlen(pVal), libEnt->szComment, 128); } if(mp4ff_meta_get_track(file, &pVal)) { libEnt->dwTrack[0] = atoi(pVal); } if(mp4ff_meta_get_totaltracks(file, &pVal)) { libEnt->dwTrack[1] = atoi(pVal); } if(mp4ff_meta_get_date(file, &pVal)) { libEnt->iYear = atoi(pVal); } int track; if ((track = GetAACTrack(file)) < 0) { } libEnt->iSampleRate = mp4ff_get_sample_rate(file, track); libEnt->iBitRate = mp4ff_get_avg_bitrate(file, track); libEnt->iChannels = mp4ff_get_channel_count(file, track); unsigned long Samples = mp4ff_get_track_duration(file, track); libEnt->iPlaybackTime = (float)Samples / (float)(libEnt->iSampleRate/1000); mp4ff_close(file); fclose(mp4File); return true; } bool Cm4aInfoManager::SetInfo(LibraryEntry * libEnt) { return true; }
20.863874
80
0.633626
Harteex
6c0c63d2bc9f00fd0c98cc6409f37e333a929049
2,282
hpp
C++
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
include/outputformat.hpp
nnaumenko/metafjson
6cd7fdc0d888481bead5d1cc2cff29fb41934167
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020 Nick Naumenko (https://gitlab.com/nnaumenko, * https:://github.com/nnaumenko) * All rights reserved. * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef OUTPUTFORMAT_HPP #define OUTPUTFORMAT_HPP #include <iostream> #include <memory> #include "nlohmann/json_fwd.hpp" #include "datetimeformat.hpp" #include "valueformat.hpp" class Settings; namespace metaf { class Runway; class Temperature; class Speed; class Distance; class Direction; class Pressure; class Precipitation; class SurfaceFriction; class WaveHeight; enum class Weather; enum class WeatherDescriptor; struct ParseResult; } // namespace metaf class OutputFormat { public: OutputFormat(std::unique_ptr<const DateTimeFormat> dtFormat, std::unique_ptr<const ValueFormat> valFormat, bool rawStrings, int refYear, unsigned refMonth, unsigned refDay) : dateTimeFormat(std::move(dtFormat)), valueFormat(std::move(valFormat)), includeRawStrings(rawStrings), referenceYear(refYear), referenceMonth(refMonth), referenceDay(refDay) { } virtual ~OutputFormat() {} // Result of METAR or TAF report parsing and serialising to JSON enum class Result { OK, // Result parsed and serialised OK EXCEPTION // Exception occurred during parsing or serialising }; // Result toJson(const std::string &report, std::ostream &out = std::cout) const; protected: // Parse a METAR or TAF report and serialise to JSON virtual nlohmann::json toJson( const metaf::ParseResult &parseResult) const = 0; std::unique_ptr<const DateTimeFormat> dateTimeFormat; std::unique_ptr<const ValueFormat> valueFormat; bool getIncludeRawStrings() const { return includeRawStrings; } int getReferenceYear() const { return referenceYear; } int getReferenceMonth() const { return referenceMonth; } int getReferenceDay() const { return referenceDay; } private: bool includeRawStrings = false; int referenceYear = 0; int referenceMonth = 0; int referenceDay = 0; }; #endif //#ifndef OUTPUTFORMAT_HPP
27.166667
82
0.691937
nnaumenko
6c10fbdd2d044eb05045c14faf2bc6506da466f3
999
hpp
C++
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/AI/ArgumentMapping.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/IScriptable.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/ArgumentType.hpp> #include <RED4ext/Scripting/Natives/Generated/AI/ParameterizationType.hpp> namespace RED4ext { namespace AI { struct ArgumentMapping; } namespace AI { struct ArgumentMapping : IScriptable { static constexpr const char* NAME = "AIArgumentMapping"; static constexpr const char* ALIAS = NAME; Variant defaultValue; // 40 uint8_t unk58[0x5C - 0x58]; // 58 AI::ParameterizationType parameterizationType; // 5C AI::ArgumentType type; // 60 uint8_t unk64[0x68 - 0x64]; // 64 Handle<AI::ArgumentMapping> prefixValue; // 68 CName customTypeName; // 78 }; RED4EXT_ASSERT_SIZE(ArgumentMapping, 0x80); } // namespace AI } // namespace RED4ext
28.542857
74
0.742743
jackhumbert
6c116a9e2695047896718d2cee553286bfc56b7b
5,373
hpp
C++
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HAPI_TransformEuler.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: HoudiniEngineUnity.HAPI_XYZOrder #include "HoudiniEngineUnity/HAPI_XYZOrder.hpp" // Including type: HoudiniEngineUnity.HAPI_RSTOrder #include "HoudiniEngineUnity/HAPI_RSTOrder.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Forward declaring type: HAPI_TransformEuler struct HAPI_TransformEuler; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HAPI_TransformEuler, "HoudiniEngineUnity", "HAPI_TransformEuler"); // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Size: 0x28 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: HoudiniEngineUnity.HAPI_TransformEuler // [TokenAttribute] Offset: FFFFFFFF struct HAPI_TransformEuler/*, public ::System::ValueType*/ { public: public: // public System.Single[] position // Size: 0x8 // Offset: 0x0 ::ArrayW<float> position; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] rotationEuler // Size: 0x8 // Offset: 0x8 ::ArrayW<float> rotationEuler; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] scale // Size: 0x8 // Offset: 0x10 ::ArrayW<float> scale; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] shear // Size: 0x8 // Offset: 0x18 ::ArrayW<float> shear; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public HoudiniEngineUnity.HAPI_XYZOrder rotationOrder // Size: 0x4 // Offset: 0x20 ::HoudiniEngineUnity::HAPI_XYZOrder rotationOrder; // Field size check static_assert(sizeof(::HoudiniEngineUnity::HAPI_XYZOrder) == 0x4); // public HoudiniEngineUnity.HAPI_RSTOrder rstOrder // Size: 0x4 // Offset: 0x24 ::HoudiniEngineUnity::HAPI_RSTOrder rstOrder; // Field size check static_assert(sizeof(::HoudiniEngineUnity::HAPI_RSTOrder) == 0x4); public: // Creating value type constructor for type: HAPI_TransformEuler constexpr HAPI_TransformEuler(::ArrayW<float> position_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> rotationEuler_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> scale_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::ArrayW<float> shear_ = ::ArrayW<float>(static_cast<void*>(nullptr)), ::HoudiniEngineUnity::HAPI_XYZOrder rotationOrder_ = {}, ::HoudiniEngineUnity::HAPI_RSTOrder rstOrder_ = {}) noexcept : position{position_}, rotationEuler{rotationEuler_}, scale{scale_}, shear{shear_}, rotationOrder{rotationOrder_}, rstOrder{rstOrder_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.Single[] position ::ArrayW<float>& dyn_position(); // Get instance field reference: public System.Single[] rotationEuler ::ArrayW<float>& dyn_rotationEuler(); // Get instance field reference: public System.Single[] scale ::ArrayW<float>& dyn_scale(); // Get instance field reference: public System.Single[] shear ::ArrayW<float>& dyn_shear(); // Get instance field reference: public HoudiniEngineUnity.HAPI_XYZOrder rotationOrder ::HoudiniEngineUnity::HAPI_XYZOrder& dyn_rotationOrder(); // Get instance field reference: public HoudiniEngineUnity.HAPI_RSTOrder rstOrder ::HoudiniEngineUnity::HAPI_RSTOrder& dyn_rstOrder(); // public System.Void .ctor(System.Boolean initializeFields) // Offset: 0x16AA6E0 HAPI_TransformEuler(bool initializeFields); // public System.Void Init() // Offset: 0x16AA78C void Init(); }; // HoudiniEngineUnity.HAPI_TransformEuler #pragma pack(pop) static check_size<sizeof(HAPI_TransformEuler), 36 + sizeof(::HoudiniEngineUnity::HAPI_RSTOrder)> __HoudiniEngineUnity_HAPI_TransformEulerSizeCheck; static_assert(sizeof(HAPI_TransformEuler) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_TransformEuler::HAPI_TransformEuler // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_TransformEuler::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HAPI_TransformEuler::*)()>(&HoudiniEngineUnity::HAPI_TransformEuler::Init)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HAPI_TransformEuler), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
47.973214
584
0.729015
RedBrumbler
6c1ba257a16f8039573499420f9f1ce9037da361
4,180
cpp
C++
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
src/RInput.cpp
chilingg/redopera
c76d6e88c1f7bb0c048191c0c7eca41ed38754af
[ "MIT" ]
null
null
null
#include <RInput.h> using namespace Redopera; RSignal<bool, int> RInput::joyPresented; RSignal<int> RInput::wheeled; std::unordered_map<SDL_Joystick*, RInput::Joystick> RInput::joysticks_; RInput::Key RInput::key_; RInput::Mouse RInput::mouse_; void RInput::process(const SDL_Event &e) { switch(e.type) { case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: joysticks_.at(SDL_JoystickFromInstanceID(e.jbutton.which)).status_[e.jbutton.button] = e.jbutton.state == SDL_PRESSED ? R_PRESSED : R_RELEASED; break; case SDL_KEYDOWN: key_.status_[e.key.keysym.scancode] = e.key.repeat ? R_REPEAR : R_PRESSED; break; case SDL_KEYUP: key_.status_[e.key.keysym.scancode] = R_RELEASED; break; case SDL_MOUSEMOTION: mouse_.moved_ = true; break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if(e.button.state == SDL_PRESSED) mouse_.status_[e.button.button - 1] = e.button.clicks == 1 ? R_PRESSED : R_DOUBLECLICK; else mouse_.status_[e.button.button - 1] = R_RELEASED; break; case SDL_JOYDEVICEADDED: if(openJoystick(e.jdevice.which)) joyPresented.emit(true, SDL_JoystickGetDeviceInstanceID(e.jdevice.which)); break; case SDL_JOYDEVICEREMOVED: joyPresented.emit(false, e.jdevice.which); break; case SDL_MOUSEWHEEL: wheeled.emit(e.wheel.y); } } void RInput::updataClear() { for(auto &[jid, joy] : joysticks_) std::fill_n(joy.status_.get(), SDL_JoystickNumButtons(joy.joy_), R_NONE); std::for_each(key_.status_.begin(), key_.status_.end(), [](auto &it){ it.second = R_NONE; }); auto &key = key_; mouse_.moved_ = false; mouse_.status_ = { R_NONE, R_NONE, R_NONE }; } /* void RInput::initJoysticks() { for(int i = 0; i < SDL_NumJoysticks(); ++i) openJoystick(i); } */ SDL_Joystick* RInput::openJoystick(int device) { SDL_Joystick *joy = SDL_JoystickOpen(device); if(joy) { joysticks_[joy].joy_ = joy; joysticks_[joy].status_ = std::make_unique<int[]>(SDL_JoystickNumButtons(joy)); } return joy; } int RInput::Mouse::status(int *x, int *y) { return SDL_GetMouseState(&pos_.rx(), &pos_.ry()); } int RInput::Mouse::left() { return status_[0]; } int RInput::Mouse::middle() { return status_[1]; } int RInput::Mouse::right() { return status_[2]; } bool RInput::Mouse::move() { return moved_; } const RPoint2 &RInput::Mouse::pos() { SDL_GetMouseState(&pos_.rx(), &pos_.ry()); return pos_; } int RInput::Key::status(int key) { static int numkeys; static const uint8_t *kStatus = SDL_GetKeyboardState(&numkeys); if(key > 0 || key < numkeys) return kStatus[key]; else return R_NONE; } bool RInput::Key::press(int key) { if(status_.contains(key)) return status_[key] == R_PRESSED; else return false; } bool RInput::Key::release(int key) { if(status_.contains(key)) return status_[key] == R_RELEASED; else return false; } bool RInput::Key::repeat(int key) { if(status_.contains(key)) return status_[key] == R_REPEAR; else return false; } int RInput::Joystick::status(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn]; return R_NONE; } bool RInput::Joystick::press(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn] == R_PRESSED; return R_NONE; } bool RInput::Joystick::release(int btn) { if(btn > 0 || btn < SDL_JoystickNumButtons(joy_)) return status_[btn] == R_RELEASED; return R_NONE; } int RInput::Joystick::axis(int axis) { if(axis > 0 || axis < SDL_JoystickNumAxes(joy_)) return SDL_JoystickGetAxis(joy_, axis); else return 0; } int RInput::Joystick::rumble(unsigned low, unsigned high, unsigned ms) { return SDL_JoystickRumble(joy_, low, high, ms); } int RInput::Joystick::rumbleTriggers(unsigned left, unsigned right, unsigned ms) { return SDL_JoystickRumbleTriggers(joy_, left, right, ms); }
22.352941
99
0.640909
chilingg
6c1eadea3fcb04d352063da9fd78bf881707a984
1,096
cpp
C++
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
Gaia/Materials/material.cpp
tim0901/Gaia
ffe17ac9deedafd577ceb35efda37e7d573eeebd
[ "MIT" ]
null
null
null
#include "Material.h" Vec3d Reflect(const Vec3d& inDirection, const Vec3d& normal) { return unit_vector(2.0 * dot(inDirection, normal) * normal - inDirection); } bool Refract(const Vec3d& inDirection, const Vec3d& normal, const double& eta, Vec3d& outDirection) { Vec3d inBound = -inDirection; double cosTheta_i = dot(inDirection, normal); double descriminant = 1.0 - eta * eta * (1.0 - cosTheta_i * cosTheta_i); if (descriminant > 0.0) { outDirection = unit_vector(eta * inBound + (eta * cosTheta_i - sqrt(descriminant)) * normal); return true; } return false; } double Fresnel(Vec3d w_i, Vec3d n, double eta_t, double eta_i) { // Fresnel double eta_t2 = eta_t * eta_t; double eta_i2 = eta_i * eta_i; double c = abs(dot(w_i, n)); double gSquared = (eta_t2 / eta_i2) - 1.0 + (c * c); if (gSquared < 0.0) { // Return 1 if g is imaginary - total internal reflection return 1.0; } double g = sqrt(gSquared); return 0.5 * (((g - c) * (g - c)) / ((g + c) * (g + c))) * (1.0 + (((c * (g + c) - 1.0) * (c * (g + c) - 1.0)) / ((c * (g - c) + 1.0) * (c * (g - c) + 1.0)))); }
32.235294
160
0.620438
tim0901
6c22daa66cd3050a9d6952ce63ac6a871e1b33f3
1,541
cpp
C++
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day10-AdapterArray/test_Day10-AdapterArray.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day10-AdapterArray.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include "CppUnitTest.h" __END_LIBRARIES_DISABLE_WARNINGS using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace CurrentDay = AdventOfCode::Year2020::Day10; TEST_CLASS(Day10AdapterArray) { public: TEST_METHOD(numOneAndThreeJoltDifferencesMultiplied_SimpleTests) { Assert::AreEqual(7 * 5, CurrentDay::numOneAndThreeJoltDifferencesMultiplied(m_joltageRatingsShort)); Assert::AreEqual(22 * 10, CurrentDay::numOneAndThreeJoltDifferencesMultiplied(m_joltageRatingsLong)); } TEST_METHOD(numDistinctAdapterArrangements_SimpleTests) { Assert::AreEqual(8ll, CurrentDay::numDistinctAdapterArrangements(m_joltageRatingsShort)); Assert::AreEqual(19208ll, CurrentDay::numDistinctAdapterArrangements(m_joltageRatingsLong)); } private: std::vector<int> m_joltageRatingsShort = { 16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4 }; std::vector<int> m_joltageRatingsLong = { 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3 }; };
19.024691
109
0.5756
dbartok
6c2aff30b36928ef20331a4dee52752a14e8a654
2,123
cpp
C++
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
2
2016-12-12T15:32:27.000Z
2021-05-18T17:55:30.000Z
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
null
null
null
ui/src/clickandgoslider.cpp
joepadmiraal/qlcplus
ca7f083012c92eb4263bc38d957b2feda6d04185
[ "Apache-2.0" ]
null
null
null
/* Q Light Controller Plus clickandgoslider.cpp Copyright (c) Massimo Callegari 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.txt 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 "clickandgoslider.h" #include <QStyleOptionSlider> #include <QStyle> ClickAndGoSlider::ClickAndGoSlider(QWidget *parent) : QSlider(parent) { } void ClickAndGoSlider::setSliderStyleSheet(const QString &styleSheet) { if(isVisible()) QSlider::setStyleSheet(styleSheet); else m_styleSheet = styleSheet; } void ClickAndGoSlider::mousePressEvent ( QMouseEvent * event ) { if (event->modifiers() == Qt::ControlModifier) { emit controlClicked(); return; } QStyleOptionSlider opt; initStyleOption(&opt); QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); if (event->button() == Qt::LeftButton && // react only to left button press sr.contains(event->pos()) == false) // check if the click is not over the slider's handle { int newVal = 0; if (orientation() == Qt::Vertical) newVal = minimum() + ((maximum() - minimum()) * (height() - event->y())) / height(); else newVal = minimum() + ((maximum() - minimum()) * event->x()) / width(); if (invertedAppearance() == true) setValue( maximum() - newVal ); else setValue(newVal); event->accept(); } QSlider::mousePressEvent(event); } void ClickAndGoSlider::showEvent(QShowEvent *) { if (m_styleSheet.isEmpty() == false) { setSliderStyleSheet(m_styleSheet); m_styleSheet = ""; } }
28.306667
97
0.655205
joepadmiraal
6c2d3173c706cc5738410995563154f1f0f33f59
3,309
hh
C++
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
tests/InteractivityTest.hh
azjezz/hh-clilib
ef39116c527ac2496c985657f93af0253c9d8227
[ "MIT" ]
null
null
null
<?hh // strict /* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ namespace Facebook\CLILib; use namespace HH\Lib\{Tuple, Vec}; use function Facebook\FBExpect\expect; use type Facebook\CLILib\TestLib\{StringInput, StringOutput}; final class InteractivityTest extends TestCase { private function getCLI( ): (TestCLIWithoutArguments, StringInput, StringOutput, StringOutput) { $stdin = new StringInput(); $stdout = new StringOutput(); $stderr = new StringOutput(); $cli = new TestCLIWithoutArguments( vec[__FILE__, '--interactive'], new Terminal($stdin, $stdout, $stderr), ); return tuple($cli, $stdin, $stdout, $stderr); } public async function testClosedInput(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($ret)->toBeSame(0); expect($out->getBuffer())->toBeSame(''); expect($err->getBuffer())->toBeSame(''); } public async function testSingleCommandBeforeStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); $in->appendToBuffer("echo hello, world\n"); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($err->getBuffer())->toBeSame(''); expect($out->getBuffer())->toBeSame("> hello, world\n"); expect($ret)->toBeSame(0); } public async function testSingleCommandAfterStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); list($ret, $_) = await Tuple\from_async( $cli->mainAsync(), async { await \HH\Asio\later(); expect($out->getBuffer())->toBeSame('> '); $out->clearBuffer(); $in->appendToBuffer("exit 123\n"); }, ); expect($ret)->toBeSame(123); expect($out->getBuffer())->toBeSame(''); } public async function testMultipleCommandBeforeStart(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); $in->appendToBuffer("echo hello, world\n"); $in->appendToBuffer("echo foo bar\n"); $in->appendToBuffer("exit 123\n"); await $in->closeAsync(); $ret = await $cli->mainAsync(); expect($err->getBuffer())->toBeSame(''); expect($out->getBuffer())->toBeSame("> hello, world\n> foo bar\n> "); expect($ret)->toBeSame(123); } public async function testMultipleCommandsSequentially(): Awaitable<void> { list($cli, $in, $out, $err) = $this->getCLI(); list($ret, $_) = await Tuple\from_async( $cli->mainAsync(), async { await \HH\Asio\later(); expect($out->getBuffer())->toBeSame('> '); $out->clearBuffer(); $in->appendToBuffer("echo foo bar\n"); await \HH\Asio\later(); expect($out->getBuffer())->toBeSame("foo bar\n> "); $out->clearBuffer(); $in->appendToBuffer("echo herp derp\n"); await \HH\Asio\later(); expect($out->getBuffer())->toBeSame("herp derp\n> "); $out->clearBuffer(); $in->appendToBuffer("exit 42\n"); }, ); expect($ret)->toBeSame(42); expect($out->getBuffer())->toBeSame(''); expect($err->getBuffer())->toBeSame(''); } }
31.817308
77
0.607434
azjezz